blob: c3914d34198980e88c210842c2b2bae577c2be32 [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"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CXXABI.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000016#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/Attr.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000018#include "clang/AST/CharUnits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000019#include "clang/AST/Comment.h"
Dmitri Gribenkoca7f80a2012-08-09 00:03:17 +000020#include "clang/AST/CommentCommandTraits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000021#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000022#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000023#include "clang/AST/DeclTemplate.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000024#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000026#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000027#include "clang/AST/Mangle.h"
Reid Klecknerd8110b62013-09-10 20:14:30 +000028#include "clang/AST/MangleNumberingContext.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000029#include "clang/AST/RecordLayout.h"
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000030#include "clang/AST/RecursiveASTVisitor.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000031#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000032#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000033#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000034#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000035#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000036#include "llvm/ADT/StringExtras.h"
Robert Lyttoneaf6f362013-11-12 10:09:34 +000037#include "llvm/ADT/Triple.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000038#include "llvm/Support/Capacity.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000039#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000040#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000041#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000042
Chris Lattnerddc135e2006-11-10 06:34:16 +000043using namespace clang;
44
Douglas Gregor9672f922010-07-03 00:47:00 +000045unsigned ASTContext::NumImplicitDefaultConstructors;
46unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000047unsigned ASTContext::NumImplicitCopyConstructors;
48unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000049unsigned ASTContext::NumImplicitMoveConstructors;
50unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000051unsigned ASTContext::NumImplicitCopyAssignmentOperators;
52unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000053unsigned ASTContext::NumImplicitMoveAssignmentOperators;
54unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000055unsigned ASTContext::NumImplicitDestructors;
56unsigned ASTContext::NumImplicitDestructorsDeclared;
57
Steve Naroff0af91202007-04-27 21:51:21 +000058enum FloatingRank {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000059 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Steve Naroff0af91202007-04-27 21:51:21 +000060};
61
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000062RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000063 if (!CommentsLoaded && ExternalSource) {
64 ExternalSource->ReadComments();
65 CommentsLoaded = true;
66 }
67
68 assert(D);
69
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000070 // User can not attach documentation to implicit declarations.
71 if (D->isImplicit())
72 return NULL;
73
Dmitri Gribenkob2610882012-08-14 17:17:18 +000074 // User can not attach documentation to implicit instantiations.
75 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
76 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
77 return NULL;
78 }
79
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000080 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
81 if (VD->isStaticDataMember() &&
82 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
83 return NULL;
84 }
85
86 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
87 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
88 return NULL;
89 }
90
Dmitri Gribenko01b06512013-01-27 21:18:39 +000091 if (const ClassTemplateSpecializationDecl *CTSD =
92 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
93 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
94 if (TSK == TSK_ImplicitInstantiation ||
95 TSK == TSK_Undeclared)
96 return NULL;
97 }
98
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000099 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
100 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
101 return NULL;
102 }
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000103 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
104 // When tag declaration (but not definition!) is part of the
105 // decl-specifier-seq of some other declaration, it doesn't get comment
106 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
107 return NULL;
108 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000109 // TODO: handle comments for function parameters properly.
110 if (isa<ParmVarDecl>(D))
111 return NULL;
112
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000113 // TODO: we could look up template parameter documentation in the template
114 // documentation.
115 if (isa<TemplateTypeParmDecl>(D) ||
116 isa<NonTypeTemplateParmDecl>(D) ||
117 isa<TemplateTemplateParmDecl>(D))
118 return NULL;
119
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000120 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000121
122 // If there are no comments anywhere, we won't find anything.
123 if (RawComments.empty())
124 return NULL;
125
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000126 // Find declaration location.
127 // For Objective-C declarations we generally don't expect to have multiple
128 // declarators, thus use declaration starting location as the "declaration
129 // location".
130 // For all other declarations multiple declarators are used quite frequently,
131 // so we use the location of the identifier as the "declaration location".
132 SourceLocation DeclLoc;
133 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000134 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000135 isa<RedeclarableTemplateDecl>(D) ||
136 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000137 DeclLoc = D->getLocStart();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000138 else {
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000139 DeclLoc = D->getLocation();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000140 // If location of the typedef name is in a macro, it is because being
141 // declared via a macro. Try using declaration's starting location
142 // as the "declaration location".
143 if (DeclLoc.isMacroID() && isa<TypedefDecl>(D))
144 DeclLoc = D->getLocStart();
145 }
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000146
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000147 // If the declaration doesn't map directly to a location in a file, we
148 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000149 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
150 return NULL;
151
152 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000153 ArrayRef<RawComment *>::iterator Comment;
154 {
155 // When searching for comments during parsing, the comment we are looking
156 // for is usually among the last two comments we parsed -- check them
157 // first.
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +0000158 RawComment CommentAtDeclLoc(
159 SourceMgr, SourceRange(DeclLoc), false,
160 LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000161 BeforeThanCompare<RawComment> Compare(SourceMgr);
162 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
163 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
164 if (!Found && RawComments.size() >= 2) {
165 MaybeBeforeDecl--;
166 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
167 }
168
169 if (Found) {
170 Comment = MaybeBeforeDecl + 1;
171 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
172 &CommentAtDeclLoc, Compare));
173 } else {
174 // Slow path.
175 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
176 &CommentAtDeclLoc, Compare);
177 }
178 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000179
180 // Decompose the location for the declaration and find the beginning of the
181 // file buffer.
182 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
183
184 // First check whether we have a trailing comment.
185 if (Comment != RawComments.end() &&
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000186 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Fariborz Jahanianfad28542013-08-06 23:29:00 +0000187 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
Fariborz Jahanian3ab62222013-08-07 16:40:29 +0000188 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000189 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000190 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000191 // Check that Doxygen trailing comment comes after the declaration, starts
192 // on the same line and in the same file as the declaration.
193 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
194 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
195 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
196 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000197 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000198 }
199 }
200
201 // The comment just after the declaration was not a trailing comment.
202 // Let's look at the previous comment.
203 if (Comment == RawComments.begin())
204 return NULL;
205 --Comment;
206
207 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000208 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000209 return NULL;
210
211 // Decompose the end of the comment.
212 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000213 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000214
215 // If the comment and the declaration aren't in the same file, then they
216 // aren't related.
217 if (DeclLocDecomp.first != CommentEndDecomp.first)
218 return NULL;
219
220 // Get the corresponding buffer.
221 bool Invalid = false;
222 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
223 &Invalid).data();
224 if (Invalid)
225 return NULL;
226
227 // Extract text between the comment and declaration.
228 StringRef Text(Buffer + CommentEndDecomp.second,
229 DeclLocDecomp.second - CommentEndDecomp.second);
230
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000231 // There should be no other declarations or preprocessor directives between
232 // comment and declaration.
Argyrios Kyrtzidisb534d3a2013-07-26 18:38:12 +0000233 if (Text.find_first_of(";{}#@") != StringRef::npos)
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000234 return NULL;
235
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000236 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000237}
238
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000239namespace {
240/// If we have a 'templated' declaration for a template, adjust 'D' to
241/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000242/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000243const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregor35ceb272012-08-13 16:37:30 +0000244 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000245 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000246 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000247 return FTD;
248
249 // Nothing to do if function is not an implicit instantiation.
250 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
251 return D;
252
253 // Function is an implicit instantiation of a function template?
254 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
255 return FTD;
256
257 // Function is instantiated from a member definition of a class template?
258 if (const FunctionDecl *MemberDecl =
259 FD->getInstantiatedFromMemberFunction())
260 return MemberDecl;
261
262 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000263 }
Dmitri Gribenko90631802012-08-22 17:44:32 +0000264 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
265 // Static data member is instantiated from a member definition of a class
266 // template?
267 if (VD->isStaticDataMember())
268 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
269 return MemberDecl;
270
271 return D;
272 }
273 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
274 // Is this class declaration part of a class template?
275 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
276 return CTD;
277
278 // Class is an implicit instantiation of a class template or partial
279 // specialization?
280 if (const ClassTemplateSpecializationDecl *CTSD =
281 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
282 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
283 return D;
284 llvm::PointerUnion<ClassTemplateDecl *,
285 ClassTemplatePartialSpecializationDecl *>
286 PU = CTSD->getSpecializedTemplateOrPartial();
287 return PU.is<ClassTemplateDecl*>() ?
288 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
289 static_cast<const Decl*>(
290 PU.get<ClassTemplatePartialSpecializationDecl *>());
291 }
292
293 // Class is instantiated from a member definition of a class template?
294 if (const MemberSpecializationInfo *Info =
295 CRD->getMemberSpecializationInfo())
296 return Info->getInstantiatedFrom();
297
298 return D;
299 }
300 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
301 // Enum is instantiated from a member definition of a class template?
302 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
303 return MemberDecl;
304
305 return D;
306 }
307 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000308 return D;
309}
310} // unnamed namespace
311
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000312const RawComment *ASTContext::getRawCommentForAnyRedecl(
313 const Decl *D,
314 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000315 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000316
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000317 // Check whether we have cached a comment for this declaration already.
318 {
319 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
320 RedeclComments.find(D);
321 if (Pos != RedeclComments.end()) {
322 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000323 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
324 if (OriginalDecl)
325 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000326 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000327 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000328 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000329 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000330
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000331 // Search for comments attached to declarations in the redeclaration chain.
332 const RawComment *RC = NULL;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000333 const Decl *OriginalDeclForRC = NULL;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000334 for (Decl::redecl_iterator I = D->redecls_begin(),
335 E = D->redecls_end();
336 I != E; ++I) {
337 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
338 RedeclComments.find(*I);
339 if (Pos != RedeclComments.end()) {
340 const RawCommentAndCacheFlags &Raw = Pos->second;
341 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
342 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000343 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000344 break;
345 }
346 } else {
347 RC = getRawCommentForDeclNoCache(*I);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000348 OriginalDeclForRC = *I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000349 RawCommentAndCacheFlags Raw;
350 if (RC) {
351 Raw.setRaw(RC);
352 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
353 } else
354 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000355 Raw.setOriginalDecl(*I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000356 RedeclComments[*I] = Raw;
357 if (RC)
358 break;
359 }
360 }
361
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000362 // If we found a comment, it should be a documentation comment.
363 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000364
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000365 if (OriginalDecl)
366 *OriginalDecl = OriginalDeclForRC;
367
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000368 // Update cache for every declaration in the redeclaration chain.
369 RawCommentAndCacheFlags Raw;
370 Raw.setRaw(RC);
371 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000372 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000373
374 for (Decl::redecl_iterator I = D->redecls_begin(),
375 E = D->redecls_end();
376 I != E; ++I) {
377 RawCommentAndCacheFlags &R = RedeclComments[*I];
378 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
379 R = Raw;
380 }
381
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000382 return RC;
383}
384
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000385static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
386 SmallVectorImpl<const NamedDecl *> &Redeclared) {
387 const DeclContext *DC = ObjCMethod->getDeclContext();
388 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
389 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
390 if (!ID)
391 return;
392 // Add redeclared method here.
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000393 for (ObjCInterfaceDecl::known_extensions_iterator
394 Ext = ID->known_extensions_begin(),
395 ExtEnd = ID->known_extensions_end();
396 Ext != ExtEnd; ++Ext) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000397 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000398 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000399 ObjCMethod->isInstanceMethod()))
400 Redeclared.push_back(RedeclaredMethod);
401 }
402 }
403}
404
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000405comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
406 const Decl *D) const {
407 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
408 ThisDeclInfo->CommentDecl = D;
409 ThisDeclInfo->IsFilled = false;
410 ThisDeclInfo->fill();
411 ThisDeclInfo->CommentDecl = FC->getDecl();
412 comments::FullComment *CFC =
413 new (*this) comments::FullComment(FC->getBlocks(),
414 ThisDeclInfo);
415 return CFC;
416
417}
418
Richard Smithb39b9d52013-05-21 05:24:00 +0000419comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
420 const RawComment *RC = getRawCommentForDeclNoCache(D);
421 return RC ? RC->parse(*this, 0, D) : 0;
422}
423
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000424comments::FullComment *ASTContext::getCommentForDecl(
425 const Decl *D,
426 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000427 if (D->isInvalidDecl())
428 return NULL;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000429 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000430
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000431 const Decl *Canonical = D->getCanonicalDecl();
432 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
433 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000434
435 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000436 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000437 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000438 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000439 return CFC;
440 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000441 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000442 }
443
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000444 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000445
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000446 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000447 if (!RC) {
448 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000449 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000450 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000451 if (OMD && OMD->isPropertyAccessor())
452 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
453 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
454 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000455 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000456 addRedeclaredMethods(OMD, Overridden);
457 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000458 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
459 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
460 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000461 }
Fariborz Jahanian6384fbb2013-05-02 15:44:16 +0000462 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000463 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000464 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000465 QualType QT = TD->getUnderlyingType();
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000466 if (const TagType *TT = QT->getAs<TagType>())
467 if (const Decl *TD = TT->getDecl())
468 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000469 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000470 }
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000471 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
472 while (IC->getSuperClass()) {
473 IC = IC->getSuperClass();
474 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
475 return cloneFullComment(FC, D);
476 }
477 }
478 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
479 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
480 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
481 return cloneFullComment(FC, D);
482 }
483 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
484 if (!(RD = RD->getDefinition()))
485 return NULL;
486 // Check non-virtual bases.
487 for (CXXRecordDecl::base_class_const_iterator I =
488 RD->bases_begin(), E = RD->bases_end(); I != E; ++I) {
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000489 if (I->isVirtual() || (I->getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000490 continue;
491 QualType Ty = I->getType();
492 if (Ty.isNull())
493 continue;
494 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
495 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
496 continue;
497
498 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
499 return cloneFullComment(FC, D);
500 }
501 }
502 // Check virtual bases.
503 for (CXXRecordDecl::base_class_const_iterator I =
504 RD->vbases_begin(), E = RD->vbases_end(); I != E; ++I) {
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000505 if (I->getAccessSpecifier() != AS_public)
506 continue;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000507 QualType Ty = I->getType();
508 if (Ty.isNull())
509 continue;
510 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
511 if (!(VirtualBase= VirtualBase->getDefinition()))
512 continue;
513 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
514 return cloneFullComment(FC, D);
515 }
516 }
517 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000518 return NULL;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000519 }
520
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000521 // If the RawComment was attached to other redeclaration of this Decl, we
522 // should parse the comment in context of that other Decl. This is important
523 // because comments can contain references to parameter names which can be
524 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000525 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000526 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000527
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000528 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000529 ParsedComments[Canonical] = FC;
530 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000531}
532
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000533void
534ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
535 TemplateTemplateParmDecl *Parm) {
536 ID.AddInteger(Parm->getDepth());
537 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000538 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000539
540 TemplateParameterList *Params = Parm->getTemplateParameters();
541 ID.AddInteger(Params->size());
542 for (TemplateParameterList::const_iterator P = Params->begin(),
543 PEnd = Params->end();
544 P != PEnd; ++P) {
545 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
546 ID.AddInteger(0);
547 ID.AddBoolean(TTP->isParameterPack());
548 continue;
549 }
550
551 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
552 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000553 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000554 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000555 if (NTTP->isExpandedParameterPack()) {
556 ID.AddBoolean(true);
557 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000558 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
559 QualType T = NTTP->getExpansionType(I);
560 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
561 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000562 } else
563 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000564 continue;
565 }
566
567 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
568 ID.AddInteger(2);
569 Profile(ID, TTP);
570 }
571}
572
573TemplateTemplateParmDecl *
574ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000575 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000576 // Check if we already have a canonical template template parameter.
577 llvm::FoldingSetNodeID ID;
578 CanonicalTemplateTemplateParm::Profile(ID, TTP);
579 void *InsertPos = 0;
580 CanonicalTemplateTemplateParm *Canonical
581 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
582 if (Canonical)
583 return Canonical->getParam();
584
585 // Build a canonical template parameter list.
586 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000587 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000588 CanonParams.reserve(Params->size());
589 for (TemplateParameterList::const_iterator P = Params->begin(),
590 PEnd = Params->end();
591 P != PEnd; ++P) {
592 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
593 CanonParams.push_back(
594 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000595 SourceLocation(),
596 SourceLocation(),
597 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000598 TTP->getIndex(), 0, false,
599 TTP->isParameterPack()));
600 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000601 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
602 QualType T = getCanonicalType(NTTP->getType());
603 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
604 NonTypeTemplateParmDecl *Param;
605 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000606 SmallVector<QualType, 2> ExpandedTypes;
607 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000608 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
609 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
610 ExpandedTInfos.push_back(
611 getTrivialTypeSourceInfo(ExpandedTypes.back()));
612 }
613
614 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000615 SourceLocation(),
616 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000617 NTTP->getDepth(),
618 NTTP->getPosition(), 0,
619 T,
620 TInfo,
621 ExpandedTypes.data(),
622 ExpandedTypes.size(),
623 ExpandedTInfos.data());
624 } else {
625 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000626 SourceLocation(),
627 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000628 NTTP->getDepth(),
629 NTTP->getPosition(), 0,
630 T,
631 NTTP->isParameterPack(),
632 TInfo);
633 }
634 CanonParams.push_back(Param);
635
636 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000637 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
638 cast<TemplateTemplateParmDecl>(*P)));
639 }
640
641 TemplateTemplateParmDecl *CanonTTP
642 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
643 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000644 TTP->getPosition(),
645 TTP->isParameterPack(),
646 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000647 TemplateParameterList::Create(*this, SourceLocation(),
648 SourceLocation(),
649 CanonParams.data(),
650 CanonParams.size(),
651 SourceLocation()));
652
653 // Get the new insert position for the node we care about.
654 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
655 assert(Canonical == 0 && "Shouldn't be in the map!");
656 (void)Canonical;
657
658 // Create the canonical template template parameter entry.
659 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
660 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
661 return CanonTTP;
662}
663
Charles Davis53c59df2010-08-16 03:33:14 +0000664CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000665 if (!LangOpts.CPlusPlus) return 0;
666
John McCall359b8852013-01-25 22:30:49 +0000667 switch (T.getCXXABI().getKind()) {
668 case TargetCXXABI::GenericARM:
669 case TargetCXXABI::iOS:
John McCall86353412010-08-21 22:46:04 +0000670 return CreateARMCXXABI(*this);
Tim Northover9bb857a2013-01-31 12:13:10 +0000671 case TargetCXXABI::GenericAArch64: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000672 case TargetCXXABI::GenericItanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000673 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000674 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000675 return CreateMicrosoftCXXABI(*this);
676 }
David Blaikie8a40f702012-01-17 06:56:22 +0000677 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000678}
679
Douglas Gregore8bbc122011-09-02 00:18:52 +0000680static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000681 const LangOptions &LOpts) {
682 if (LOpts.FakeAddressSpaceMap) {
683 // The fake address space map must have a distinct entry for each
684 // language-specific address space.
685 static const unsigned FakeAddrSpaceMap[] = {
686 1, // opencl_global
687 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000688 3, // opencl_constant
689 4, // cuda_device
690 5, // cuda_constant
691 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000692 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000693 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000694 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000695 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000696 }
697}
698
David Tweed31d09b02013-09-13 12:04:22 +0000699static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
700 const LangOptions &LangOpts) {
701 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000702 case LangOptions::ASMM_Target:
703 return TI.useAddressSpaceMapMangling();
704 case LangOptions::ASMM_On:
705 return true;
706 case LangOptions::ASMM_Off:
707 return false;
708 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000709 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000710}
711
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000712ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000713 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000714 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000715 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000716 unsigned size_reserve,
717 bool DelayInitialization)
718 : FunctionProtoTypes(this_()),
719 TemplateSpecializationTypes(this_()),
720 DependentTemplateSpecializationTypes(this_()),
721 SubstTemplateTemplateParmPacks(this_()),
722 GlobalNestedNameSpecifier(0),
Nico Webere1687c52013-06-20 21:44:55 +0000723 Int128Decl(0), UInt128Decl(0), Float128StubDecl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000724 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000725 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanianf2578572012-08-30 18:49:41 +0000726 BOOLDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000727 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000728 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000729 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
730 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
731 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000732 NullTypeSourceInfo(QualType()),
733 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000734 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000735 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000736 Idents(idents), Selectors(sels),
737 BuiltinInfo(builtins),
738 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000739 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000740 Comments(SM), CommentsLoaded(false),
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000741 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
Rafael Espindolace2168f2013-05-29 19:51:12 +0000742 LastSDM(0, 0)
Douglas Gregore8bbc122011-09-02 00:18:52 +0000743{
Mike Stump11289f42009-09-09 15:08:12 +0000744 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000745 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000746
747 if (!DelayInitialization) {
748 assert(t && "No target supplied for ASTContext initialization");
749 InitBuiltinTypes(*t);
750 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000751}
752
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000753ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000754 // Release the DenseMaps associated with DeclContext objects.
755 // FIXME: Is this the ideal solution?
756 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000757
Manuel Klimeka7328992013-06-03 13:51:33 +0000758 // Call all of the deallocation functions on all of their targets.
759 for (DeallocationMap::const_iterator I = Deallocations.begin(),
760 E = Deallocations.end(); I != E; ++I)
761 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
762 (I->first)((I->second)[J]);
763
Ted Kremenek076baeb2010-06-08 23:00:58 +0000764 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000765 // because they can contain DenseMaps.
766 for (llvm::DenseMap<const ObjCContainerDecl*,
767 const ASTRecordLayout*>::iterator
768 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
769 // Increment in loop to prevent using deallocated memory.
770 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
771 R->Destroy(*this);
772
Ted Kremenek076baeb2010-06-08 23:00:58 +0000773 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
774 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
775 // Increment in loop to prevent using deallocated memory.
776 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
777 R->Destroy(*this);
778 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000779
780 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
781 AEnd = DeclAttrs.end();
782 A != AEnd; ++A)
783 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000784
785 for (llvm::DenseMap<const DeclContext *, MangleNumberingContext *>::iterator
786 I = MangleNumberingContexts.begin(),
787 E = MangleNumberingContexts.end();
788 I != E; ++I)
789 delete I->second;
Douglas Gregor561eceb2010-08-30 16:49:28 +0000790}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000791
Douglas Gregor1a809332010-05-23 18:26:36 +0000792void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimeka7328992013-06-03 13:51:33 +0000793 Deallocations[Callback].push_back(Data);
Douglas Gregor1a809332010-05-23 18:26:36 +0000794}
795
Mike Stump11289f42009-09-09 15:08:12 +0000796void
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000797ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000798 ExternalSource.reset(Source.take());
799}
800
Chris Lattner4eb445d2007-01-26 01:27:23 +0000801void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000802 llvm::errs() << "\n*** AST Context Stats:\n";
803 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000804
Douglas Gregora30d0462009-05-26 14:40:08 +0000805 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000806#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000807#define ABSTRACT_TYPE(Name, Parent)
808#include "clang/AST/TypeNodes.def"
809 0 // Extra
810 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000811
Chris Lattner4eb445d2007-01-26 01:27:23 +0000812 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
813 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000814 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000815 }
816
Douglas Gregora30d0462009-05-26 14:40:08 +0000817 unsigned Idx = 0;
818 unsigned TotalBytes = 0;
819#define TYPE(Name, Parent) \
820 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000821 llvm::errs() << " " << counts[Idx] << " " << #Name \
822 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000823 TotalBytes += counts[Idx] * sizeof(Name##Type); \
824 ++Idx;
825#define ABSTRACT_TYPE(Name, Parent)
826#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000827
Chandler Carruth3c147a72011-07-04 05:32:14 +0000828 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
829
Douglas Gregor7454c562010-07-02 20:37:36 +0000830 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000831 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
832 << NumImplicitDefaultConstructors
833 << " implicit default constructors created\n";
834 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
835 << NumImplicitCopyConstructors
836 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000837 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000838 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
839 << NumImplicitMoveConstructors
840 << " implicit move constructors created\n";
841 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
842 << NumImplicitCopyAssignmentOperators
843 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000844 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000845 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
846 << NumImplicitMoveAssignmentOperators
847 << " implicit move assignment operators created\n";
848 llvm::errs() << NumImplicitDestructorsDeclared << "/"
849 << NumImplicitDestructors
850 << " implicit destructors created\n";
851
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000852 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000853 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000854 ExternalSource->PrintStats();
855 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000856
Douglas Gregor5b11d492010-07-25 17:53:33 +0000857 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000858}
859
Alp Toker2dea15b2013-12-17 01:22:38 +0000860RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
861 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000862 SourceLocation Loc;
863 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +0000864 if (getLangOpts().CPlusPlus)
865 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
866 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000867 else
Alp Toker2dea15b2013-12-17 01:22:38 +0000868 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
869 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000870 NewDecl->setImplicit();
871 return NewDecl;
872}
873
874TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
875 StringRef Name) const {
876 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
877 TypedefDecl *NewDecl = TypedefDecl::Create(
878 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
879 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
880 NewDecl->setImplicit();
881 return NewDecl;
882}
883
Douglas Gregor801c99d2011-08-12 06:49:56 +0000884TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000885 if (!Int128Decl)
886 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000887 return Int128Decl;
888}
889
890TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000891 if (!UInt128Decl)
892 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000893 return UInt128Decl;
894}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000895
Nico Webere1687c52013-06-20 21:44:55 +0000896TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber5b0b46f2013-06-21 01:29:36 +0000897 assert(LangOpts.CPlusPlus && "should only be called for c++");
Alp Toker56b5cc92013-12-15 10:36:26 +0000898 if (!Float128StubDecl)
Alp Toker2dea15b2013-12-17 01:22:38 +0000899 Float128StubDecl = buildImplicitRecord("__float128");
Alp Toker56b5cc92013-12-15 10:36:26 +0000900
Nico Webere1687c52013-06-20 21:44:55 +0000901 return Float128StubDecl;
902}
903
John McCall48f2d582009-10-23 23:03:21 +0000904void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000905 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000906 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000907 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000908}
909
Douglas Gregore8bbc122011-09-02 00:18:52 +0000910void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
911 assert((!this->Target || this->Target == &Target) &&
912 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000913 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000914
Douglas Gregore8bbc122011-09-02 00:18:52 +0000915 this->Target = &Target;
916
917 ABI.reset(createCXXABI(Target));
918 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +0000919 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000920
Chris Lattner970e54e2006-11-12 00:37:36 +0000921 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000922 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000923
Chris Lattner970e54e2006-11-12 00:37:36 +0000924 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000925 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000926 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000927 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000928 InitBuiltinType(CharTy, BuiltinType::Char_S);
929 else
930 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000931 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000932 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
933 InitBuiltinType(ShortTy, BuiltinType::Short);
934 InitBuiltinType(IntTy, BuiltinType::Int);
935 InitBuiltinType(LongTy, BuiltinType::Long);
936 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000937
Chris Lattner970e54e2006-11-12 00:37:36 +0000938 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000939 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
940 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
941 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
942 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
943 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000944
Chris Lattner970e54e2006-11-12 00:37:36 +0000945 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000946 InitBuiltinType(FloatTy, BuiltinType::Float);
947 InitBuiltinType(DoubleTy, BuiltinType::Double);
948 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000949
Chris Lattnerf122cef2009-04-30 02:43:43 +0000950 // GNU extension, 128-bit integers.
951 InitBuiltinType(Int128Ty, BuiltinType::Int128);
952 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
953
Hans Wennborg0d81e012013-05-10 10:08:40 +0000954 // C++ 3.9.1p5
955 if (TargetInfo::isTypeSigned(Target.getWCharType()))
956 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
957 else // -fshort-wchar makes wchar_t be unsigned.
958 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
959 if (LangOpts.CPlusPlus && LangOpts.WChar)
960 WideCharTy = WCharTy;
961 else {
962 // C99 (or C++ using -fno-wchar).
963 WideCharTy = getFromTargetType(Target.getWCharType());
964 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000965
James Molloy36365542012-05-04 10:55:22 +0000966 WIntTy = getFromTargetType(Target.getWIntType());
967
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000968 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
969 InitBuiltinType(Char16Ty, BuiltinType::Char16);
970 else // C99
971 Char16Ty = getFromTargetType(Target.getChar16Type());
972
973 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
974 InitBuiltinType(Char32Ty, BuiltinType::Char32);
975 else // C99
976 Char32Ty = getFromTargetType(Target.getChar32Type());
977
Douglas Gregor4619e432008-12-05 23:32:09 +0000978 // Placeholder type for type-dependent expressions whose type is
979 // completely unknown. No code should ever check a type against
980 // DependentTy and users should never see it; however, it is here to
981 // help diagnose failures to properly check for type-dependent
982 // expressions.
983 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000984
John McCall36e7fe32010-10-12 00:20:44 +0000985 // Placeholder type for functions.
986 InitBuiltinType(OverloadTy, BuiltinType::Overload);
987
John McCall0009fcc2011-04-26 20:42:42 +0000988 // Placeholder type for bound members.
989 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
990
John McCall526ab472011-10-25 17:37:35 +0000991 // Placeholder type for pseudo-objects.
992 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
993
John McCall31996342011-04-07 08:22:57 +0000994 // "any" type; useful for debugger-like clients.
995 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
996
John McCall8a6b59a2011-10-17 18:09:15 +0000997 // Placeholder type for unbridged ARC casts.
998 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
999
Eli Friedman34866c72012-08-31 00:14:07 +00001000 // Placeholder type for builtin functions.
1001 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1002
Chris Lattner970e54e2006-11-12 00:37:36 +00001003 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001004 FloatComplexTy = getComplexType(FloatTy);
1005 DoubleComplexTy = getComplexType(DoubleTy);
1006 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001007
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001008 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001009 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1010 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001011 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001012
1013 if (LangOpts.OpenCL) {
1014 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1015 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1016 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1017 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1018 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
1019 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001020
Guy Benyei61054192013-02-07 10:55:47 +00001021 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001022 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001023 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001024
1025 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001026 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1027 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001028
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001029 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001030
1031 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001032
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001033 // void * type
1034 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001035
1036 // nullptr type (C++0x 2.14.7)
1037 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001038
1039 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1040 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001041
1042 // Builtin type used to help define __builtin_va_list.
1043 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +00001044}
1045
David Blaikie9c902b52011-09-25 23:23:43 +00001046DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001047 return SourceMgr.getDiagnostics();
1048}
1049
Douglas Gregor561eceb2010-08-30 16:49:28 +00001050AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1051 AttrVec *&Result = DeclAttrs[D];
1052 if (!Result) {
1053 void *Mem = Allocate(sizeof(AttrVec));
1054 Result = new (Mem) AttrVec;
1055 }
1056
1057 return *Result;
1058}
1059
1060/// \brief Erase the attributes corresponding to the given declaration.
1061void ASTContext::eraseDeclAttrs(const Decl *D) {
1062 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1063 if (Pos != DeclAttrs.end()) {
1064 Pos->second->~AttrVec();
1065 DeclAttrs.erase(Pos);
1066 }
1067}
1068
Larisse Voufo39a1e502013-08-06 01:03:05 +00001069// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001070MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001071ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001072 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001073 return getTemplateOrSpecializationInfo(Var)
1074 .dyn_cast<MemberSpecializationInfo *>();
1075}
1076
1077ASTContext::TemplateOrSpecializationInfo
1078ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1079 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1080 TemplateOrInstantiation.find(Var);
1081 if (Pos == TemplateOrInstantiation.end())
1082 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001083
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001084 return Pos->second;
1085}
1086
Mike Stump11289f42009-09-09 15:08:12 +00001087void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001088ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001089 TemplateSpecializationKind TSK,
1090 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001091 assert(Inst->isStaticDataMember() && "Not a static data member");
1092 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001093 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1094 Tmpl, TSK, PointOfInstantiation));
1095}
1096
1097void
1098ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1099 TemplateOrSpecializationInfo TSI) {
1100 assert(!TemplateOrInstantiation[Inst] &&
1101 "Already noted what the variable was instantiated from");
1102 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001103}
1104
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001105FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1106 const FunctionDecl *FD){
1107 assert(FD && "Specialization is 0");
1108 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001109 = ClassScopeSpecializationPattern.find(FD);
1110 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001111 return 0;
1112
1113 return Pos->second;
1114}
1115
1116void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1117 FunctionDecl *Pattern) {
1118 assert(FD && "Specialization is 0");
1119 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001120 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001121}
1122
John McCalle61f2ba2009-11-18 02:36:19 +00001123NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001124ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001125 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001126 = InstantiatedFromUsingDecl.find(UUD);
1127 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001128 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001129
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001130 return Pos->second;
1131}
1132
1133void
John McCallb96ec562009-12-04 22:46:56 +00001134ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1135 assert((isa<UsingDecl>(Pattern) ||
1136 isa<UnresolvedUsingValueDecl>(Pattern) ||
1137 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1138 "pattern decl is not a using decl");
1139 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1140 InstantiatedFromUsingDecl[Inst] = Pattern;
1141}
1142
1143UsingShadowDecl *
1144ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1145 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1146 = InstantiatedFromUsingShadowDecl.find(Inst);
1147 if (Pos == InstantiatedFromUsingShadowDecl.end())
1148 return 0;
1149
1150 return Pos->second;
1151}
1152
1153void
1154ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1155 UsingShadowDecl *Pattern) {
1156 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1157 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001158}
1159
Anders Carlsson5da84842009-09-01 04:26:58 +00001160FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1161 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1162 = InstantiatedFromUnnamedFieldDecl.find(Field);
1163 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1164 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001165
Anders Carlsson5da84842009-09-01 04:26:58 +00001166 return Pos->second;
1167}
1168
1169void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1170 FieldDecl *Tmpl) {
1171 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1172 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1173 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1174 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001175
Anders Carlsson5da84842009-09-01 04:26:58 +00001176 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1177}
1178
Douglas Gregor832940b2010-03-02 23:58:15 +00001179ASTContext::overridden_cxx_method_iterator
1180ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1181 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001182 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001183 if (Pos == OverriddenMethods.end())
1184 return 0;
1185
1186 return Pos->second.begin();
1187}
1188
1189ASTContext::overridden_cxx_method_iterator
1190ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1191 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001192 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001193 if (Pos == OverriddenMethods.end())
1194 return 0;
1195
1196 return Pos->second.end();
1197}
1198
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001199unsigned
1200ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1201 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001202 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001203 if (Pos == OverriddenMethods.end())
1204 return 0;
1205
1206 return Pos->second.size();
1207}
1208
Douglas Gregor832940b2010-03-02 23:58:15 +00001209void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1210 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001211 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001212 OverriddenMethods[Method].push_back(Overridden);
1213}
1214
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001215void ASTContext::getOverriddenMethods(
1216 const NamedDecl *D,
1217 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001218 assert(D);
1219
1220 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001221 Overridden.append(overridden_methods_begin(CXXMethod),
1222 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001223 return;
1224 }
1225
1226 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1227 if (!Method)
1228 return;
1229
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001230 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1231 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001232 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001233}
1234
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001235void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1236 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1237 assert(!Import->isFromASTFile() && "Non-local import declaration");
1238 if (!FirstLocalImport) {
1239 FirstLocalImport = Import;
1240 LastLocalImport = Import;
1241 return;
1242 }
1243
1244 LastLocalImport->NextLocalImport = Import;
1245 LastLocalImport = Import;
1246}
1247
Chris Lattner53cfe802007-07-18 17:52:12 +00001248//===----------------------------------------------------------------------===//
1249// Type Sizing and Analysis
1250//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001251
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001252/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1253/// scalar floating point type.
1254const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001255 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001256 assert(BT && "Not a floating point type!");
1257 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001258 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001259 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001260 case BuiltinType::Float: return Target->getFloatFormat();
1261 case BuiltinType::Double: return Target->getDoubleFormat();
1262 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001263 }
1264}
1265
Rafael Espindola71eccb32013-08-08 19:53:46 +00001266CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001267 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001268
John McCall94268702010-10-08 18:24:19 +00001269 bool UseAlignAttrOnly = false;
1270 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1271 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001272
John McCall94268702010-10-08 18:24:19 +00001273 // __attribute__((aligned)) can increase or decrease alignment
1274 // *except* on a struct or struct member, where it only increases
1275 // alignment unless 'packed' is also specified.
1276 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001277 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001278 // ignore that possibility; Sema should diagnose it.
1279 if (isa<FieldDecl>(D)) {
1280 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1281 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1282 } else {
1283 UseAlignAttrOnly = true;
1284 }
1285 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001286 else if (isa<FieldDecl>(D))
1287 UseAlignAttrOnly =
1288 D->hasAttr<PackedAttr>() ||
1289 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001290
John McCall4e819612011-01-20 07:57:12 +00001291 // If we're using the align attribute only, just ignore everything
1292 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001293 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001294 // do nothing
1295
John McCall94268702010-10-08 18:24:19 +00001296 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001297 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001298 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001299 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001300 T = RT->getPointeeType();
1301 else
1302 T = getPointerType(RT->getPointeeType());
1303 }
1304 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001305 // Adjust alignments of declarations with array type by the
1306 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001307 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001308 unsigned MinWidth = Target->getLargeArrayMinWidth();
1309 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001310 if (isa<VariableArrayType>(arrayType))
1311 Align = std::max(Align, Target->getLargeArrayAlign());
1312 else if (isa<ConstantArrayType>(arrayType) &&
1313 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1314 Align = std::max(Align, Target->getLargeArrayAlign());
1315 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001316
John McCall33ddac02011-01-19 10:06:00 +00001317 // Walk through any array types while we're at it.
1318 T = getBaseElementType(arrayType);
1319 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001320 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001321 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1322 if (VD->hasGlobalStorage())
1323 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1324 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001325 }
John McCall4e819612011-01-20 07:57:12 +00001326
1327 // Fields can be subject to extra alignment constraints, like if
1328 // the field is packed, the struct is packed, or the struct has a
1329 // a max-field-alignment constraint (#pragma pack). So calculate
1330 // the actual alignment of the field within the struct, and then
1331 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001332 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1333 const RecordDecl *Parent = Field->getParent();
1334 // We can only produce a sensible answer if the record is valid.
1335 if (!Parent->isInvalidDecl()) {
1336 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001337
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001338 // Start with the record's overall alignment.
1339 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001340
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001341 // Use the GCD of that and the offset within the record.
1342 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1343 if (Offset > 0) {
1344 // Alignment is always a power of 2, so the GCD will be a power of 2,
1345 // which means we get to do this crazy thing instead of Euclid's.
1346 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1347 if (LowBitOfOffset < FieldAlign)
1348 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1349 }
1350
1351 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001352 }
Charles Davis3fc51072010-02-23 04:52:00 +00001353 }
Chris Lattner68061312009-01-24 21:53:27 +00001354 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001355
Ken Dyckcc56c542011-01-15 18:38:59 +00001356 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001357}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001358
John McCallf1249922012-08-21 04:10:00 +00001359// getTypeInfoDataSizeInChars - Return the size of a type, in
1360// chars. If the type is a record, its data size is returned. This is
1361// the size of the memcpy that's performed when assigning this type
1362// using a trivial copy/move assignment operator.
1363std::pair<CharUnits, CharUnits>
1364ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1365 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1366
1367 // In C++, objects can sometimes be allocated into the tail padding
1368 // of a base-class subobject. We decide whether that's possible
1369 // during class layout, so here we can just trust the layout results.
1370 if (getLangOpts().CPlusPlus) {
1371 if (const RecordType *RT = T->getAs<RecordType>()) {
1372 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1373 sizeAndAlign.first = layout.getDataSize();
1374 }
1375 }
1376
1377 return sizeAndAlign;
1378}
1379
Richard Trieu04d2d942013-05-14 21:59:17 +00001380/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1381/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1382std::pair<CharUnits, CharUnits>
1383static getConstantArrayInfoInChars(const ASTContext &Context,
1384 const ConstantArrayType *CAT) {
1385 std::pair<CharUnits, CharUnits> EltInfo =
1386 Context.getTypeInfoInChars(CAT->getElementType());
1387 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001388 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1389 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001390 "Overflow in array type char size evaluation");
1391 uint64_t Width = EltInfo.first.getQuantity() * Size;
1392 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001393 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1394 Context.getTargetInfo().getPointerWidth(0) == 64)
1395 Width = llvm::RoundUpToAlignment(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001396 return std::make_pair(CharUnits::fromQuantity(Width),
1397 CharUnits::fromQuantity(Align));
1398}
1399
John McCall87fe5d52010-05-20 01:18:31 +00001400std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001401ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001402 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1403 return getConstantArrayInfoInChars(*this, CAT);
John McCall87fe5d52010-05-20 01:18:31 +00001404 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +00001405 return std::make_pair(toCharUnitsFromBits(Info.first),
1406 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +00001407}
1408
1409std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001410ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001411 return getTypeInfoInChars(T.getTypePtr());
1412}
1413
Daniel Dunbarc6475872012-03-09 04:12:54 +00001414std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1415 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1416 if (it != MemoizedTypeInfo.end())
1417 return it->second;
1418
1419 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1420 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1421 return Info;
1422}
1423
1424/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1425/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001426///
1427/// FIXME: Pointers into different addr spaces could have different sizes and
1428/// alignment requirements: getPointerInfo should take an AddrSpace, this
1429/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +00001430std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +00001431ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +00001432 uint64_t Width=0;
1433 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001434 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001435#define TYPE(Class, Base)
1436#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001437#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001438#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001439#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1440 case Type::Class: \
1441 assert(!T->isDependentType() && "should not see dependent types here"); \
1442 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001443#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001444 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001445
Chris Lattner355332d2007-07-13 22:27:08 +00001446 case Type::FunctionNoProto:
1447 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001448 // GCC extension: alignof(function) = 32 bits
1449 Width = 0;
1450 Align = 32;
1451 break;
1452
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001453 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001454 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001455 Width = 0;
1456 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1457 break;
1458
Steve Naroff5c131802007-08-30 01:06:46 +00001459 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001460 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001461
Chris Lattner37e05872008-03-05 18:54:05 +00001462 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001463 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +00001464 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1465 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001466 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001467 Align = EltInfo.second;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001468 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1469 getTargetInfo().getPointerWidth(0) == 64)
1470 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001471 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001472 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001473 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001474 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001475 const VectorType *VT = cast<VectorType>(T);
1476 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1477 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001478 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001479 // If the alignment is not a power of 2, round up to the next power of 2.
1480 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001481 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001482 Align = llvm::NextPowerOf2(Align);
1483 Width = llvm::RoundUpToAlignment(Width, Align);
1484 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001485 // Adjust the alignment based on the target max.
1486 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1487 if (TargetVectorAlign && TargetVectorAlign < Align)
1488 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001489 break;
1490 }
Chris Lattner647fb222007-07-18 18:26:58 +00001491
Chris Lattner7570e9c2008-03-08 08:52:55 +00001492 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001493 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001494 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001495 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001496 // GCC extension: alignof(void) = 8 bits.
1497 Width = 0;
1498 Align = 8;
1499 break;
1500
Chris Lattner6a4f7452007-12-19 19:23:28 +00001501 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001502 Width = Target->getBoolWidth();
1503 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001504 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001505 case BuiltinType::Char_S:
1506 case BuiltinType::Char_U:
1507 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001508 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001509 Width = Target->getCharWidth();
1510 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001511 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001512 case BuiltinType::WChar_S:
1513 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001514 Width = Target->getWCharWidth();
1515 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001516 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001517 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001518 Width = Target->getChar16Width();
1519 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001520 break;
1521 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001522 Width = Target->getChar32Width();
1523 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001524 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001525 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001526 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001527 Width = Target->getShortWidth();
1528 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001529 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001530 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001531 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001532 Width = Target->getIntWidth();
1533 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001534 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001535 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001536 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001537 Width = Target->getLongWidth();
1538 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001539 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001540 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001541 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001542 Width = Target->getLongLongWidth();
1543 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001544 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001545 case BuiltinType::Int128:
1546 case BuiltinType::UInt128:
1547 Width = 128;
1548 Align = 128; // int128_t is 128-bit aligned on all targets.
1549 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001550 case BuiltinType::Half:
1551 Width = Target->getHalfWidth();
1552 Align = Target->getHalfAlign();
1553 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001554 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001555 Width = Target->getFloatWidth();
1556 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001557 break;
1558 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001559 Width = Target->getDoubleWidth();
1560 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001561 break;
1562 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001563 Width = Target->getLongDoubleWidth();
1564 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001565 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001566 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001567 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1568 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001569 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001570 case BuiltinType::ObjCId:
1571 case BuiltinType::ObjCClass:
1572 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001573 Width = Target->getPointerWidth(0);
1574 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001575 break;
Guy Benyei61054192013-02-07 10:55:47 +00001576 case BuiltinType::OCLSampler:
1577 // Samplers are modeled as integers.
1578 Width = Target->getIntWidth();
1579 Align = Target->getIntAlign();
1580 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001581 case BuiltinType::OCLEvent:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001582 case BuiltinType::OCLImage1d:
1583 case BuiltinType::OCLImage1dArray:
1584 case BuiltinType::OCLImage1dBuffer:
1585 case BuiltinType::OCLImage2d:
1586 case BuiltinType::OCLImage2dArray:
1587 case BuiltinType::OCLImage3d:
1588 // Currently these types are pointers to opaque types.
1589 Width = Target->getPointerWidth(0);
1590 Align = Target->getPointerAlign(0);
1591 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001592 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001593 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001594 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001595 Width = Target->getPointerWidth(0);
1596 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001597 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001598 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001599 unsigned AS = getTargetAddressSpace(
1600 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001601 Width = Target->getPointerWidth(AS);
1602 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001603 break;
1604 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001605 case Type::LValueReference:
1606 case Type::RValueReference: {
1607 // alignof and sizeof should never enter this code path here, so we go
1608 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001609 unsigned AS = getTargetAddressSpace(
1610 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001611 Width = Target->getPointerWidth(AS);
1612 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001613 break;
1614 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001615 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001616 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001617 Width = Target->getPointerWidth(AS);
1618 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001619 break;
1620 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001621 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001622 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Reid Kleckner3a52abf2013-03-28 20:02:56 +00001623 llvm::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001624 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001625 }
Chris Lattner647fb222007-07-18 18:26:58 +00001626 case Type::Complex: {
1627 // Complex types have the same alignment as their elements, but twice the
1628 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001629 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001630 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001631 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001632 Align = EltInfo.second;
1633 break;
1634 }
John McCall8b07ec22010-05-15 11:32:37 +00001635 case Type::ObjCObject:
1636 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001637 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001638 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001639 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001640 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001641 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001642 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001643 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001644 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001645 break;
1646 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001647 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001648 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001649 const TagType *TT = cast<TagType>(T);
1650
1651 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001652 Width = 8;
1653 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001654 break;
1655 }
Mike Stump11289f42009-09-09 15:08:12 +00001656
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001657 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001658 return getTypeInfo(ET->getDecl()->getIntegerType());
1659
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001660 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001661 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001662 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001663 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001664 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001665 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001666
Chris Lattner63d2b362009-10-22 05:17:15 +00001667 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001668 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1669 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001670
Richard Smith30482bc2011-02-20 03:19:35 +00001671 case Type::Auto: {
1672 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001673 assert(!A->getDeducedType().isNull() &&
1674 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001675 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001676 }
1677
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001678 case Type::Paren:
1679 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1680
Douglas Gregoref462e62009-04-30 17:32:17 +00001681 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001682 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001683 std::pair<uint64_t, unsigned> Info
1684 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001685 // If the typedef has an aligned attribute on it, it overrides any computed
1686 // alignment we have. This violates the GCC documentation (which says that
1687 // attribute(aligned) can only round up) but matches its implementation.
1688 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1689 Align = AttrAlign;
1690 else
1691 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001692 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001693 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001694 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001695
Abramo Bagnara6150c882010-05-11 21:36:43 +00001696 case Type::Elaborated:
1697 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001698
John McCall81904512011-01-06 01:58:22 +00001699 case Type::Attributed:
1700 return getTypeInfo(
1701 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1702
Eli Friedman0dfb8892011-10-06 23:00:33 +00001703 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001704 // Start with the base type information.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001705 std::pair<uint64_t, unsigned> Info
1706 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1707 Width = Info.first;
1708 Align = Info.second;
John McCalla8ec7eb2013-03-07 21:37:17 +00001709
1710 // If the size of the type doesn't exceed the platform's max
1711 // atomic promotion width, make the size and alignment more
1712 // favorable to atomic operations:
1713 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1714 // Round the size up to a power of 2.
1715 if (!llvm::isPowerOf2_64(Width))
1716 Width = llvm::NextPowerOf2(Width);
1717
1718 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001719 Align = static_cast<unsigned>(Width);
1720 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001721 }
1722
Douglas Gregoref462e62009-04-30 17:32:17 +00001723 }
Mike Stump11289f42009-09-09 15:08:12 +00001724
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001725 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001726 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001727}
1728
Ken Dyckcc56c542011-01-15 18:38:59 +00001729/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1730CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1731 return CharUnits::fromQuantity(BitSize / getCharWidth());
1732}
1733
Ken Dyckb0fcc592011-02-11 01:54:29 +00001734/// toBits - Convert a size in characters to a size in characters.
1735int64_t ASTContext::toBits(CharUnits CharSize) const {
1736 return CharSize.getQuantity() * getCharWidth();
1737}
1738
Ken Dyck8c89d592009-12-22 14:23:30 +00001739/// getTypeSizeInChars - Return the size of the specified type, in characters.
1740/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001741CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001742 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001743}
Jay Foad39c79802011-01-12 09:06:06 +00001744CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001745 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001746}
1747
Ken Dycka6046ab2010-01-26 17:25:18 +00001748/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001749/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001750CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001751 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001752}
Jay Foad39c79802011-01-12 09:06:06 +00001753CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001754 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001755}
1756
Chris Lattnera3402cd2009-01-27 18:08:34 +00001757/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1758/// type for the current target in bits. This can be different than the ABI
1759/// alignment in cases where it is beneficial for performance to overalign
1760/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001761unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001762 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001763
Robert Lyttoneaf6f362013-11-12 10:09:34 +00001764 if (Target->getTriple().getArch() == llvm::Triple::xcore)
1765 return ABIAlign; // Never overalign on XCore.
1766
Eli Friedman7ab09572009-05-25 21:27:19 +00001767 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001768 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001769 T = CT->getElementType().getTypePtr();
1770 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001771 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1772 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001773 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1774
Chris Lattnera3402cd2009-01-27 18:08:34 +00001775 return ABIAlign;
1776}
1777
Ulrich Weigandfa806422013-05-06 16:23:57 +00001778/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1779/// to a global variable of the specified type.
1780unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1781 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1782}
1783
1784/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1785/// should be given to a global variable of the specified type.
1786CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1787 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1788}
1789
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001790/// DeepCollectObjCIvars -
1791/// This routine first collects all declared, but not synthesized, ivars in
1792/// super class and then collects all ivars, including those synthesized for
1793/// current class. This routine is used for implementation of current class
1794/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001795///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001796void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1797 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001798 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001799 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1800 DeepCollectObjCIvars(SuperClass, false, Ivars);
1801 if (!leafClass) {
1802 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1803 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001804 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001805 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001806 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001807 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001808 Iv= Iv->getNextIvar())
1809 Ivars.push_back(Iv);
1810 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001811}
1812
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001813/// CollectInheritedProtocols - Collect all protocols in current class and
1814/// those inherited by it.
1815void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001816 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001817 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001818 // We can use protocol_iterator here instead of
1819 // all_referenced_protocol_iterator since we are walking all categories.
1820 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1821 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001822 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001823 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001824 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001825 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001826 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001827 CollectInheritedProtocols(*P, Protocols);
1828 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001829 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001830
1831 // Categories of this Interface.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001832 for (ObjCInterfaceDecl::visible_categories_iterator
1833 Cat = OI->visible_categories_begin(),
1834 CatEnd = OI->visible_categories_end();
1835 Cat != CatEnd; ++Cat) {
1836 CollectInheritedProtocols(*Cat, Protocols);
1837 }
1838
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001839 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1840 while (SD) {
1841 CollectInheritedProtocols(SD, Protocols);
1842 SD = SD->getSuperClass();
1843 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001844 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001845 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001846 PE = OC->protocol_end(); P != PE; ++P) {
1847 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001848 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001849 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1850 PE = Proto->protocol_end(); P != PE; ++P)
1851 CollectInheritedProtocols(*P, Protocols);
1852 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001853 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001854 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1855 PE = OP->protocol_end(); P != PE; ++P) {
1856 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001857 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001858 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1859 PE = Proto->protocol_end(); P != PE; ++P)
1860 CollectInheritedProtocols(*P, Protocols);
1861 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001862 }
1863}
1864
Jay Foad39c79802011-01-12 09:06:06 +00001865unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001866 unsigned count = 0;
1867 // Count ivars declared in class extension.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001868 for (ObjCInterfaceDecl::known_extensions_iterator
1869 Ext = OI->known_extensions_begin(),
1870 ExtEnd = OI->known_extensions_end();
1871 Ext != ExtEnd; ++Ext) {
1872 count += Ext->ivar_size();
1873 }
1874
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001875 // Count ivar defined in this class's implementation. This
1876 // includes synthesized ivars.
1877 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001878 count += ImplDecl->ivar_size();
1879
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001880 return count;
1881}
1882
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001883bool ASTContext::isSentinelNullExpr(const Expr *E) {
1884 if (!E)
1885 return false;
1886
1887 // nullptr_t is always treated as null.
1888 if (E->getType()->isNullPtrType()) return true;
1889
1890 if (E->getType()->isAnyPointerType() &&
1891 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1892 Expr::NPC_ValueDependentIsNull))
1893 return true;
1894
1895 // Unfortunately, __null has type 'int'.
1896 if (isa<GNUNullExpr>(E)) return true;
1897
1898 return false;
1899}
1900
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001901/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1902ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1903 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1904 I = ObjCImpls.find(D);
1905 if (I != ObjCImpls.end())
1906 return cast<ObjCImplementationDecl>(I->second);
1907 return 0;
1908}
1909/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1910ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1911 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1912 I = ObjCImpls.find(D);
1913 if (I != ObjCImpls.end())
1914 return cast<ObjCCategoryImplDecl>(I->second);
1915 return 0;
1916}
1917
1918/// \brief Set the implementation of ObjCInterfaceDecl.
1919void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1920 ObjCImplementationDecl *ImplD) {
1921 assert(IFaceD && ImplD && "Passed null params");
1922 ObjCImpls[IFaceD] = ImplD;
1923}
1924/// \brief Set the implementation of ObjCCategoryDecl.
1925void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1926 ObjCCategoryImplDecl *ImplD) {
1927 assert(CatD && ImplD && "Passed null params");
1928 ObjCImpls[CatD] = ImplD;
1929}
1930
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001931const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1932 const NamedDecl *ND) const {
1933 if (const ObjCInterfaceDecl *ID =
1934 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001935 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001936 if (const ObjCCategoryDecl *CD =
1937 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001938 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001939 if (const ObjCImplDecl *IMD =
1940 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001941 return IMD->getClassInterface();
1942
1943 return 0;
1944}
1945
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001946/// \brief Get the copy initialization expression of VarDecl,or NULL if
1947/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001948Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001949 assert(VD && "Passed null params");
1950 assert(VD->hasAttr<BlocksAttr>() &&
1951 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001952 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001953 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001954 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1955}
1956
1957/// \brief Set the copy inialization expression of a block var decl.
1958void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1959 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001960 assert(VD->hasAttr<BlocksAttr>() &&
1961 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001962 BlockVarCopyInits[VD] = Init;
1963}
1964
John McCallbcd03502009-12-07 02:54:59 +00001965TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001966 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001967 if (!DataSize)
1968 DataSize = TypeLoc::getFullDataSizeForType(T);
1969 else
1970 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001971 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001972
John McCallbcd03502009-12-07 02:54:59 +00001973 TypeSourceInfo *TInfo =
1974 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1975 new (TInfo) TypeSourceInfo(T);
1976 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001977}
1978
John McCallbcd03502009-12-07 02:54:59 +00001979TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001980 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001981 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001982 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001983 return DI;
1984}
1985
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001986const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001987ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001988 return getObjCLayout(D, 0);
1989}
1990
1991const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001992ASTContext::getASTObjCImplementationLayout(
1993 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001994 return getObjCLayout(D->getClassInterface(), D);
1995}
1996
Chris Lattner983a8bb2007-07-13 22:13:22 +00001997//===----------------------------------------------------------------------===//
1998// Type creation/memoization methods
1999//===----------------------------------------------------------------------===//
2000
Jay Foad39c79802011-01-12 09:06:06 +00002001QualType
John McCall33ddac02011-01-19 10:06:00 +00002002ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2003 unsigned fastQuals = quals.getFastQualifiers();
2004 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002005
2006 // Check if we've already instantiated this type.
2007 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002008 ExtQuals::Profile(ID, baseType, quals);
2009 void *insertPos = 0;
2010 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2011 assert(eq->getQualifiers() == quals);
2012 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002013 }
2014
John McCall33ddac02011-01-19 10:06:00 +00002015 // If the base type is not canonical, make the appropriate canonical type.
2016 QualType canon;
2017 if (!baseType->isCanonicalUnqualified()) {
2018 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002019 canonSplit.Quals.addConsistentQualifiers(quals);
2020 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002021
2022 // Re-find the insert position.
2023 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2024 }
2025
2026 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2027 ExtQualNodes.InsertNode(eq, insertPos);
2028 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002029}
2030
Jay Foad39c79802011-01-12 09:06:06 +00002031QualType
2032ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002033 QualType CanT = getCanonicalType(T);
2034 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002035 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002036
John McCall8ccfcb52009-09-24 19:53:00 +00002037 // If we are composing extended qualifiers together, merge together
2038 // into one ExtQuals node.
2039 QualifierCollector Quals;
2040 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002041
John McCall8ccfcb52009-09-24 19:53:00 +00002042 // If this type already has an address space specified, it cannot get
2043 // another one.
2044 assert(!Quals.hasAddressSpace() &&
2045 "Type cannot be in multiple addr spaces!");
2046 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002047
John McCall8ccfcb52009-09-24 19:53:00 +00002048 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002049}
2050
Chris Lattnerd60183d2009-02-18 22:53:11 +00002051QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002052 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002053 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002054 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002055 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002056
John McCall53fa7142010-12-24 02:08:15 +00002057 if (const PointerType *ptr = T->getAs<PointerType>()) {
2058 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002059 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002060 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2061 return getPointerType(ResultType);
2062 }
2063 }
Mike Stump11289f42009-09-09 15:08:12 +00002064
John McCall8ccfcb52009-09-24 19:53:00 +00002065 // If we are composing extended qualifiers together, merge together
2066 // into one ExtQuals node.
2067 QualifierCollector Quals;
2068 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002069
John McCall8ccfcb52009-09-24 19:53:00 +00002070 // If this type already has an ObjCGC specified, it cannot get
2071 // another one.
2072 assert(!Quals.hasObjCGCAttr() &&
2073 "Type cannot have multiple ObjCGCs!");
2074 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002075
John McCall8ccfcb52009-09-24 19:53:00 +00002076 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002077}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002078
John McCall4f5019e2010-12-19 02:44:49 +00002079const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2080 FunctionType::ExtInfo Info) {
2081 if (T->getExtInfo() == Info)
2082 return T;
2083
2084 QualType Result;
2085 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2086 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
2087 } else {
2088 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2089 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2090 EPI.ExtInfo = Info;
Alp Toker9cacbab2014-01-20 20:26:09 +00002091 Result = getFunctionType(FPT->getResultType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002092 }
2093
2094 return cast<FunctionType>(Result.getTypePtr());
2095}
2096
Richard Smith2a7d4812013-05-04 07:00:32 +00002097void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2098 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002099 FD = FD->getMostRecentDecl();
2100 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002101 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2102 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002103 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002104 if (FunctionDecl *Next = FD->getPreviousDecl())
2105 FD = Next;
2106 else
2107 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002108 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002109 if (ASTMutationListener *L = getASTMutationListener())
2110 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002111}
2112
Chris Lattnerc6395932007-06-22 20:56:16 +00002113/// getComplexType - Return the uniqued reference to the type for a complex
2114/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002115QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002116 // Unique pointers, to guarantee there is only one pointer of a particular
2117 // structure.
2118 llvm::FoldingSetNodeID ID;
2119 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002120
Chris Lattnerc6395932007-06-22 20:56:16 +00002121 void *InsertPos = 0;
2122 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2123 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002124
Chris Lattnerc6395932007-06-22 20:56:16 +00002125 // If the pointee type isn't canonical, this won't be a canonical type either,
2126 // so fill in the canonical type field.
2127 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002128 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002129 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002130
Chris Lattnerc6395932007-06-22 20:56:16 +00002131 // Get the new insert position for the node we care about.
2132 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002133 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002134 }
John McCall90d1c2d2009-09-24 23:30:46 +00002135 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002136 Types.push_back(New);
2137 ComplexTypes.InsertNode(New, InsertPos);
2138 return QualType(New, 0);
2139}
2140
Chris Lattner970e54e2006-11-12 00:37:36 +00002141/// getPointerType - Return the uniqued reference to the type for a pointer to
2142/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002143QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002144 // Unique pointers, to guarantee there is only one pointer of a particular
2145 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002146 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002147 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002148
Chris Lattner67521df2007-01-27 01:29:36 +00002149 void *InsertPos = 0;
2150 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002151 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002152
Chris Lattner7ccecb92006-11-12 08:50:50 +00002153 // If the pointee type isn't canonical, this won't be a canonical type either,
2154 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002155 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002156 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002157 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002158
Bob Wilsonc8541f22013-03-15 17:12:43 +00002159 // Get the new insert position for the node we care about.
2160 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2161 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2162 }
John McCall90d1c2d2009-09-24 23:30:46 +00002163 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002164 Types.push_back(New);
2165 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002166 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002167}
2168
Reid Kleckner0503a872013-12-05 01:23:43 +00002169QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2170 llvm::FoldingSetNodeID ID;
2171 AdjustedType::Profile(ID, Orig, New);
2172 void *InsertPos = 0;
2173 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2174 if (AT)
2175 return QualType(AT, 0);
2176
2177 QualType Canonical = getCanonicalType(New);
2178
2179 // Get the new insert position for the node we care about.
2180 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2181 assert(AT == 0 && "Shouldn't be in the map!");
2182
2183 AT = new (*this, TypeAlignment)
2184 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2185 Types.push_back(AT);
2186 AdjustedTypes.InsertNode(AT, InsertPos);
2187 return QualType(AT, 0);
2188}
2189
Reid Kleckner8a365022013-06-24 17:51:48 +00002190QualType ASTContext::getDecayedType(QualType T) const {
2191 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2192
Reid Kleckner8a365022013-06-24 17:51:48 +00002193 QualType Decayed;
2194
2195 // C99 6.7.5.3p7:
2196 // A declaration of a parameter as "array of type" shall be
2197 // adjusted to "qualified pointer to type", where the type
2198 // qualifiers (if any) are those specified within the [ and ] of
2199 // the array type derivation.
2200 if (T->isArrayType())
2201 Decayed = getArrayDecayedType(T);
2202
2203 // C99 6.7.5.3p8:
2204 // A declaration of a parameter as "function returning type"
2205 // shall be adjusted to "pointer to function returning type", as
2206 // in 6.3.2.1.
2207 if (T->isFunctionType())
2208 Decayed = getPointerType(T);
2209
Reid Kleckner0503a872013-12-05 01:23:43 +00002210 llvm::FoldingSetNodeID ID;
2211 AdjustedType::Profile(ID, T, Decayed);
2212 void *InsertPos = 0;
2213 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2214 if (AT)
2215 return QualType(AT, 0);
2216
Reid Kleckner8a365022013-06-24 17:51:48 +00002217 QualType Canonical = getCanonicalType(Decayed);
2218
2219 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002220 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2221 assert(AT == 0 && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002222
Reid Kleckner0503a872013-12-05 01:23:43 +00002223 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2224 Types.push_back(AT);
2225 AdjustedTypes.InsertNode(AT, InsertPos);
2226 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002227}
2228
Mike Stump11289f42009-09-09 15:08:12 +00002229/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002230/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002231QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002232 assert(T->isFunctionType() && "block of function types only");
2233 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002234 // structure.
2235 llvm::FoldingSetNodeID ID;
2236 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002237
Steve Naroffec33ed92008-08-27 16:04:49 +00002238 void *InsertPos = 0;
2239 if (BlockPointerType *PT =
2240 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2241 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002242
2243 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002244 // type either so fill in the canonical type field.
2245 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002246 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002247 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002248
Steve Naroffec33ed92008-08-27 16:04:49 +00002249 // Get the new insert position for the node we care about.
2250 BlockPointerType *NewIP =
2251 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002252 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002253 }
John McCall90d1c2d2009-09-24 23:30:46 +00002254 BlockPointerType *New
2255 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002256 Types.push_back(New);
2257 BlockPointerTypes.InsertNode(New, InsertPos);
2258 return QualType(New, 0);
2259}
2260
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002261/// getLValueReferenceType - Return the uniqued reference to the type for an
2262/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002263QualType
2264ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002265 assert(getCanonicalType(T) != OverloadTy &&
2266 "Unresolved overloaded function type");
2267
Bill Wendling3708c182007-05-27 10:15:43 +00002268 // Unique pointers, to guarantee there is only one pointer of a particular
2269 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002270 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002271 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002272
2273 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002274 if (LValueReferenceType *RT =
2275 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002276 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002277
John McCallfc93cf92009-10-22 22:37:11 +00002278 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2279
Bill Wendling3708c182007-05-27 10:15:43 +00002280 // If the referencee type isn't canonical, this won't be a canonical type
2281 // either, so fill in the canonical type field.
2282 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002283 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2284 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2285 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002286
Bill Wendling3708c182007-05-27 10:15:43 +00002287 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002288 LValueReferenceType *NewIP =
2289 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002290 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002291 }
2292
John McCall90d1c2d2009-09-24 23:30:46 +00002293 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002294 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2295 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002296 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002297 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002298
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002299 return QualType(New, 0);
2300}
2301
2302/// getRValueReferenceType - Return the uniqued reference to the type for an
2303/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002304QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002305 // Unique pointers, to guarantee there is only one pointer of a particular
2306 // structure.
2307 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002308 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002309
2310 void *InsertPos = 0;
2311 if (RValueReferenceType *RT =
2312 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2313 return QualType(RT, 0);
2314
John McCallfc93cf92009-10-22 22:37:11 +00002315 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2316
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002317 // If the referencee type isn't canonical, this won't be a canonical type
2318 // either, so fill in the canonical type field.
2319 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002320 if (InnerRef || !T.isCanonical()) {
2321 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2322 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002323
2324 // Get the new insert position for the node we care about.
2325 RValueReferenceType *NewIP =
2326 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002327 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002328 }
2329
John McCall90d1c2d2009-09-24 23:30:46 +00002330 RValueReferenceType *New
2331 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002332 Types.push_back(New);
2333 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002334 return QualType(New, 0);
2335}
2336
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002337/// getMemberPointerType - Return the uniqued reference to the type for a
2338/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002339QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002340 // Unique pointers, to guarantee there is only one pointer of a particular
2341 // structure.
2342 llvm::FoldingSetNodeID ID;
2343 MemberPointerType::Profile(ID, T, Cls);
2344
2345 void *InsertPos = 0;
2346 if (MemberPointerType *PT =
2347 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2348 return QualType(PT, 0);
2349
2350 // If the pointee or class type isn't canonical, this won't be a canonical
2351 // type either, so fill in the canonical type field.
2352 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002353 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002354 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2355
2356 // Get the new insert position for the node we care about.
2357 MemberPointerType *NewIP =
2358 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002359 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002360 }
John McCall90d1c2d2009-09-24 23:30:46 +00002361 MemberPointerType *New
2362 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002363 Types.push_back(New);
2364 MemberPointerTypes.InsertNode(New, InsertPos);
2365 return QualType(New, 0);
2366}
2367
Mike Stump11289f42009-09-09 15:08:12 +00002368/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002369/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002370QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002371 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002372 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002373 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002374 assert((EltTy->isDependentType() ||
2375 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002376 "Constant array of VLAs is illegal!");
2377
Chris Lattnere2df3f92009-05-13 04:12:56 +00002378 // Convert the array size into a canonical width matching the pointer size for
2379 // the target.
2380 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002381 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002382 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002383
Chris Lattner23b7eb62007-06-15 23:05:46 +00002384 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002385 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002386
Chris Lattner36f8e652007-01-27 08:31:04 +00002387 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002388 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002389 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002390 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002391
John McCall33ddac02011-01-19 10:06:00 +00002392 // If the element type isn't canonical or has qualifiers, this won't
2393 // be a canonical type either, so fill in the canonical type field.
2394 QualType Canon;
2395 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2396 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002397 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002398 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002399 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002400
Chris Lattner36f8e652007-01-27 08:31:04 +00002401 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002402 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002403 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002404 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002405 }
Mike Stump11289f42009-09-09 15:08:12 +00002406
John McCall90d1c2d2009-09-24 23:30:46 +00002407 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002408 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002409 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002410 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002411 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002412}
2413
John McCall06549462011-01-18 08:40:38 +00002414/// getVariableArrayDecayedType - Turns the given type, which may be
2415/// variably-modified, into the corresponding type with all the known
2416/// sizes replaced with [*].
2417QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2418 // Vastly most common case.
2419 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002420
John McCall06549462011-01-18 08:40:38 +00002421 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002422
John McCall06549462011-01-18 08:40:38 +00002423 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002424 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002425 switch (ty->getTypeClass()) {
2426#define TYPE(Class, Base)
2427#define ABSTRACT_TYPE(Class, Base)
2428#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2429#include "clang/AST/TypeNodes.def"
2430 llvm_unreachable("didn't desugar past all non-canonical types?");
2431
2432 // These types should never be variably-modified.
2433 case Type::Builtin:
2434 case Type::Complex:
2435 case Type::Vector:
2436 case Type::ExtVector:
2437 case Type::DependentSizedExtVector:
2438 case Type::ObjCObject:
2439 case Type::ObjCInterface:
2440 case Type::ObjCObjectPointer:
2441 case Type::Record:
2442 case Type::Enum:
2443 case Type::UnresolvedUsing:
2444 case Type::TypeOfExpr:
2445 case Type::TypeOf:
2446 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002447 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002448 case Type::DependentName:
2449 case Type::InjectedClassName:
2450 case Type::TemplateSpecialization:
2451 case Type::DependentTemplateSpecialization:
2452 case Type::TemplateTypeParm:
2453 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002454 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002455 case Type::PackExpansion:
2456 llvm_unreachable("type should never be variably-modified");
2457
2458 // These types can be variably-modified but should never need to
2459 // further decay.
2460 case Type::FunctionNoProto:
2461 case Type::FunctionProto:
2462 case Type::BlockPointer:
2463 case Type::MemberPointer:
2464 return type;
2465
2466 // These types can be variably-modified. All these modifications
2467 // preserve structure except as noted by comments.
2468 // TODO: if we ever care about optimizing VLAs, there are no-op
2469 // optimizations available here.
2470 case Type::Pointer:
2471 result = getPointerType(getVariableArrayDecayedType(
2472 cast<PointerType>(ty)->getPointeeType()));
2473 break;
2474
2475 case Type::LValueReference: {
2476 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2477 result = getLValueReferenceType(
2478 getVariableArrayDecayedType(lv->getPointeeType()),
2479 lv->isSpelledAsLValue());
2480 break;
2481 }
2482
2483 case Type::RValueReference: {
2484 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2485 result = getRValueReferenceType(
2486 getVariableArrayDecayedType(lv->getPointeeType()));
2487 break;
2488 }
2489
Eli Friedman0dfb8892011-10-06 23:00:33 +00002490 case Type::Atomic: {
2491 const AtomicType *at = cast<AtomicType>(ty);
2492 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2493 break;
2494 }
2495
John McCall06549462011-01-18 08:40:38 +00002496 case Type::ConstantArray: {
2497 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2498 result = getConstantArrayType(
2499 getVariableArrayDecayedType(cat->getElementType()),
2500 cat->getSize(),
2501 cat->getSizeModifier(),
2502 cat->getIndexTypeCVRQualifiers());
2503 break;
2504 }
2505
2506 case Type::DependentSizedArray: {
2507 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2508 result = getDependentSizedArrayType(
2509 getVariableArrayDecayedType(dat->getElementType()),
2510 dat->getSizeExpr(),
2511 dat->getSizeModifier(),
2512 dat->getIndexTypeCVRQualifiers(),
2513 dat->getBracketsRange());
2514 break;
2515 }
2516
2517 // Turn incomplete types into [*] types.
2518 case Type::IncompleteArray: {
2519 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2520 result = getVariableArrayType(
2521 getVariableArrayDecayedType(iat->getElementType()),
2522 /*size*/ 0,
2523 ArrayType::Normal,
2524 iat->getIndexTypeCVRQualifiers(),
2525 SourceRange());
2526 break;
2527 }
2528
2529 // Turn VLA types into [*] types.
2530 case Type::VariableArray: {
2531 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2532 result = getVariableArrayType(
2533 getVariableArrayDecayedType(vat->getElementType()),
2534 /*size*/ 0,
2535 ArrayType::Star,
2536 vat->getIndexTypeCVRQualifiers(),
2537 vat->getBracketsRange());
2538 break;
2539 }
2540 }
2541
2542 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002543 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002544}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002545
Steve Naroffcadebd02007-08-30 18:14:25 +00002546/// getVariableArrayType - Returns a non-unique reference to the type for a
2547/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002548QualType ASTContext::getVariableArrayType(QualType EltTy,
2549 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002550 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002551 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002552 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002553 // Since we don't unique expressions, it isn't possible to unique VLA's
2554 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002555 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002556
John McCall33ddac02011-01-19 10:06:00 +00002557 // Be sure to pull qualifiers off the element type.
2558 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2559 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002560 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002561 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002562 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002563 }
2564
John McCall90d1c2d2009-09-24 23:30:46 +00002565 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002566 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002567
2568 VariableArrayTypes.push_back(New);
2569 Types.push_back(New);
2570 return QualType(New, 0);
2571}
2572
Douglas Gregor4619e432008-12-05 23:32:09 +00002573/// getDependentSizedArrayType - Returns a non-unique reference to
2574/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002575/// type.
John McCall33ddac02011-01-19 10:06:00 +00002576QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2577 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002578 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002579 unsigned elementTypeQuals,
2580 SourceRange brackets) const {
2581 assert((!numElements || numElements->isTypeDependent() ||
2582 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002583 "Size must be type- or value-dependent!");
2584
John McCall33ddac02011-01-19 10:06:00 +00002585 // Dependently-sized array types that do not have a specified number
2586 // of elements will have their sizes deduced from a dependent
2587 // initializer. We do no canonicalization here at all, which is okay
2588 // because they can't be used in most locations.
2589 if (!numElements) {
2590 DependentSizedArrayType *newType
2591 = new (*this, TypeAlignment)
2592 DependentSizedArrayType(*this, elementType, QualType(),
2593 numElements, ASM, elementTypeQuals,
2594 brackets);
2595 Types.push_back(newType);
2596 return QualType(newType, 0);
2597 }
2598
2599 // Otherwise, we actually build a new type every time, but we
2600 // also build a canonical type.
2601
2602 SplitQualType canonElementType = getCanonicalType(elementType).split();
2603
2604 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002605 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002606 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002607 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002608 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002609
John McCall33ddac02011-01-19 10:06:00 +00002610 // Look for an existing type with these properties.
2611 DependentSizedArrayType *canonTy =
2612 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002613
John McCall33ddac02011-01-19 10:06:00 +00002614 // If we don't have one, build one.
2615 if (!canonTy) {
2616 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002617 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002618 QualType(), numElements, ASM, elementTypeQuals,
2619 brackets);
2620 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2621 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002622 }
2623
John McCall33ddac02011-01-19 10:06:00 +00002624 // Apply qualifiers from the element type to the array.
2625 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002626 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002627
John McCall33ddac02011-01-19 10:06:00 +00002628 // If we didn't need extra canonicalization for the element type,
2629 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002630 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002631 return canon;
2632
2633 // Otherwise, we need to build a type which follows the spelling
2634 // of the element type.
2635 DependentSizedArrayType *sugaredType
2636 = new (*this, TypeAlignment)
2637 DependentSizedArrayType(*this, elementType, canon, numElements,
2638 ASM, elementTypeQuals, brackets);
2639 Types.push_back(sugaredType);
2640 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002641}
2642
John McCall33ddac02011-01-19 10:06:00 +00002643QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002644 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002645 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002646 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002647 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002648
John McCall33ddac02011-01-19 10:06:00 +00002649 void *insertPos = 0;
2650 if (IncompleteArrayType *iat =
2651 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2652 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002653
2654 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002655 // either, so fill in the canonical type field. We also have to pull
2656 // qualifiers off the element type.
2657 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002658
John McCall33ddac02011-01-19 10:06:00 +00002659 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2660 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002661 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002662 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002663 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002664
2665 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002666 IncompleteArrayType *existing =
2667 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2668 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002669 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002670
John McCall33ddac02011-01-19 10:06:00 +00002671 IncompleteArrayType *newType = new (*this, TypeAlignment)
2672 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002673
John McCall33ddac02011-01-19 10:06:00 +00002674 IncompleteArrayTypes.InsertNode(newType, insertPos);
2675 Types.push_back(newType);
2676 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002677}
2678
Steve Naroff91fcddb2007-07-18 18:00:27 +00002679/// getVectorType - Return the unique reference to a vector type of
2680/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002681QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002682 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002683 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002684
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002685 // Check if we've already instantiated a vector of this type.
2686 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002687 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002688
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002689 void *InsertPos = 0;
2690 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2691 return QualType(VTP, 0);
2692
2693 // If the element type isn't canonical, this won't be a canonical type either,
2694 // so fill in the canonical type field.
2695 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002696 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002697 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002698
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002699 // Get the new insert position for the node we care about.
2700 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002701 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002702 }
John McCall90d1c2d2009-09-24 23:30:46 +00002703 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002704 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002705 VectorTypes.InsertNode(New, InsertPos);
2706 Types.push_back(New);
2707 return QualType(New, 0);
2708}
2709
Nate Begemance4d7fc2008-04-18 23:10:10 +00002710/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002711/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002712QualType
2713ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002714 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002715
Steve Naroff91fcddb2007-07-18 18:00:27 +00002716 // Check if we've already instantiated a vector of this type.
2717 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002718 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002719 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002720 void *InsertPos = 0;
2721 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2722 return QualType(VTP, 0);
2723
2724 // If the element type isn't canonical, this won't be a canonical type either,
2725 // so fill in the canonical type field.
2726 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002727 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002728 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002729
Steve Naroff91fcddb2007-07-18 18:00:27 +00002730 // Get the new insert position for the node we care about.
2731 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002732 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002733 }
John McCall90d1c2d2009-09-24 23:30:46 +00002734 ExtVectorType *New = new (*this, TypeAlignment)
2735 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002736 VectorTypes.InsertNode(New, InsertPos);
2737 Types.push_back(New);
2738 return QualType(New, 0);
2739}
2740
Jay Foad39c79802011-01-12 09:06:06 +00002741QualType
2742ASTContext::getDependentSizedExtVectorType(QualType vecType,
2743 Expr *SizeExpr,
2744 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002745 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002746 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002747 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002748
Douglas Gregor352169a2009-07-31 03:54:25 +00002749 void *InsertPos = 0;
2750 DependentSizedExtVectorType *Canon
2751 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2752 DependentSizedExtVectorType *New;
2753 if (Canon) {
2754 // We already have a canonical version of this array type; use it as
2755 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002756 New = new (*this, TypeAlignment)
2757 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2758 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002759 } else {
2760 QualType CanonVecTy = getCanonicalType(vecType);
2761 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002762 New = new (*this, TypeAlignment)
2763 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2764 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002765
2766 DependentSizedExtVectorType *CanonCheck
2767 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2768 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2769 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002770 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2771 } else {
2772 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2773 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002774 New = new (*this, TypeAlignment)
2775 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002776 }
2777 }
Mike Stump11289f42009-09-09 15:08:12 +00002778
Douglas Gregor758a8692009-06-17 21:51:59 +00002779 Types.push_back(New);
2780 return QualType(New, 0);
2781}
2782
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002783/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002784///
Jay Foad39c79802011-01-12 09:06:06 +00002785QualType
2786ASTContext::getFunctionNoProtoType(QualType ResultTy,
2787 const FunctionType::ExtInfo &Info) const {
Reid Kleckner78af0702013-08-27 23:08:25 +00002788 const CallingConv CallConv = Info.getCC();
2789
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002790 // Unique functions, to guarantee there is only one function of a particular
2791 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002792 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002793 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002794
Chris Lattner47955de2007-01-27 08:37:20 +00002795 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002796 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002797 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002798 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002799
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002800 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002801 if (!ResultTy.isCanonical()) {
2802 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00002803
Chris Lattner47955de2007-01-27 08:37:20 +00002804 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002805 FunctionNoProtoType *NewIP =
2806 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002807 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002808 }
Mike Stump11289f42009-09-09 15:08:12 +00002809
Roman Divacky65b88cd2011-03-01 17:40:53 +00002810 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002811 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002812 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002813 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002814 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002815 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002816}
2817
Douglas Gregorcd780372013-01-17 23:36:45 +00002818/// \brief Determine whether \p T is canonical as the result type of a function.
2819static bool isCanonicalResultType(QualType T) {
2820 return T.isCanonical() &&
2821 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2822 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2823}
2824
Jay Foad39c79802011-01-12 09:06:06 +00002825QualType
Jordan Rose5c382722013-03-08 21:51:21 +00002826ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00002827 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00002828 size_t NumArgs = ArgArray.size();
2829
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002830 // Unique functions, to guarantee there is only one function of a particular
2831 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002832 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00002833 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2834 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002835
2836 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002837 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002838 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002839 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002840
2841 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002842 bool isCanonical =
Douglas Gregorcd780372013-01-17 23:36:45 +00002843 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00002844 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002845 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002846 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002847 isCanonical = false;
2848
2849 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002850 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002851 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002852 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002853 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002854 CanonicalArgs.reserve(NumArgs);
2855 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002856 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002857
John McCalldb40c7f2010-12-14 08:05:40 +00002858 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002859 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002860 CanonicalEPI.ExceptionSpecType = EST_None;
2861 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002862
Douglas Gregorcd780372013-01-17 23:36:45 +00002863 // Result types do not have ARC lifetime qualifiers.
2864 QualType CanResultTy = getCanonicalType(ResultTy);
2865 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2866 Qualifiers Qs = CanResultTy.getQualifiers();
2867 Qs.removeObjCLifetime();
2868 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2869 }
2870
Jordan Rose5c382722013-03-08 21:51:21 +00002871 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002872
Chris Lattnerfd4de792007-01-27 01:15:32 +00002873 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002874 FunctionProtoType *NewIP =
2875 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002876 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002877 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002878
John McCall31168b02011-06-15 23:02:42 +00002879 // FunctionProtoType objects are allocated with extra bytes after
2880 // them for three variable size arrays at the end:
2881 // - parameter types
2882 // - exception types
2883 // - consumed-arguments flags
2884 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002885 // expression, or information used to resolve the exception
2886 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002887 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002888 NumArgs * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002889 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002890 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002891 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002892 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002893 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002894 Size += 2 * sizeof(FunctionDecl*);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002895 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2896 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002897 }
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002898 if (EPI.ConsumedParameters)
John McCall31168b02011-06-15 23:02:42 +00002899 Size += NumArgs * sizeof(bool);
2900
John McCalldb40c7f2010-12-14 08:05:40 +00002901 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002902 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00002903 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002904 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002905 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002906 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002907}
Chris Lattneref51c202006-11-10 07:17:23 +00002908
John McCalle78aac42010-03-10 03:28:59 +00002909#ifndef NDEBUG
2910static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2911 if (!isa<CXXRecordDecl>(D)) return false;
2912 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2913 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2914 return true;
2915 if (RD->getDescribedClassTemplate() &&
2916 !isa<ClassTemplateSpecializationDecl>(RD))
2917 return true;
2918 return false;
2919}
2920#endif
2921
2922/// getInjectedClassNameType - Return the unique reference to the
2923/// injected class name type for the specified templated declaration.
2924QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002925 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002926 assert(NeedsInjectedClassNameType(Decl));
2927 if (Decl->TypeForDecl) {
2928 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002929 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002930 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2931 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2932 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2933 } else {
John McCall424cec92011-01-19 06:33:43 +00002934 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002935 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002936 Decl->TypeForDecl = newType;
2937 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002938 }
2939 return QualType(Decl->TypeForDecl, 0);
2940}
2941
Douglas Gregor83a586e2008-04-13 21:07:44 +00002942/// getTypeDeclType - Return the unique reference to the type for the
2943/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002944QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002945 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002946 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002947
Richard Smithdda56e42011-04-15 14:24:37 +00002948 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002949 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002950
John McCall96f0b5f2010-03-10 06:48:02 +00002951 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2952 "Template type parameter types are always available.");
2953
John McCall81e38502010-02-16 03:57:14 +00002954 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00002955 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00002956 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002957 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002958 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00002959 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002960 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002961 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002962 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002963 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2964 Decl->TypeForDecl = newType;
2965 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002966 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002967 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002968
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002969 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002970}
2971
Chris Lattner32d920b2007-01-26 02:01:53 +00002972/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002973/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002974QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002975ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2976 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002977 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002978
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002979 if (Canonical.isNull())
2980 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002981 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002982 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002983 Decl->TypeForDecl = newType;
2984 Types.push_back(newType);
2985 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002986}
2987
Jay Foad39c79802011-01-12 09:06:06 +00002988QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002989 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2990
Douglas Gregorec9fd132012-01-14 16:38:05 +00002991 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002992 if (PrevDecl->TypeForDecl)
2993 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2994
John McCall424cec92011-01-19 06:33:43 +00002995 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2996 Decl->TypeForDecl = newType;
2997 Types.push_back(newType);
2998 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002999}
3000
Jay Foad39c79802011-01-12 09:06:06 +00003001QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003002 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3003
Douglas Gregorec9fd132012-01-14 16:38:05 +00003004 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003005 if (PrevDecl->TypeForDecl)
3006 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3007
John McCall424cec92011-01-19 06:33:43 +00003008 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3009 Decl->TypeForDecl = newType;
3010 Types.push_back(newType);
3011 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003012}
3013
John McCall81904512011-01-06 01:58:22 +00003014QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3015 QualType modifiedType,
3016 QualType equivalentType) {
3017 llvm::FoldingSetNodeID id;
3018 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3019
3020 void *insertPos = 0;
3021 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3022 if (type) return QualType(type, 0);
3023
3024 QualType canon = getCanonicalType(equivalentType);
3025 type = new (*this, TypeAlignment)
3026 AttributedType(canon, attrKind, modifiedType, equivalentType);
3027
3028 Types.push_back(type);
3029 AttributedTypes.InsertNode(type, insertPos);
3030
3031 return QualType(type, 0);
3032}
3033
3034
John McCallcebee162009-10-18 09:09:24 +00003035/// \brief Retrieve a substitution-result type.
3036QualType
3037ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003038 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003039 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003040 && "replacement types must always be canonical");
3041
3042 llvm::FoldingSetNodeID ID;
3043 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3044 void *InsertPos = 0;
3045 SubstTemplateTypeParmType *SubstParm
3046 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3047
3048 if (!SubstParm) {
3049 SubstParm = new (*this, TypeAlignment)
3050 SubstTemplateTypeParmType(Parm, Replacement);
3051 Types.push_back(SubstParm);
3052 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3053 }
3054
3055 return QualType(SubstParm, 0);
3056}
3057
Douglas Gregorada4b792011-01-14 02:55:32 +00003058/// \brief Retrieve a
3059QualType ASTContext::getSubstTemplateTypeParmPackType(
3060 const TemplateTypeParmType *Parm,
3061 const TemplateArgument &ArgPack) {
3062#ifndef NDEBUG
3063 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
3064 PEnd = ArgPack.pack_end();
3065 P != PEnd; ++P) {
3066 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3067 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
3068 }
3069#endif
3070
3071 llvm::FoldingSetNodeID ID;
3072 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3073 void *InsertPos = 0;
3074 if (SubstTemplateTypeParmPackType *SubstParm
3075 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3076 return QualType(SubstParm, 0);
3077
3078 QualType Canon;
3079 if (!Parm->isCanonicalUnqualified()) {
3080 Canon = getCanonicalType(QualType(Parm, 0));
3081 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3082 ArgPack);
3083 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3084 }
3085
3086 SubstTemplateTypeParmPackType *SubstParm
3087 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3088 ArgPack);
3089 Types.push_back(SubstParm);
3090 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3091 return QualType(SubstParm, 0);
3092}
3093
Douglas Gregoreff93e02009-02-05 23:33:38 +00003094/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003095/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003096/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003097QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003098 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003099 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003100 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003101 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003102 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003103 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003104 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3105
3106 if (TypeParm)
3107 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003108
Chandler Carruth08836322011-05-01 00:51:33 +00003109 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003110 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003111 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003112
3113 TemplateTypeParmType *TypeCheck
3114 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3115 assert(!TypeCheck && "Template type parameter canonical type broken");
3116 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003117 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003118 TypeParm = new (*this, TypeAlignment)
3119 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003120
3121 Types.push_back(TypeParm);
3122 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3123
3124 return QualType(TypeParm, 0);
3125}
3126
John McCalle78aac42010-03-10 03:28:59 +00003127TypeSourceInfo *
3128ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3129 SourceLocation NameLoc,
3130 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003131 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003132 assert(!Name.getAsDependentTemplateName() &&
3133 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003134 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003135
3136 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003137 TemplateSpecializationTypeLoc TL =
3138 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003139 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003140 TL.setTemplateNameLoc(NameLoc);
3141 TL.setLAngleLoc(Args.getLAngleLoc());
3142 TL.setRAngleLoc(Args.getRAngleLoc());
3143 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3144 TL.setArgLocInfo(i, Args[i].getLocInfo());
3145 return DI;
3146}
3147
Mike Stump11289f42009-09-09 15:08:12 +00003148QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003149ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003150 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003151 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003152 assert(!Template.getAsDependentTemplateName() &&
3153 "No dependent template names here!");
3154
John McCall6b51f282009-11-23 01:53:49 +00003155 unsigned NumArgs = Args.size();
3156
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003157 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003158 ArgVec.reserve(NumArgs);
3159 for (unsigned i = 0; i != NumArgs; ++i)
3160 ArgVec.push_back(Args[i].getArgument());
3161
John McCall2408e322010-04-27 00:57:59 +00003162 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003163 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003164}
3165
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003166#ifndef NDEBUG
3167static bool hasAnyPackExpansions(const TemplateArgument *Args,
3168 unsigned NumArgs) {
3169 for (unsigned I = 0; I != NumArgs; ++I)
3170 if (Args[I].isPackExpansion())
3171 return true;
3172
3173 return true;
3174}
3175#endif
3176
John McCall0ad16662009-10-29 08:12:44 +00003177QualType
3178ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003179 const TemplateArgument *Args,
3180 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003181 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003182 assert(!Template.getAsDependentTemplateName() &&
3183 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003184 // Look through qualified template names.
3185 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3186 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003187
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003188 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003189 Template.getAsTemplateDecl() &&
3190 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003191 QualType CanonType;
3192 if (!Underlying.isNull())
3193 CanonType = getCanonicalType(Underlying);
3194 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003195 // We can get here with an alias template when the specialization contains
3196 // a pack expansion that does not match up with a parameter pack.
3197 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3198 "Caller must compute aliased type");
3199 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003200 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3201 NumArgs);
3202 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003203
Douglas Gregora8e02e72009-07-28 23:00:59 +00003204 // Allocate the (non-canonical) template specialization type, but don't
3205 // try to unique it: these types typically have location information that
3206 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003207 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3208 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003209 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003210 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003211 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003212 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3213 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003214
Douglas Gregor8bf42052009-02-09 18:46:07 +00003215 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003216 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003217}
3218
Mike Stump11289f42009-09-09 15:08:12 +00003219QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003220ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3221 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003222 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003223 assert(!Template.getAsDependentTemplateName() &&
3224 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003225
Douglas Gregore29139c2011-03-03 17:04:51 +00003226 // Look through qualified template names.
3227 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3228 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003229
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003230 // Build the canonical template specialization type.
3231 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003232 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003233 CanonArgs.reserve(NumArgs);
3234 for (unsigned I = 0; I != NumArgs; ++I)
3235 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3236
3237 // Determine whether this canonical template specialization type already
3238 // exists.
3239 llvm::FoldingSetNodeID ID;
3240 TemplateSpecializationType::Profile(ID, CanonTemplate,
3241 CanonArgs.data(), NumArgs, *this);
3242
3243 void *InsertPos = 0;
3244 TemplateSpecializationType *Spec
3245 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3246
3247 if (!Spec) {
3248 // Allocate a new canonical template specialization type.
3249 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3250 sizeof(TemplateArgument) * NumArgs),
3251 TypeAlignment);
3252 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3253 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003254 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003255 Types.push_back(Spec);
3256 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3257 }
3258
3259 assert(Spec->isDependentType() &&
3260 "Non-dependent template-id type must have a canonical type");
3261 return QualType(Spec, 0);
3262}
3263
3264QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003265ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3266 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003267 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003268 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003269 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003270
3271 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003272 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003273 if (T)
3274 return QualType(T, 0);
3275
Douglas Gregorc42075a2010-02-04 18:10:26 +00003276 QualType Canon = NamedType;
3277 if (!Canon.isCanonical()) {
3278 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003279 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3280 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003281 (void)CheckT;
3282 }
3283
Abramo Bagnara6150c882010-05-11 21:36:43 +00003284 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003285 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003286 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003287 return QualType(T, 0);
3288}
3289
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003290QualType
Jay Foad39c79802011-01-12 09:06:06 +00003291ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003292 llvm::FoldingSetNodeID ID;
3293 ParenType::Profile(ID, InnerType);
3294
3295 void *InsertPos = 0;
3296 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3297 if (T)
3298 return QualType(T, 0);
3299
3300 QualType Canon = InnerType;
3301 if (!Canon.isCanonical()) {
3302 Canon = getCanonicalType(InnerType);
3303 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3304 assert(!CheckT && "Paren canonical type broken");
3305 (void)CheckT;
3306 }
3307
3308 T = new (*this) ParenType(InnerType, Canon);
3309 Types.push_back(T);
3310 ParenTypes.InsertNode(T, InsertPos);
3311 return QualType(T, 0);
3312}
3313
Douglas Gregor02085352010-03-31 20:19:30 +00003314QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3315 NestedNameSpecifier *NNS,
3316 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003317 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003318 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3319
3320 if (Canon.isNull()) {
3321 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003322 ElaboratedTypeKeyword CanonKeyword = Keyword;
3323 if (Keyword == ETK_None)
3324 CanonKeyword = ETK_Typename;
3325
3326 if (CanonNNS != NNS || CanonKeyword != Keyword)
3327 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003328 }
3329
3330 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003331 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003332
3333 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003334 DependentNameType *T
3335 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003336 if (T)
3337 return QualType(T, 0);
3338
Douglas Gregor02085352010-03-31 20:19:30 +00003339 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003340 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003341 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003342 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003343}
3344
Mike Stump11289f42009-09-09 15:08:12 +00003345QualType
John McCallc392f372010-06-11 00:33:02 +00003346ASTContext::getDependentTemplateSpecializationType(
3347 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003348 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003349 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003350 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003351 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003352 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003353 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3354 ArgCopy.push_back(Args[I].getArgument());
3355 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3356 ArgCopy.size(),
3357 ArgCopy.data());
3358}
3359
3360QualType
3361ASTContext::getDependentTemplateSpecializationType(
3362 ElaboratedTypeKeyword Keyword,
3363 NestedNameSpecifier *NNS,
3364 const IdentifierInfo *Name,
3365 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003366 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003367 assert((!NNS || NNS->isDependent()) &&
3368 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003369
Douglas Gregorc42075a2010-02-04 18:10:26 +00003370 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003371 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3372 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003373
3374 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00003375 DependentTemplateSpecializationType *T
3376 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003377 if (T)
3378 return QualType(T, 0);
3379
John McCallc392f372010-06-11 00:33:02 +00003380 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003381
John McCallc392f372010-06-11 00:33:02 +00003382 ElaboratedTypeKeyword CanonKeyword = Keyword;
3383 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3384
3385 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003386 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003387 for (unsigned I = 0; I != NumArgs; ++I) {
3388 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3389 if (!CanonArgs[I].structurallyEquals(Args[I]))
3390 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003391 }
3392
John McCallc392f372010-06-11 00:33:02 +00003393 QualType Canon;
3394 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3395 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3396 Name, NumArgs,
3397 CanonArgs.data());
3398
3399 // Find the insert position again.
3400 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3401 }
3402
3403 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3404 sizeof(TemplateArgument) * NumArgs),
3405 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003406 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003407 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003408 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003409 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003410 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003411}
3412
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003413QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003414 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003415 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003416 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003417
3418 assert(Pattern->containsUnexpandedParameterPack() &&
3419 "Pack expansions must expand one or more parameter packs");
3420 void *InsertPos = 0;
3421 PackExpansionType *T
3422 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3423 if (T)
3424 return QualType(T, 0);
3425
3426 QualType Canon;
3427 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003428 Canon = getCanonicalType(Pattern);
3429 // The canonical type might not contain an unexpanded parameter pack, if it
3430 // contains an alias template specialization which ignores one of its
3431 // parameters.
3432 if (Canon->containsUnexpandedParameterPack()) {
3433 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003434
Richard Smith68eea502012-07-16 00:20:35 +00003435 // Find the insert position again, in case we inserted an element into
3436 // PackExpansionTypes and invalidated our insert position.
3437 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3438 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003439 }
3440
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003441 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003442 Types.push_back(T);
3443 PackExpansionTypes.InsertNode(T, InsertPos);
3444 return QualType(T, 0);
3445}
3446
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003447/// CmpProtocolNames - Comparison predicate for sorting protocols
3448/// alphabetically.
3449static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3450 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003451 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003452}
3453
John McCall8b07ec22010-05-15 11:32:37 +00003454static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003455 unsigned NumProtocols) {
3456 if (NumProtocols == 0) return true;
3457
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003458 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3459 return false;
3460
John McCallfc93cf92009-10-22 22:37:11 +00003461 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003462 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3463 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003464 return false;
3465 return true;
3466}
3467
3468static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003469 unsigned &NumProtocols) {
3470 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003471
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003472 // Sort protocols, keyed by name.
3473 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3474
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003475 // Canonicalize.
3476 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3477 Protocols[I] = Protocols[I]->getCanonicalDecl();
3478
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003479 // Remove duplicates.
3480 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3481 NumProtocols = ProtocolsEnd-Protocols;
3482}
3483
John McCall8b07ec22010-05-15 11:32:37 +00003484QualType ASTContext::getObjCObjectType(QualType BaseType,
3485 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003486 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003487 // If the base type is an interface and there aren't any protocols
3488 // to add, then the interface type will do just fine.
3489 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3490 return BaseType;
3491
3492 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003493 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003494 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00003495 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00003496 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3497 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003498
John McCall8b07ec22010-05-15 11:32:37 +00003499 // Build the canonical type, which has the canonical base type and
3500 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003501 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003502 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3503 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3504 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003505 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003506 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003507 unsigned UniqueCount = NumProtocols;
3508
John McCallfc93cf92009-10-22 22:37:11 +00003509 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003510 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3511 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003512 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003513 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3514 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003515 }
3516
3517 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003518 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3519 }
3520
3521 unsigned Size = sizeof(ObjCObjectTypeImpl);
3522 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3523 void *Mem = Allocate(Size, TypeAlignment);
3524 ObjCObjectTypeImpl *T =
3525 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3526
3527 Types.push_back(T);
3528 ObjCObjectTypes.InsertNode(T, InsertPos);
3529 return QualType(T, 0);
3530}
3531
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003532/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3533/// protocol list adopt all protocols in QT's qualified-id protocol
3534/// list.
3535bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3536 ObjCInterfaceDecl *IC) {
3537 if (!QT->isObjCQualifiedIdType())
3538 return false;
3539
3540 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3541 // If both the right and left sides have qualifiers.
3542 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3543 E = OPT->qual_end(); I != E; ++I) {
3544 ObjCProtocolDecl *Proto = *I;
3545 if (!IC->ClassImplementsProtocol(Proto, false))
3546 return false;
3547 }
3548 return true;
3549 }
3550 return false;
3551}
3552
3553/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3554/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3555/// of protocols.
3556bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3557 ObjCInterfaceDecl *IDecl) {
3558 if (!QT->isObjCQualifiedIdType())
3559 return false;
3560 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3561 if (!OPT)
3562 return false;
3563 if (!IDecl->hasDefinition())
3564 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003565 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3566 CollectInheritedProtocols(IDecl, InheritedProtocols);
3567 if (InheritedProtocols.empty())
3568 return false;
3569
3570 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator PI =
3571 InheritedProtocols.begin(),
3572 E = InheritedProtocols.end(); PI != E; ++PI) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003573 // If both the right and left sides have qualifiers.
3574 bool Adopts = false;
3575 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3576 E = OPT->qual_end(); I != E; ++I) {
3577 ObjCProtocolDecl *Proto = *I;
3578 // return 'true' if '*PI' is in the inheritance hierarchy of Proto
3579 if ((Adopts = ProtocolCompatibleWithProtocol(*PI, Proto)))
3580 break;
3581 }
3582 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003583 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003584 }
3585 return true;
3586}
3587
John McCall8b07ec22010-05-15 11:32:37 +00003588/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3589/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003590QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003591 llvm::FoldingSetNodeID ID;
3592 ObjCObjectPointerType::Profile(ID, ObjectT);
3593
3594 void *InsertPos = 0;
3595 if (ObjCObjectPointerType *QT =
3596 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3597 return QualType(QT, 0);
3598
3599 // Find the canonical object type.
3600 QualType Canonical;
3601 if (!ObjectT.isCanonical()) {
3602 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3603
3604 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003605 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3606 }
3607
Douglas Gregorf85bee62010-02-08 22:59:26 +00003608 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003609 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3610 ObjCObjectPointerType *QType =
3611 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003612
Steve Narofffb4330f2009-06-17 22:40:22 +00003613 Types.push_back(QType);
3614 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003615 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003616}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003617
Douglas Gregor1c283312010-08-11 12:19:30 +00003618/// getObjCInterfaceType - Return the unique reference to the type for the
3619/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003620QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3621 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003622 if (Decl->TypeForDecl)
3623 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003624
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003625 if (PrevDecl) {
3626 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3627 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3628 return QualType(PrevDecl->TypeForDecl, 0);
3629 }
3630
Douglas Gregor7671e532011-12-16 16:34:57 +00003631 // Prefer the definition, if there is one.
3632 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3633 Decl = Def;
3634
Douglas Gregor1c283312010-08-11 12:19:30 +00003635 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3636 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3637 Decl->TypeForDecl = T;
3638 Types.push_back(T);
3639 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003640}
3641
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003642/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3643/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003644/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003645/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003646/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003647QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003648 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003649 if (tofExpr->isTypeDependent()) {
3650 llvm::FoldingSetNodeID ID;
3651 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003652
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003653 void *InsertPos = 0;
3654 DependentTypeOfExprType *Canon
3655 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3656 if (Canon) {
3657 // We already have a "canonical" version of an identical, dependent
3658 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003659 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003660 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003661 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003662 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003663 Canon
3664 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003665 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3666 toe = Canon;
3667 }
3668 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003669 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003670 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003671 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003672 Types.push_back(toe);
3673 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003674}
3675
Steve Naroffa773cd52007-08-01 18:02:17 +00003676/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3677/// TypeOfType AST's. The only motivation to unique these nodes would be
3678/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003679/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003680/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003681QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003682 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003683 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003684 Types.push_back(tot);
3685 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003686}
3687
Anders Carlssonad6bd352009-06-24 21:24:56 +00003688
Anders Carlsson81df7b82009-06-24 19:06:50 +00003689/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3690/// DecltypeType AST's. The only motivation to unique these nodes would be
3691/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003692/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003693/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003694QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003695 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003696
3697 // C++0x [temp.type]p2:
3698 // If an expression e involves a template parameter, decltype(e) denotes a
3699 // unique dependent type. Two such decltype-specifiers refer to the same
3700 // type only if their expressions are equivalent (14.5.6.1).
3701 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003702 llvm::FoldingSetNodeID ID;
3703 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003704
Douglas Gregora21f6c32009-07-30 23:36:40 +00003705 void *InsertPos = 0;
3706 DependentDecltypeType *Canon
3707 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3708 if (Canon) {
3709 // We already have a "canonical" version of an equivalent, dependent
3710 // decltype type. Use that as our canonical type.
Richard Smithef8bf432012-08-13 20:08:14 +00003711 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003712 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003713 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003714 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003715 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003716 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3717 dt = Canon;
3718 }
3719 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003720 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3721 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003722 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003723 Types.push_back(dt);
3724 return QualType(dt, 0);
3725}
3726
Alexis Hunte852b102011-05-24 22:41:36 +00003727/// getUnaryTransformationType - We don't unique these, since the memory
3728/// savings are minimal and these are rare.
3729QualType ASTContext::getUnaryTransformType(QualType BaseType,
3730 QualType UnderlyingType,
3731 UnaryTransformType::UTTKind Kind)
3732 const {
3733 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003734 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3735 Kind,
3736 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003737 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003738 Types.push_back(Ty);
3739 return QualType(Ty, 0);
3740}
3741
Richard Smith2a7d4812013-05-04 07:00:32 +00003742/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3743/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3744/// canonical deduced-but-dependent 'auto' type.
3745QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003746 bool IsDependent) const {
3747 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00003748 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003749
Richard Smith2a7d4812013-05-04 07:00:32 +00003750 // Look in the folding set for an existing type.
Richard Smithb2bc2e62011-02-21 20:05:19 +00003751 void *InsertPos = 0;
Richard Smith2a7d4812013-05-04 07:00:32 +00003752 llvm::FoldingSetNodeID ID;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003753 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00003754 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3755 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003756
Richard Smith74aeef52013-04-26 16:15:35 +00003757 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smith27d807c2013-04-30 13:56:41 +00003758 IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003759 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003760 Types.push_back(AT);
3761 if (InsertPos)
3762 AutoTypes.InsertNode(AT, InsertPos);
3763 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003764}
3765
Eli Friedman0dfb8892011-10-06 23:00:33 +00003766/// getAtomicType - Return the uniqued reference to the atomic type for
3767/// the given value type.
3768QualType ASTContext::getAtomicType(QualType T) const {
3769 // Unique pointers, to guarantee there is only one pointer of a particular
3770 // structure.
3771 llvm::FoldingSetNodeID ID;
3772 AtomicType::Profile(ID, T);
3773
3774 void *InsertPos = 0;
3775 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3776 return QualType(AT, 0);
3777
3778 // If the atomic value type isn't canonical, this won't be a canonical type
3779 // either, so fill in the canonical type field.
3780 QualType Canonical;
3781 if (!T.isCanonical()) {
3782 Canonical = getAtomicType(getCanonicalType(T));
3783
3784 // Get the new insert position for the node we care about.
3785 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3786 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3787 }
3788 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3789 Types.push_back(New);
3790 AtomicTypes.InsertNode(New, InsertPos);
3791 return QualType(New, 0);
3792}
3793
Richard Smith02e85f32011-04-14 22:09:26 +00003794/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3795QualType ASTContext::getAutoDeductType() const {
3796 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00003797 AutoDeductTy = QualType(
3798 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003799 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00003800 0);
Richard Smith02e85f32011-04-14 22:09:26 +00003801 return AutoDeductTy;
3802}
3803
3804/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3805QualType ASTContext::getAutoRRefDeductType() const {
3806 if (AutoRRefDeductTy.isNull())
3807 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3808 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3809 return AutoRRefDeductTy;
3810}
3811
Chris Lattnerfb072462007-01-23 05:45:31 +00003812/// getTagDeclType - Return the unique reference to the type for the
3813/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003814QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003815 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003816 // FIXME: What is the design on getTagDeclType when it requires casting
3817 // away const? mutable?
3818 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003819}
3820
Mike Stump11289f42009-09-09 15:08:12 +00003821/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3822/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3823/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003824CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003825 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003826}
Chris Lattnerfb072462007-01-23 05:45:31 +00003827
Hans Wennborg27541db2011-10-27 08:29:09 +00003828/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3829CanQualType ASTContext::getIntMaxType() const {
3830 return getFromTargetType(Target->getIntMaxType());
3831}
3832
3833/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3834CanQualType ASTContext::getUIntMaxType() const {
3835 return getFromTargetType(Target->getUIntMaxType());
3836}
3837
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003838/// getSignedWCharType - Return the type of "signed wchar_t".
3839/// Used when in C++, as a GCC extension.
3840QualType ASTContext::getSignedWCharType() const {
3841 // FIXME: derive from "Target" ?
3842 return WCharTy;
3843}
3844
3845/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3846/// Used when in C++, as a GCC extension.
3847QualType ASTContext::getUnsignedWCharType() const {
3848 // FIXME: derive from "Target" ?
3849 return UnsignedIntTy;
3850}
3851
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00003852QualType ASTContext::getIntPtrType() const {
3853 return getFromTargetType(Target->getIntPtrType());
3854}
3855
3856QualType ASTContext::getUIntPtrType() const {
3857 return getCorrespondingUnsignedType(getIntPtrType());
3858}
3859
Hans Wennborg27541db2011-10-27 08:29:09 +00003860/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003861/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3862QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003863 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003864}
3865
Eli Friedman4e91899e2012-11-27 02:58:24 +00003866/// \brief Return the unique type for "pid_t" defined in
3867/// <sys/types.h>. We need this to compute the correct type for vfork().
3868QualType ASTContext::getProcessIDType() const {
3869 return getFromTargetType(Target->getProcessIDType());
3870}
3871
Chris Lattnera21ad802008-04-02 05:18:44 +00003872//===----------------------------------------------------------------------===//
3873// Type Operators
3874//===----------------------------------------------------------------------===//
3875
Jay Foad39c79802011-01-12 09:06:06 +00003876CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003877 // Push qualifiers into arrays, and then discard any remaining
3878 // qualifiers.
3879 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003880 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003881 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003882 QualType Result;
3883 if (isa<ArrayType>(Ty)) {
3884 Result = getArrayDecayedType(QualType(Ty,0));
3885 } else if (isa<FunctionType>(Ty)) {
3886 Result = getPointerType(QualType(Ty, 0));
3887 } else {
3888 Result = QualType(Ty, 0);
3889 }
3890
3891 return CanQualType::CreateUnsafe(Result);
3892}
3893
John McCall6c9dd522011-01-18 07:41:22 +00003894QualType ASTContext::getUnqualifiedArrayType(QualType type,
3895 Qualifiers &quals) {
3896 SplitQualType splitType = type.getSplitUnqualifiedType();
3897
3898 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3899 // the unqualified desugared type and then drops it on the floor.
3900 // We then have to strip that sugar back off with
3901 // getUnqualifiedDesugaredType(), which is silly.
3902 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003903 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003904
3905 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003906 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003907 quals = splitType.Quals;
3908 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003909 }
3910
John McCall6c9dd522011-01-18 07:41:22 +00003911 // Otherwise, recurse on the array's element type.
3912 QualType elementType = AT->getElementType();
3913 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3914
3915 // If that didn't change the element type, AT has no qualifiers, so we
3916 // can just use the results in splitType.
3917 if (elementType == unqualElementType) {
3918 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003919 quals = splitType.Quals;
3920 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003921 }
3922
3923 // Otherwise, add in the qualifiers from the outermost type, then
3924 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003925 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003926
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003927 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003928 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003929 CAT->getSizeModifier(), 0);
3930 }
3931
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003932 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003933 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003934 }
3935
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003936 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003937 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003938 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003939 VAT->getSizeModifier(),
3940 VAT->getIndexTypeCVRQualifiers(),
3941 VAT->getBracketsRange());
3942 }
3943
3944 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003945 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003946 DSAT->getSizeModifier(), 0,
3947 SourceRange());
3948}
3949
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003950/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3951/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3952/// they point to and return true. If T1 and T2 aren't pointer types
3953/// or pointer-to-member types, or if they are not similar at this
3954/// level, returns false and leaves T1 and T2 unchanged. Top-level
3955/// qualifiers on T1 and T2 are ignored. This function will typically
3956/// be called in a loop that successively "unwraps" pointer and
3957/// pointer-to-member types to compare them at each level.
3958bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3959 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3960 *T2PtrType = T2->getAs<PointerType>();
3961 if (T1PtrType && T2PtrType) {
3962 T1 = T1PtrType->getPointeeType();
3963 T2 = T2PtrType->getPointeeType();
3964 return true;
3965 }
3966
3967 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3968 *T2MPType = T2->getAs<MemberPointerType>();
3969 if (T1MPType && T2MPType &&
3970 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3971 QualType(T2MPType->getClass(), 0))) {
3972 T1 = T1MPType->getPointeeType();
3973 T2 = T2MPType->getPointeeType();
3974 return true;
3975 }
3976
David Blaikiebbafb8a2012-03-11 07:00:24 +00003977 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003978 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3979 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3980 if (T1OPType && T2OPType) {
3981 T1 = T1OPType->getPointeeType();
3982 T2 = T2OPType->getPointeeType();
3983 return true;
3984 }
3985 }
3986
3987 // FIXME: Block pointers, too?
3988
3989 return false;
3990}
3991
Jay Foad39c79802011-01-12 09:06:06 +00003992DeclarationNameInfo
3993ASTContext::getNameForTemplate(TemplateName Name,
3994 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003995 switch (Name.getKind()) {
3996 case TemplateName::QualifiedTemplate:
3997 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003998 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003999 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4000 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004001
John McCalld9dfe3a2011-06-30 08:33:18 +00004002 case TemplateName::OverloadedTemplate: {
4003 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4004 // DNInfo work in progress: CHECKME: what about DNLoc?
4005 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4006 }
4007
4008 case TemplateName::DependentTemplate: {
4009 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004010 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004011 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004012 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4013 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004014 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004015 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4016 // DNInfo work in progress: FIXME: source locations?
4017 DeclarationNameLoc DNLoc;
4018 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4019 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4020 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004021 }
4022 }
4023
John McCalld9dfe3a2011-06-30 08:33:18 +00004024 case TemplateName::SubstTemplateTemplateParm: {
4025 SubstTemplateTemplateParmStorage *subst
4026 = Name.getAsSubstTemplateTemplateParm();
4027 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4028 NameLoc);
4029 }
4030
4031 case TemplateName::SubstTemplateTemplateParmPack: {
4032 SubstTemplateTemplateParmPackStorage *subst
4033 = Name.getAsSubstTemplateTemplateParmPack();
4034 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4035 NameLoc);
4036 }
4037 }
4038
4039 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004040}
4041
Jay Foad39c79802011-01-12 09:06:06 +00004042TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004043 switch (Name.getKind()) {
4044 case TemplateName::QualifiedTemplate:
4045 case TemplateName::Template: {
4046 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004047 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004048 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004049 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4050
4051 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004052 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004053 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004054
John McCalld9dfe3a2011-06-30 08:33:18 +00004055 case TemplateName::OverloadedTemplate:
4056 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004057
John McCalld9dfe3a2011-06-30 08:33:18 +00004058 case TemplateName::DependentTemplate: {
4059 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4060 assert(DTN && "Non-dependent template names must refer to template decls.");
4061 return DTN->CanonicalTemplateName;
4062 }
4063
4064 case TemplateName::SubstTemplateTemplateParm: {
4065 SubstTemplateTemplateParmStorage *subst
4066 = Name.getAsSubstTemplateTemplateParm();
4067 return getCanonicalTemplateName(subst->getReplacement());
4068 }
4069
4070 case TemplateName::SubstTemplateTemplateParmPack: {
4071 SubstTemplateTemplateParmPackStorage *subst
4072 = Name.getAsSubstTemplateTemplateParmPack();
4073 TemplateTemplateParmDecl *canonParameter
4074 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4075 TemplateArgument canonArgPack
4076 = getCanonicalTemplateArgument(subst->getArgumentPack());
4077 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4078 }
4079 }
4080
4081 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004082}
4083
Douglas Gregoradee3e32009-11-11 23:06:43 +00004084bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4085 X = getCanonicalTemplateName(X);
4086 Y = getCanonicalTemplateName(Y);
4087 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4088}
4089
Mike Stump11289f42009-09-09 15:08:12 +00004090TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004091ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004092 switch (Arg.getKind()) {
4093 case TemplateArgument::Null:
4094 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004095
Douglas Gregora8e02e72009-07-28 23:00:59 +00004096 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004097 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004098
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004099 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004100 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4101 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004102 }
Mike Stump11289f42009-09-09 15:08:12 +00004103
Eli Friedmanb826a002012-09-26 02:36:12 +00004104 case TemplateArgument::NullPtr:
4105 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4106 /*isNullPtr*/true);
4107
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004108 case TemplateArgument::Template:
4109 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004110
4111 case TemplateArgument::TemplateExpansion:
4112 return TemplateArgument(getCanonicalTemplateName(
4113 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004114 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004115
Douglas Gregora8e02e72009-07-28 23:00:59 +00004116 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004117 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004118
Douglas Gregora8e02e72009-07-28 23:00:59 +00004119 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004120 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004121
Douglas Gregora8e02e72009-07-28 23:00:59 +00004122 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004123 if (Arg.pack_size() == 0)
4124 return Arg;
4125
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004126 TemplateArgument *CanonArgs
4127 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004128 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004129 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004130 AEnd = Arg.pack_end();
4131 A != AEnd; (void)++A, ++Idx)
4132 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004133
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004134 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00004135 }
4136 }
4137
4138 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004139 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004140}
4141
Douglas Gregor333489b2009-03-27 23:10:48 +00004142NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004143ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004144 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00004145 return 0;
4146
4147 switch (NNS->getKind()) {
4148 case NestedNameSpecifier::Identifier:
4149 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004150 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004151 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4152 NNS->getAsIdentifier());
4153
4154 case NestedNameSpecifier::Namespace:
4155 // A namespace is canonical; build a nested-name-specifier with
4156 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004157 return NestedNameSpecifier::Create(*this, 0,
4158 NNS->getAsNamespace()->getOriginalNamespace());
4159
4160 case NestedNameSpecifier::NamespaceAlias:
4161 // A namespace is canonical; build a nested-name-specifier with
4162 // this namespace and no prefix.
4163 return NestedNameSpecifier::Create(*this, 0,
4164 NNS->getAsNamespaceAlias()->getNamespace()
4165 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004166
4167 case NestedNameSpecifier::TypeSpec:
4168 case NestedNameSpecifier::TypeSpecWithTemplate: {
4169 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004170
4171 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4172 // break it apart into its prefix and identifier, then reconsititute those
4173 // as the canonical nested-name-specifier. This is required to canonicalize
4174 // a dependent nested-name-specifier involving typedefs of dependent-name
4175 // types, e.g.,
4176 // typedef typename T::type T1;
4177 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004178 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4179 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004180 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004181
Eli Friedman5358a0a2012-03-03 04:09:56 +00004182 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4183 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4184 // first place?
John McCall33ddac02011-01-19 10:06:00 +00004185 return NestedNameSpecifier::Create(*this, 0, false,
4186 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004187 }
4188
4189 case NestedNameSpecifier::Global:
4190 // The global specifier is canonical and unique.
4191 return NNS;
4192 }
4193
David Blaikie8a40f702012-01-17 06:56:22 +00004194 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004195}
4196
Chris Lattner7adf0762008-08-04 07:31:14 +00004197
Jay Foad39c79802011-01-12 09:06:06 +00004198const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004199 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004200 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004201 // Handle the common positive case fast.
4202 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4203 return AT;
4204 }
Mike Stump11289f42009-09-09 15:08:12 +00004205
John McCall8ccfcb52009-09-24 19:53:00 +00004206 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004207 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00004208 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004209
John McCall8ccfcb52009-09-24 19:53:00 +00004210 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004211 // implements C99 6.7.3p8: "If the specification of an array type includes
4212 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004213
Chris Lattner7adf0762008-08-04 07:31:14 +00004214 // If we get here, we either have type qualifiers on the type, or we have
4215 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004216 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004217
John McCall33ddac02011-01-19 10:06:00 +00004218 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004219 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004220
Chris Lattner7adf0762008-08-04 07:31:14 +00004221 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004222 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00004223 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004224 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004225
Chris Lattner7adf0762008-08-04 07:31:14 +00004226 // Otherwise, we have an array and we have qualifiers on it. Push the
4227 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004228 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004229
Chris Lattner7adf0762008-08-04 07:31:14 +00004230 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4231 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4232 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004233 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004234 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4235 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4236 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004237 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004238
Mike Stump11289f42009-09-09 15:08:12 +00004239 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004240 = dyn_cast<DependentSizedArrayType>(ATy))
4241 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004242 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004243 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004244 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004245 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004246 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004247
Chris Lattner7adf0762008-08-04 07:31:14 +00004248 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004249 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004250 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004251 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004252 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004253 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004254}
4255
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004256QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004257 if (T->isArrayType() || T->isFunctionType())
4258 return getDecayedType(T);
4259 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004260}
4261
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004262QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004263 T = getVariableArrayDecayedType(T);
4264 T = getAdjustedParameterType(T);
4265 return T.getUnqualifiedType();
4266}
4267
Chris Lattnera21ad802008-04-02 05:18:44 +00004268/// getArrayDecayedType - Return the properly qualified result of decaying the
4269/// specified array type to a pointer. This operation is non-trivial when
4270/// handling typedefs etc. The canonical type of "T" must be an array type,
4271/// this returns a pointer to a properly qualified element of the array.
4272///
4273/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004274QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004275 // Get the element type with 'getAsArrayType' so that we don't lose any
4276 // typedefs in the element type of the array. This also handles propagation
4277 // of type qualifiers from the array type into the element type if present
4278 // (C99 6.7.3p8).
4279 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4280 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004281
Chris Lattner7adf0762008-08-04 07:31:14 +00004282 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004283
4284 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004285 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004286}
4287
John McCall33ddac02011-01-19 10:06:00 +00004288QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4289 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004290}
4291
John McCall33ddac02011-01-19 10:06:00 +00004292QualType ASTContext::getBaseElementType(QualType type) const {
4293 Qualifiers qs;
4294 while (true) {
4295 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004296 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004297 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004298
John McCall33ddac02011-01-19 10:06:00 +00004299 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004300 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004301 }
Mike Stump11289f42009-09-09 15:08:12 +00004302
John McCall33ddac02011-01-19 10:06:00 +00004303 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004304}
4305
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004306/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004307uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004308ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4309 uint64_t ElementCount = 1;
4310 do {
4311 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004312 CA = dyn_cast_or_null<ConstantArrayType>(
4313 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004314 } while (CA);
4315 return ElementCount;
4316}
4317
Steve Naroff0af91202007-04-27 21:51:21 +00004318/// getFloatingRank - Return a relative rank for floating point types.
4319/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004320static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004321 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004322 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004323
John McCall9dd450b2009-09-21 23:43:11 +00004324 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4325 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004326 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004327 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004328 case BuiltinType::Float: return FloatRank;
4329 case BuiltinType::Double: return DoubleRank;
4330 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004331 }
4332}
4333
Mike Stump11289f42009-09-09 15:08:12 +00004334/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4335/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004336/// 'typeDomain' is a real floating point or complex type.
4337/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004338QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4339 QualType Domain) const {
4340 FloatingRank EltRank = getFloatingRank(Size);
4341 if (Domain->isComplexType()) {
4342 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004343 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004344 case FloatRank: return FloatComplexTy;
4345 case DoubleRank: return DoubleComplexTy;
4346 case LongDoubleRank: return LongDoubleComplexTy;
4347 }
Steve Naroff0af91202007-04-27 21:51:21 +00004348 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004349
4350 assert(Domain->isRealFloatingType() && "Unknown domain!");
4351 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004352 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004353 case FloatRank: return FloatTy;
4354 case DoubleRank: return DoubleTy;
4355 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004356 }
David Blaikief47fa302012-01-17 02:30:50 +00004357 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004358}
4359
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004360/// getFloatingTypeOrder - Compare the rank of the two specified floating
4361/// point types, ignoring the domain of the type (i.e. 'double' ==
4362/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004363/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004364int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004365 FloatingRank LHSR = getFloatingRank(LHS);
4366 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004367
Chris Lattnerb90739d2008-04-06 23:38:49 +00004368 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004369 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004370 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004371 return 1;
4372 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004373}
4374
Chris Lattner76a00cf2008-04-06 22:59:24 +00004375/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4376/// routine will assert if passed a built-in type that isn't an integer or enum,
4377/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004378unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004379 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004380
Chris Lattner76a00cf2008-04-06 22:59:24 +00004381 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004382 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004383 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004384 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004385 case BuiltinType::Char_S:
4386 case BuiltinType::Char_U:
4387 case BuiltinType::SChar:
4388 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004389 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004390 case BuiltinType::Short:
4391 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004392 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004393 case BuiltinType::Int:
4394 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004395 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004396 case BuiltinType::Long:
4397 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004398 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004399 case BuiltinType::LongLong:
4400 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004401 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004402 case BuiltinType::Int128:
4403 case BuiltinType::UInt128:
4404 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004405 }
4406}
4407
Eli Friedman629ffb92009-08-20 04:21:42 +00004408/// \brief Whether this is a promotable bitfield reference according
4409/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4410///
4411/// \returns the type this bit-field will promote to, or NULL if no
4412/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004413QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004414 if (E->isTypeDependent() || E->isValueDependent())
4415 return QualType();
4416
John McCalld25db7e2013-05-06 21:39:12 +00004417 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004418 if (!Field)
4419 return QualType();
4420
4421 QualType FT = Field->getType();
4422
Richard Smithcaf33902011-10-10 18:28:20 +00004423 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004424 uint64_t IntSize = getTypeSize(IntTy);
4425 // GCC extension compatibility: if the bit-field size is less than or equal
4426 // to the size of int, it gets promoted no matter what its type is.
4427 // For instance, unsigned long bf : 4 gets promoted to signed int.
4428 if (BitWidth < IntSize)
4429 return IntTy;
4430
4431 if (BitWidth == IntSize)
4432 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4433
4434 // Types bigger than int are not subject to promotions, and therefore act
4435 // like the base type.
4436 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4437 // is ridiculous.
4438 return QualType();
4439}
4440
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004441/// getPromotedIntegerType - Returns the type that Promotable will
4442/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4443/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004444QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004445 assert(!Promotable.isNull());
4446 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004447 if (const EnumType *ET = Promotable->getAs<EnumType>())
4448 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004449
4450 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4451 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4452 // (3.9.1) can be converted to a prvalue of the first of the following
4453 // types that can represent all the values of its underlying type:
4454 // int, unsigned int, long int, unsigned long int, long long int, or
4455 // unsigned long long int [...]
4456 // FIXME: Is there some better way to compute this?
4457 if (BT->getKind() == BuiltinType::WChar_S ||
4458 BT->getKind() == BuiltinType::WChar_U ||
4459 BT->getKind() == BuiltinType::Char16 ||
4460 BT->getKind() == BuiltinType::Char32) {
4461 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4462 uint64_t FromSize = getTypeSize(BT);
4463 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4464 LongLongTy, UnsignedLongLongTy };
4465 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4466 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4467 if (FromSize < ToSize ||
4468 (FromSize == ToSize &&
4469 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4470 return PromoteTypes[Idx];
4471 }
4472 llvm_unreachable("char type should fit into long long");
4473 }
4474 }
4475
4476 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004477 if (Promotable->isSignedIntegerType())
4478 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004479 uint64_t PromotableSize = getIntWidth(Promotable);
4480 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004481 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4482 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4483}
4484
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004485/// \brief Recurses in pointer/array types until it finds an objc retainable
4486/// type and returns its ownership.
4487Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4488 while (!T.isNull()) {
4489 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4490 return T.getObjCLifetime();
4491 if (T->isArrayType())
4492 T = getBaseElementType(T);
4493 else if (const PointerType *PT = T->getAs<PointerType>())
4494 T = PT->getPointeeType();
4495 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004496 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004497 else
4498 break;
4499 }
4500
4501 return Qualifiers::OCL_None;
4502}
4503
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004504static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4505 // Incomplete enum types are not treated as integer types.
4506 // FIXME: In C++, enum types are never integer types.
4507 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4508 return ET->getDecl()->getIntegerType().getTypePtr();
4509 return NULL;
4510}
4511
Mike Stump11289f42009-09-09 15:08:12 +00004512/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004513/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004514/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004515int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004516 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4517 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004518
4519 // Unwrap enums to their underlying type.
4520 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4521 LHSC = getIntegerTypeForEnum(ET);
4522 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4523 RHSC = getIntegerTypeForEnum(ET);
4524
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004525 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004526
Chris Lattner76a00cf2008-04-06 22:59:24 +00004527 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4528 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004529
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004530 unsigned LHSRank = getIntegerRank(LHSC);
4531 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004532
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004533 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4534 if (LHSRank == RHSRank) return 0;
4535 return LHSRank > RHSRank ? 1 : -1;
4536 }
Mike Stump11289f42009-09-09 15:08:12 +00004537
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004538 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4539 if (LHSUnsigned) {
4540 // If the unsigned [LHS] type is larger, return it.
4541 if (LHSRank >= RHSRank)
4542 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004543
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004544 // If the signed type can represent all values of the unsigned type, it
4545 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004546 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004547 return -1;
4548 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004549
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004550 // If the unsigned [RHS] type is larger, return it.
4551 if (RHSRank >= LHSRank)
4552 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004553
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004554 // If the signed type can represent all values of the unsigned type, it
4555 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004556 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004557 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004558}
Anders Carlsson98f07902007-08-17 05:31:46 +00004559
Mike Stump11289f42009-09-09 15:08:12 +00004560// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004561QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004562 if (!CFConstantStringTypeDecl) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004563 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
John McCallae580fe2010-02-05 01:33:36 +00004564 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004565
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004566 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004567
Anders Carlsson98f07902007-08-17 05:31:46 +00004568 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004569 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004570 // int flags;
4571 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004572 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004573 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004574 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004575 FieldTypes[3] = LongTy;
4576
Anders Carlsson98f07902007-08-17 05:31:46 +00004577 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004578 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004579 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004580 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004581 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00004582 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00004583 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004584 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004585 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004586 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004587 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004588 }
4589
Douglas Gregord5058122010-02-11 01:19:42 +00004590 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004591 }
Mike Stump11289f42009-09-09 15:08:12 +00004592
Anders Carlsson98f07902007-08-17 05:31:46 +00004593 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004594}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004595
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004596QualType ASTContext::getObjCSuperType() const {
4597 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004598 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004599 TUDecl->addDecl(ObjCSuperTypeDecl);
4600 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4601 }
4602 return ObjCSuperType;
4603}
4604
Douglas Gregor512b0772009-04-23 22:29:11 +00004605void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004606 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004607 assert(Rec && "Invalid CFConstantStringType");
4608 CFConstantStringTypeDecl = Rec->getDecl();
4609}
4610
Jay Foad39c79802011-01-12 09:06:06 +00004611QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004612 if (BlockDescriptorType)
4613 return getTagDeclType(BlockDescriptorType);
4614
Alp Toker2dea15b2013-12-17 01:22:38 +00004615 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004616 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004617 RD = buildImplicitRecord("__block_descriptor");
4618 RD->startDefinition();
4619
Mike Stumpd0153282009-10-20 02:12:22 +00004620 QualType FieldTypes[] = {
4621 UnsignedLongTy,
4622 UnsignedLongTy,
4623 };
4624
Craig Topperd6d31ac2013-07-15 08:24:27 +00004625 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004626 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004627 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004628 };
4629
4630 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004631 FieldDecl *Field = FieldDecl::Create(
4632 *this, RD, SourceLocation(), SourceLocation(),
4633 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/0,
4634 /*BitWidth=*/0, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004635 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004636 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00004637 }
4638
Alp Toker2dea15b2013-12-17 01:22:38 +00004639 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004640
Alp Toker2dea15b2013-12-17 01:22:38 +00004641 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004642
4643 return getTagDeclType(BlockDescriptorType);
4644}
4645
Jay Foad39c79802011-01-12 09:06:06 +00004646QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004647 if (BlockDescriptorExtendedType)
4648 return getTagDeclType(BlockDescriptorExtendedType);
4649
Alp Toker2dea15b2013-12-17 01:22:38 +00004650 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004651 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004652 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4653 RD->startDefinition();
4654
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004655 QualType FieldTypes[] = {
4656 UnsignedLongTy,
4657 UnsignedLongTy,
4658 getPointerType(VoidPtrTy),
4659 getPointerType(VoidPtrTy)
4660 };
4661
Craig Topperd6d31ac2013-07-15 08:24:27 +00004662 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004663 "reserved",
4664 "Size",
4665 "CopyFuncPtr",
4666 "DestroyFuncPtr"
4667 };
4668
4669 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004670 FieldDecl *Field = FieldDecl::Create(
4671 *this, RD, SourceLocation(), SourceLocation(),
4672 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/0,
4673 /*BitWidth=*/0,
4674 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004675 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004676 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004677 }
4678
Alp Toker2dea15b2013-12-17 01:22:38 +00004679 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004680
Alp Toker2dea15b2013-12-17 01:22:38 +00004681 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004682 return getTagDeclType(BlockDescriptorExtendedType);
4683}
4684
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004685/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4686/// requires copy/dispose. Note that this must match the logic
4687/// in buildByrefHelpers.
4688bool ASTContext::BlockRequiresCopying(QualType Ty,
4689 const VarDecl *D) {
4690 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4691 const Expr *copyExpr = getBlockVarCopyInits(D);
4692 if (!copyExpr && record->hasTrivialDestructor()) return false;
4693
Mike Stump94967902009-10-21 18:16:27 +00004694 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004695 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004696
4697 if (!Ty->isObjCRetainableType()) return false;
4698
4699 Qualifiers qs = Ty.getQualifiers();
4700
4701 // If we have lifetime, that dominates.
4702 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4703 assert(getLangOpts().ObjCAutoRefCount);
4704
4705 switch (lifetime) {
4706 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4707
4708 // These are just bits as far as the runtime is concerned.
4709 case Qualifiers::OCL_ExplicitNone:
4710 case Qualifiers::OCL_Autoreleasing:
4711 return false;
4712
4713 // Tell the runtime that this is ARC __weak, called by the
4714 // byref routines.
4715 case Qualifiers::OCL_Weak:
4716 // ARC __strong __block variables need to be retained.
4717 case Qualifiers::OCL_Strong:
4718 return true;
4719 }
4720 llvm_unreachable("fell out of lifetime switch!");
4721 }
4722 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4723 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004724}
4725
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004726bool ASTContext::getByrefLifetime(QualType Ty,
4727 Qualifiers::ObjCLifetime &LifeTime,
4728 bool &HasByrefExtendedLayout) const {
4729
4730 if (!getLangOpts().ObjC1 ||
4731 getLangOpts().getGC() != LangOptions::NonGC)
4732 return false;
4733
4734 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004735 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004736 HasByrefExtendedLayout = true;
4737 LifeTime = Qualifiers::OCL_None;
4738 }
4739 else if (getLangOpts().ObjCAutoRefCount)
4740 LifeTime = Ty.getObjCLifetime();
4741 // MRR.
4742 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4743 LifeTime = Qualifiers::OCL_ExplicitNone;
4744 else
4745 LifeTime = Qualifiers::OCL_None;
4746 return true;
4747}
4748
Douglas Gregorbab8a962011-09-08 01:46:34 +00004749TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4750 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00004751 ObjCInstanceTypeDecl =
4752 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00004753 return ObjCInstanceTypeDecl;
4754}
4755
Anders Carlsson18acd442007-10-29 06:33:42 +00004756// This returns true if a type has been typedefed to BOOL:
4757// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004758static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004759 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004760 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4761 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004762
Anders Carlssond8499822007-10-29 05:01:08 +00004763 return false;
4764}
4765
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004766/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004767/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004768CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004769 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4770 return CharUnits::Zero();
4771
Ken Dyck40775002010-01-11 17:06:35 +00004772 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004773
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004774 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004775 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004776 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004777 // Treat arrays as pointers, since that's how they're passed in.
4778 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004779 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004780 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004781}
4782
4783static inline
4784std::string charUnitsToString(const CharUnits &CU) {
4785 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004786}
4787
John McCall351762c2011-02-07 10:33:21 +00004788/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004789/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004790std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4791 std::string S;
4792
David Chisnall950a9512009-11-17 19:33:30 +00004793 const BlockDecl *Decl = Expr->getBlockDecl();
4794 QualType BlockTy =
4795 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4796 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004797 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004798 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4799 BlockTy->getAs<FunctionType>()->getResultType(),
4800 S, true /*Extended*/);
4801 else
4802 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4803 S);
David Chisnall950a9512009-11-17 19:33:30 +00004804 // Compute size of all parameters.
4805 // Start with computing size of a pointer in number of bytes.
4806 // FIXME: There might(should) be a better way of doing this computation!
4807 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004808 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4809 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004810 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004811 E = Decl->param_end(); PI != E; ++PI) {
4812 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004813 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004814 if (sz.isZero())
4815 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004816 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004817 ParmOffset += sz;
4818 }
4819 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004820 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004821 // Block pointer and offset.
4822 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004823
4824 // Argument types.
4825 ParmOffset = PtrSize;
4826 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4827 Decl->param_end(); PI != E; ++PI) {
4828 ParmVarDecl *PVDecl = *PI;
4829 QualType PType = PVDecl->getOriginalType();
4830 if (const ArrayType *AT =
4831 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4832 // Use array's original type only if it has known number of
4833 // elements.
4834 if (!isa<ConstantArrayType>(AT))
4835 PType = PVDecl->getType();
4836 } else if (PType->isFunctionType())
4837 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004838 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004839 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4840 S, true /*Extended*/);
4841 else
4842 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004843 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004844 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004845 }
John McCall351762c2011-02-07 10:33:21 +00004846
4847 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004848}
4849
Douglas Gregora9d84932011-05-27 01:19:52 +00004850bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004851 std::string& S) {
4852 // Encode result type.
4853 getObjCEncodingForType(Decl->getResultType(), S);
4854 CharUnits ParmOffset;
4855 // Compute size of all parameters.
4856 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4857 E = Decl->param_end(); PI != E; ++PI) {
4858 QualType PType = (*PI)->getType();
4859 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004860 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004861 continue;
4862
David Chisnall50e4eba2010-12-30 14:05:53 +00004863 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004864 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004865 ParmOffset += sz;
4866 }
4867 S += charUnitsToString(ParmOffset);
4868 ParmOffset = CharUnits::Zero();
4869
4870 // Argument types.
4871 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4872 E = Decl->param_end(); PI != E; ++PI) {
4873 ParmVarDecl *PVDecl = *PI;
4874 QualType PType = PVDecl->getOriginalType();
4875 if (const ArrayType *AT =
4876 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4877 // Use array's original type only if it has known number of
4878 // elements.
4879 if (!isa<ConstantArrayType>(AT))
4880 PType = PVDecl->getType();
4881 } else if (PType->isFunctionType())
4882 PType = PVDecl->getType();
4883 getObjCEncodingForType(PType, S);
4884 S += charUnitsToString(ParmOffset);
4885 ParmOffset += getObjCEncodingTypeSize(PType);
4886 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004887
4888 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004889}
4890
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004891/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4892/// method parameter or return type. If Extended, include class names and
4893/// block object types.
4894void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4895 QualType T, std::string& S,
4896 bool Extended) const {
4897 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4898 getObjCEncodingForTypeQualifier(QT, S);
4899 // Encode parameter type.
4900 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4901 true /*OutermostType*/,
4902 false /*EncodingProperty*/,
4903 false /*StructField*/,
4904 Extended /*EncodeBlockParameters*/,
4905 Extended /*EncodeClassNames*/);
4906}
4907
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004908/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004909/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004910bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004911 std::string& S,
4912 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004913 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004914 // Encode return type.
4915 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4916 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004917 // Compute size of all parameters.
4918 // Start with computing size of a pointer in number of bytes.
4919 // FIXME: There might(should) be a better way of doing this computation!
4920 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004921 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004922 // The first two arguments (self and _cmd) are pointers; account for
4923 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004924 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004925 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004926 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004927 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004928 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004929 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004930 continue;
4931
Ken Dyck40775002010-01-11 17:06:35 +00004932 assert (sz.isPositive() &&
4933 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004934 ParmOffset += sz;
4935 }
Ken Dyck40775002010-01-11 17:06:35 +00004936 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004937 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004938 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004939
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004940 // Argument types.
4941 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004942 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004943 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004944 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004945 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004946 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004947 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4948 // Use array's original type only if it has known number of
4949 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004950 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004951 PType = PVDecl->getType();
4952 } else if (PType->isFunctionType())
4953 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004954 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4955 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004956 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004957 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004958 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004959
4960 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004961}
4962
Fariborz Jahaniandad96302014-01-22 19:02:20 +00004963ObjCPropertyImplDecl *
4964ASTContext::getObjCPropertyImplDeclForPropertyDecl(
4965 const ObjCPropertyDecl *PD,
4966 const Decl *Container) const {
4967 if (!Container)
4968 return 0;
4969 if (const ObjCCategoryImplDecl *CID =
4970 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4971 for (ObjCCategoryImplDecl::propimpl_iterator
4972 i = CID->propimpl_begin(), e = CID->propimpl_end();
4973 i != e; ++i) {
4974 ObjCPropertyImplDecl *PID = *i;
4975 if (PID->getPropertyDecl() == PD)
4976 return PID;
4977 }
4978 } else {
4979 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
4980 for (ObjCCategoryImplDecl::propimpl_iterator
4981 i = OID->propimpl_begin(), e = OID->propimpl_end();
4982 i != e; ++i) {
4983 ObjCPropertyImplDecl *PID = *i;
4984 if (PID->getPropertyDecl() == PD)
4985 return PID;
4986 }
4987 }
4988 return 0;
4989}
4990
Daniel Dunbar4932b362008-08-28 04:38:10 +00004991/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004992/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004993/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4994/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004995/// Property attributes are stored as a comma-delimited C string. The simple
4996/// attributes readonly and bycopy are encoded as single characters. The
4997/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4998/// encoded as single characters, followed by an identifier. Property types
4999/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005000/// these attributes are defined by the following enumeration:
5001/// @code
5002/// enum PropertyAttributes {
5003/// kPropertyReadOnly = 'R', // property is read-only.
5004/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5005/// kPropertyByref = '&', // property is a reference to the value last assigned
5006/// kPropertyDynamic = 'D', // property is dynamic
5007/// kPropertyGetter = 'G', // followed by getter selector name
5008/// kPropertySetter = 'S', // followed by setter selector name
5009/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005010/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005011/// kPropertyWeak = 'W' // 'weak' property
5012/// kPropertyStrong = 'P' // property GC'able
5013/// kPropertyNonAtomic = 'N' // property non-atomic
5014/// };
5015/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005016void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00005017 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005018 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005019 // Collect information from the property implementation decl(s).
5020 bool Dynamic = false;
5021 ObjCPropertyImplDecl *SynthesizePID = 0;
5022
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005023 if (ObjCPropertyImplDecl *PropertyImpDecl =
5024 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5025 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5026 Dynamic = true;
5027 else
5028 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005029 }
5030
5031 // FIXME: This is not very efficient.
5032 S = "T";
5033
5034 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005035 // GCC has some special rules regarding encoding of properties which
5036 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00005037 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005038 true /* outermost type */,
5039 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005040
5041 if (PD->isReadOnly()) {
5042 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005043 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5044 S += ",C";
5045 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5046 S += ",&";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005047 } else {
5048 switch (PD->getSetterKind()) {
5049 case ObjCPropertyDecl::Assign: break;
5050 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005051 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005052 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005053 }
5054 }
5055
5056 // It really isn't clear at all what this means, since properties
5057 // are "dynamic by default".
5058 if (Dynamic)
5059 S += ",D";
5060
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005061 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5062 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005063
Daniel Dunbar4932b362008-08-28 04:38:10 +00005064 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5065 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005066 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005067 }
5068
5069 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5070 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005071 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005072 }
5073
5074 if (SynthesizePID) {
5075 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5076 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005077 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005078 }
5079
5080 // FIXME: OBJCGC: weak & strong
5081}
5082
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005083/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005084/// Another legacy compatibility encoding: 32-bit longs are encoded as
5085/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005086/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5087///
5088void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005089 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005090 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005091 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005092 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005093 else
Jay Foad39c79802011-01-12 09:06:06 +00005094 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005095 PointeeTy = IntTy;
5096 }
5097 }
5098}
5099
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005100void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00005101 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005102 // We follow the behavior of gcc, expanding structures which are
5103 // directly pointed to, and expanding embedded structures. Note that
5104 // these rules are sufficient to prevent recursive encoding of the
5105 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005106 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00005107 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005108}
5109
John McCall393a78d2012-12-20 02:45:14 +00005110static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5111 BuiltinType::Kind kind) {
5112 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005113 case BuiltinType::Void: return 'v';
5114 case BuiltinType::Bool: return 'B';
5115 case BuiltinType::Char_U:
5116 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005117 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005118 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005119 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005120 case BuiltinType::UInt: return 'I';
5121 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005122 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005123 case BuiltinType::UInt128: return 'T';
5124 case BuiltinType::ULongLong: return 'Q';
5125 case BuiltinType::Char_S:
5126 case BuiltinType::SChar: return 'c';
5127 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005128 case BuiltinType::WChar_S:
5129 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005130 case BuiltinType::Int: return 'i';
5131 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005132 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005133 case BuiltinType::LongLong: return 'q';
5134 case BuiltinType::Int128: return 't';
5135 case BuiltinType::Float: return 'f';
5136 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005137 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005138 case BuiltinType::NullPtr: return '*'; // like char*
5139
5140 case BuiltinType::Half:
5141 // FIXME: potentially need @encodes for these!
5142 return ' ';
5143
5144 case BuiltinType::ObjCId:
5145 case BuiltinType::ObjCClass:
5146 case BuiltinType::ObjCSel:
5147 llvm_unreachable("@encoding ObjC primitive type");
5148
5149 // OpenCL and placeholder types don't need @encodings.
5150 case BuiltinType::OCLImage1d:
5151 case BuiltinType::OCLImage1dArray:
5152 case BuiltinType::OCLImage1dBuffer:
5153 case BuiltinType::OCLImage2d:
5154 case BuiltinType::OCLImage2dArray:
5155 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005156 case BuiltinType::OCLEvent:
Guy Benyei61054192013-02-07 10:55:47 +00005157 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005158 case BuiltinType::Dependent:
5159#define BUILTIN_TYPE(KIND, ID)
5160#define PLACEHOLDER_TYPE(KIND, ID) \
5161 case BuiltinType::KIND:
5162#include "clang/AST/BuiltinTypes.def"
5163 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005164 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005165 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005166}
5167
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005168static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5169 EnumDecl *Enum = ET->getDecl();
5170
5171 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5172 if (!Enum->isFixed())
5173 return 'i';
5174
5175 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005176 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5177 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005178}
5179
Jay Foad39c79802011-01-12 09:06:06 +00005180static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005181 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005182 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005183 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005184 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5185 // The GNU runtime requires more information; bitfields are encoded as b,
5186 // then the offset (in bits) of the first element, then the type of the
5187 // bitfield, then the size in bits. For example, in this structure:
5188 //
5189 // struct
5190 // {
5191 // int integer;
5192 // int flags:2;
5193 // };
5194 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5195 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5196 // information is not especially sensible, but we're stuck with it for
5197 // compatibility with GCC, although providing it breaks anything that
5198 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005199 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005200 const RecordDecl *RD = FD->getParent();
5201 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005202 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005203 if (const EnumType *ET = T->getAs<EnumType>())
5204 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005205 else {
5206 const BuiltinType *BT = T->castAs<BuiltinType>();
5207 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5208 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005209 }
Richard Smithcaf33902011-10-10 18:28:20 +00005210 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005211}
5212
Daniel Dunbar07d07852009-10-18 21:17:35 +00005213// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005214void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5215 bool ExpandPointedToStructures,
5216 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005217 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005218 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005219 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005220 bool StructField,
5221 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005222 bool EncodeClassNames,
5223 bool EncodePointerToObjCTypedef) const {
John McCall393a78d2012-12-20 02:45:14 +00005224 CanQualType CT = getCanonicalType(T);
5225 switch (CT->getTypeClass()) {
5226 case Type::Builtin:
5227 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005228 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005229 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005230 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5231 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5232 else
5233 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005234 return;
Mike Stump11289f42009-09-09 15:08:12 +00005235
John McCall393a78d2012-12-20 02:45:14 +00005236 case Type::Complex: {
5237 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005238 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00005239 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00005240 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005241 return;
5242 }
John McCall393a78d2012-12-20 02:45:14 +00005243
5244 case Type::Atomic: {
5245 const AtomicType *AT = T->castAs<AtomicType>();
5246 S += 'A';
5247 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5248 false, false);
5249 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005250 }
John McCall393a78d2012-12-20 02:45:14 +00005251
5252 // encoding for pointer or reference types.
5253 case Type::Pointer:
5254 case Type::LValueReference:
5255 case Type::RValueReference: {
5256 QualType PointeeTy;
5257 if (isa<PointerType>(CT)) {
5258 const PointerType *PT = T->castAs<PointerType>();
5259 if (PT->isObjCSelType()) {
5260 S += ':';
5261 return;
5262 }
5263 PointeeTy = PT->getPointeeType();
5264 } else {
5265 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5266 }
5267
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005268 bool isReadOnly = false;
5269 // For historical/compatibility reasons, the read-only qualifier of the
5270 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5271 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005272 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005273 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005274 if (OutermostType && T.isConstQualified()) {
5275 isReadOnly = true;
5276 S += 'r';
5277 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005278 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005279 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005280 while (P->getAs<PointerType>())
5281 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005282 if (P.isConstQualified()) {
5283 isReadOnly = true;
5284 S += 'r';
5285 }
5286 }
5287 if (isReadOnly) {
5288 // Another legacy compatibility encoding. Some ObjC qualifier and type
5289 // combinations need to be rearranged.
5290 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005291 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005292 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005293 }
Mike Stump11289f42009-09-09 15:08:12 +00005294
Anders Carlssond8499822007-10-29 05:01:08 +00005295 if (PointeeTy->isCharType()) {
5296 // char pointer types should be encoded as '*' unless it is a
5297 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005298 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005299 S += '*';
5300 return;
5301 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005302 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005303 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5304 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5305 S += '#';
5306 return;
5307 }
5308 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5309 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5310 S += '@';
5311 return;
5312 }
5313 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005314 }
Anders Carlssond8499822007-10-29 05:01:08 +00005315 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005316 getLegacyIntegralTypeEncoding(PointeeTy);
5317
Mike Stump11289f42009-09-09 15:08:12 +00005318 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005319 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005320 return;
5321 }
John McCall393a78d2012-12-20 02:45:14 +00005322
5323 case Type::ConstantArray:
5324 case Type::IncompleteArray:
5325 case Type::VariableArray: {
5326 const ArrayType *AT = cast<ArrayType>(CT);
5327
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005328 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005329 // Incomplete arrays are encoded as a pointer to the array element.
5330 S += '^';
5331
Mike Stump11289f42009-09-09 15:08:12 +00005332 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005333 false, ExpandStructures, FD);
5334 } else {
5335 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005336
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005337 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5338 S += llvm::utostr(CAT->getSize().getZExtValue());
5339 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005340 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005341 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5342 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005343 S += '0';
5344 }
Mike Stump11289f42009-09-09 15:08:12 +00005345
5346 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005347 false, ExpandStructures, FD);
5348 S += ']';
5349 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005350 return;
5351 }
Mike Stump11289f42009-09-09 15:08:12 +00005352
John McCall393a78d2012-12-20 02:45:14 +00005353 case Type::FunctionNoProto:
5354 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005355 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005356 return;
Mike Stump11289f42009-09-09 15:08:12 +00005357
John McCall393a78d2012-12-20 02:45:14 +00005358 case Type::Record: {
5359 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005360 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005361 // Anonymous structures print as '?'
5362 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5363 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005364 if (ClassTemplateSpecializationDecl *Spec
5365 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5366 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005367 llvm::raw_string_ostream OS(S);
5368 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005369 TemplateArgs.data(),
5370 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005371 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005372 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005373 } else {
5374 S += '?';
5375 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005376 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005377 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005378 if (!RDecl->isUnion()) {
5379 getObjCEncodingForStructureImpl(RDecl, S, FD);
5380 } else {
5381 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5382 FieldEnd = RDecl->field_end();
5383 Field != FieldEnd; ++Field) {
5384 if (FD) {
5385 S += '"';
5386 S += Field->getNameAsString();
5387 S += '"';
5388 }
Mike Stump11289f42009-09-09 15:08:12 +00005389
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005390 // Special case bit-fields.
5391 if (Field->isBitField()) {
5392 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00005393 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005394 } else {
5395 QualType qt = Field->getType();
5396 getLegacyIntegralTypeEncoding(qt);
5397 getObjCEncodingForTypeImpl(qt, S, false, true,
5398 FD, /*OutermostType*/false,
5399 /*EncodingProperty*/false,
5400 /*StructField*/true);
5401 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005402 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005403 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005404 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005405 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005406 return;
5407 }
Mike Stump11289f42009-09-09 15:08:12 +00005408
John McCall393a78d2012-12-20 02:45:14 +00005409 case Type::BlockPointer: {
5410 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005411 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005412 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005413 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005414
5415 S += '<';
5416 // Block return type
5417 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5418 ExpandPointedToStructures, ExpandStructures,
5419 FD,
5420 false /* OutermostType */,
5421 EncodingProperty,
5422 false /* StructField */,
5423 EncodeBlockParameters,
5424 EncodeClassNames);
5425 // Block self
5426 S += "@?";
5427 // Block parameters
5428 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Alp Toker9cacbab2014-01-20 20:26:09 +00005429 for (FunctionProtoType::param_type_iterator I = FPT->param_type_begin(),
5430 E = FPT->param_type_end();
5431 I && (I != E); ++I) {
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005432 getObjCEncodingForTypeImpl(*I, S,
5433 ExpandPointedToStructures,
5434 ExpandStructures,
5435 FD,
5436 false /* OutermostType */,
5437 EncodingProperty,
5438 false /* StructField */,
5439 EncodeBlockParameters,
5440 EncodeClassNames);
5441 }
5442 }
5443 S += '>';
5444 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005445 return;
5446 }
Mike Stump11289f42009-09-09 15:08:12 +00005447
John McCall393a78d2012-12-20 02:45:14 +00005448 case Type::ObjCObject:
5449 case Type::ObjCInterface: {
5450 // Ignore protocol qualifiers when mangling at this level.
5451 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCall8b07ec22010-05-15 11:32:37 +00005452
John McCall393a78d2012-12-20 02:45:14 +00005453 // The assumption seems to be that this assert will succeed
5454 // because nested levels will have filtered out 'id' and 'Class'.
5455 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005456 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005457 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005458 S += '{';
5459 const IdentifierInfo *II = OI->getIdentifier();
5460 S += II->getName();
5461 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005462 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005463 DeepCollectObjCIvars(OI, true, Ivars);
5464 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005465 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005466 if (Field->isBitField())
5467 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005468 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005469 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5470 false, false, false, false, false,
5471 EncodePointerToObjCTypedef);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005472 }
5473 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005474 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005475 }
Mike Stump11289f42009-09-09 15:08:12 +00005476
John McCall393a78d2012-12-20 02:45:14 +00005477 case Type::ObjCObjectPointer: {
5478 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005479 if (OPT->isObjCIdType()) {
5480 S += '@';
5481 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005482 }
Mike Stump11289f42009-09-09 15:08:12 +00005483
Steve Narofff0c86112009-10-28 22:03:49 +00005484 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5485 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5486 // Since this is a binary compatibility issue, need to consult with runtime
5487 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005488 S += '#';
5489 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005490 }
Mike Stump11289f42009-09-09 15:08:12 +00005491
Chris Lattnere7cabb92009-07-13 00:10:46 +00005492 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005493 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005494 ExpandPointedToStructures,
5495 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005496 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005497 // Note that we do extended encoding of protocol qualifer list
5498 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005499 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00005500 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5501 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005502 S += '<';
5503 S += (*I)->getNameAsString();
5504 S += '>';
5505 }
5506 S += '"';
5507 }
5508 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005509 }
Mike Stump11289f42009-09-09 15:08:12 +00005510
Chris Lattnere7cabb92009-07-13 00:10:46 +00005511 QualType PointeeTy = OPT->getPointeeType();
5512 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005513 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5514 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005515 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005516 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005517 // {...};
5518 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005519 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005520 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005521 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5522 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5523 DeepCollectObjCIvars(OI, true, Ivars);
5524 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5525 if (cast<FieldDecl>(Ivars[i]) == FD) {
5526 S += '{';
5527 S += OI->getIdentifier()->getName();
5528 S += '}';
5529 return;
5530 }
5531 }
5532 }
Mike Stump11289f42009-09-09 15:08:12 +00005533 getObjCEncodingForTypeImpl(PointeeTy, S,
5534 false, ExpandPointedToStructures,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005535 NULL,
5536 false, false, false, false, false,
5537 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005538 return;
5539 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005540
5541 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005542 if (OPT->getInterfaceDecl() &&
5543 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005544 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005545 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00005546 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5547 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005548 S += '<';
5549 S += (*I)->getNameAsString();
5550 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005551 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005552 S += '"';
5553 }
5554 return;
5555 }
Mike Stump11289f42009-09-09 15:08:12 +00005556
John McCalla9e6e8d2010-05-17 23:56:34 +00005557 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005558 // FIXME: we shoul do better than that. 'M' is available.
5559 case Type::MemberPointer:
John McCalla9e6e8d2010-05-17 23:56:34 +00005560 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005561
John McCall393a78d2012-12-20 02:45:14 +00005562 case Type::Vector:
5563 case Type::ExtVector:
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005564 // This matches gcc's encoding, even though technically it is
5565 // insufficient.
5566 // FIXME. We should do a better job than gcc.
5567 return;
John McCall393a78d2012-12-20 02:45:14 +00005568
Richard Smith27d807c2013-04-30 13:56:41 +00005569 case Type::Auto:
5570 // We could see an undeduced auto type here during error recovery.
5571 // Just ignore it.
5572 return;
5573
John McCall393a78d2012-12-20 02:45:14 +00005574#define ABSTRACT_TYPE(KIND, BASE)
5575#define TYPE(KIND, BASE)
5576#define DEPENDENT_TYPE(KIND, BASE) \
5577 case Type::KIND:
5578#define NON_CANONICAL_TYPE(KIND, BASE) \
5579 case Type::KIND:
5580#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5581 case Type::KIND:
5582#include "clang/AST/TypeNodes.def"
5583 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005584 }
John McCall393a78d2012-12-20 02:45:14 +00005585 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005586}
5587
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005588void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5589 std::string &S,
5590 const FieldDecl *FD,
5591 bool includeVBases) const {
5592 assert(RDecl && "Expected non-null RecordDecl");
5593 assert(!RDecl->isUnion() && "Should not be called for unions");
5594 if (!RDecl->getDefinition())
5595 return;
5596
5597 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5598 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5599 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5600
5601 if (CXXRec) {
5602 for (CXXRecordDecl::base_class_iterator
5603 BI = CXXRec->bases_begin(),
5604 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5605 if (!BI->isVirtual()) {
5606 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005607 if (base->isEmpty())
5608 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005609 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005610 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5611 std::make_pair(offs, base));
5612 }
5613 }
5614 }
5615
5616 unsigned i = 0;
5617 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5618 FieldEnd = RDecl->field_end();
5619 Field != FieldEnd; ++Field, ++i) {
5620 uint64_t offs = layout.getFieldOffset(i);
5621 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00005622 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005623 }
5624
5625 if (CXXRec && includeVBases) {
5626 for (CXXRecordDecl::base_class_iterator
5627 BI = CXXRec->vbases_begin(),
5628 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5629 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005630 if (base->isEmpty())
5631 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005632 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00005633 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5634 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005635 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5636 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005637 }
5638 }
5639
5640 CharUnits size;
5641 if (CXXRec) {
5642 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5643 } else {
5644 size = layout.getSize();
5645 }
5646
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005647#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005648 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005649#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005650 std::multimap<uint64_t, NamedDecl *>::iterator
5651 CurLayObj = FieldOrBaseOffsets.begin();
5652
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005653 if (CXXRec && CXXRec->isDynamicClass() &&
5654 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005655 if (FD) {
5656 S += "\"_vptr$";
5657 std::string recname = CXXRec->getNameAsString();
5658 if (recname.empty()) recname = "?";
5659 S += recname;
5660 S += '"';
5661 }
5662 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005663#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005664 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005665#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005666 }
5667
5668 if (!RDecl->hasFlexibleArrayMember()) {
5669 // Mark the end of the structure.
5670 uint64_t offs = toBits(size);
5671 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5672 std::make_pair(offs, (NamedDecl*)0));
5673 }
5674
5675 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005676#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005677 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005678 if (CurOffs < CurLayObj->first) {
5679 uint64_t padding = CurLayObj->first - CurOffs;
5680 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5681 // packing/alignment of members is different that normal, in which case
5682 // the encoding will be out-of-sync with the real layout.
5683 // If the runtime switches to just consider the size of types without
5684 // taking into account alignment, we could make padding explicit in the
5685 // encoding (e.g. using arrays of chars). The encoding strings would be
5686 // longer then though.
5687 CurOffs += padding;
5688 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005689#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005690
5691 NamedDecl *dcl = CurLayObj->second;
5692 if (dcl == 0)
5693 break; // reached end of structure.
5694
5695 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5696 // We expand the bases without their virtual bases since those are going
5697 // in the initial structure. Note that this differs from gcc which
5698 // expands virtual bases each time one is encountered in the hierarchy,
5699 // making the encoding type bigger than it really is.
5700 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005701 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005702#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005703 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005704#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005705 } else {
5706 FieldDecl *field = cast<FieldDecl>(dcl);
5707 if (FD) {
5708 S += '"';
5709 S += field->getNameAsString();
5710 S += '"';
5711 }
5712
5713 if (field->isBitField()) {
5714 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005715#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00005716 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005717#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005718 } else {
5719 QualType qt = field->getType();
5720 getLegacyIntegralTypeEncoding(qt);
5721 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5722 /*OutermostType*/false,
5723 /*EncodingProperty*/false,
5724 /*StructField*/true);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005725#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005726 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005727#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005728 }
5729 }
5730 }
5731}
5732
Mike Stump11289f42009-09-09 15:08:12 +00005733void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005734 std::string& S) const {
5735 if (QT & Decl::OBJC_TQ_In)
5736 S += 'n';
5737 if (QT & Decl::OBJC_TQ_Inout)
5738 S += 'N';
5739 if (QT & Decl::OBJC_TQ_Out)
5740 S += 'o';
5741 if (QT & Decl::OBJC_TQ_Bycopy)
5742 S += 'O';
5743 if (QT & Decl::OBJC_TQ_Byref)
5744 S += 'R';
5745 if (QT & Decl::OBJC_TQ_Oneway)
5746 S += 'V';
5747}
5748
Douglas Gregor3ea72692011-08-12 05:46:01 +00005749TypedefDecl *ASTContext::getObjCIdDecl() const {
5750 if (!ObjCIdDecl) {
5751 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5752 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005753 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00005754 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00005755 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005756}
5757
Douglas Gregor52e02802011-08-12 06:17:30 +00005758TypedefDecl *ASTContext::getObjCSelDecl() const {
5759 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005760 QualType T = getPointerType(ObjCBuiltinSelTy);
5761 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00005762 }
5763 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005764}
5765
Douglas Gregor0a586182011-08-12 05:59:41 +00005766TypedefDecl *ASTContext::getObjCClassDecl() const {
5767 if (!ObjCClassDecl) {
5768 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5769 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005770 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00005771 }
Douglas Gregor0a586182011-08-12 05:59:41 +00005772 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005773}
5774
Douglas Gregord53ae832012-01-17 18:09:05 +00005775ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5776 if (!ObjCProtocolClassDecl) {
5777 ObjCProtocolClassDecl
5778 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5779 SourceLocation(),
5780 &Idents.get("Protocol"),
5781 /*PrevDecl=*/0,
5782 SourceLocation(), true);
5783 }
5784
5785 return ObjCProtocolClassDecl;
5786}
5787
Meador Inge5d3fb222012-06-16 03:34:49 +00005788//===----------------------------------------------------------------------===//
5789// __builtin_va_list Construction Functions
5790//===----------------------------------------------------------------------===//
5791
5792static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5793 // typedef char* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005794 QualType T = Context->getPointerType(Context->CharTy);
5795 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005796}
5797
5798static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5799 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005800 QualType T = Context->getPointerType(Context->VoidTy);
5801 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005802}
5803
Tim Northover9bb857a2013-01-31 12:13:10 +00005804static TypedefDecl *
5805CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005806 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00005807 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005808 if (Context->getLangOpts().CPlusPlus) {
5809 // namespace std { struct __va_list {
5810 NamespaceDecl *NS;
5811 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5812 Context->getTranslationUnitDecl(),
5813 /*Inline*/false, SourceLocation(),
5814 SourceLocation(), &Context->Idents.get("std"),
5815 /*PrevDecl*/0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005816 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00005817 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00005818 }
5819
5820 VaListTagDecl->startDefinition();
5821
5822 const size_t NumFields = 5;
5823 QualType FieldTypes[NumFields];
5824 const char *FieldNames[NumFields];
5825
5826 // void *__stack;
5827 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5828 FieldNames[0] = "__stack";
5829
5830 // void *__gr_top;
5831 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5832 FieldNames[1] = "__gr_top";
5833
5834 // void *__vr_top;
5835 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5836 FieldNames[2] = "__vr_top";
5837
5838 // int __gr_offs;
5839 FieldTypes[3] = Context->IntTy;
5840 FieldNames[3] = "__gr_offs";
5841
5842 // int __vr_offs;
5843 FieldTypes[4] = Context->IntTy;
5844 FieldNames[4] = "__vr_offs";
5845
5846 // Create fields
5847 for (unsigned i = 0; i < NumFields; ++i) {
5848 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5849 VaListTagDecl,
5850 SourceLocation(),
5851 SourceLocation(),
5852 &Context->Idents.get(FieldNames[i]),
5853 FieldTypes[i], /*TInfo=*/0,
5854 /*BitWidth=*/0,
5855 /*Mutable=*/false,
5856 ICIS_NoInit);
5857 Field->setAccess(AS_public);
5858 VaListTagDecl->addDecl(Field);
5859 }
5860 VaListTagDecl->completeDefinition();
5861 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5862 Context->VaListTagTy = VaListTagType;
5863
5864 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005865 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005866}
5867
Meador Inge5d3fb222012-06-16 03:34:49 +00005868static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5869 // typedef struct __va_list_tag {
5870 RecordDecl *VaListTagDecl;
5871
Alp Toker2dea15b2013-12-17 01:22:38 +00005872 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00005873 VaListTagDecl->startDefinition();
5874
5875 const size_t NumFields = 5;
5876 QualType FieldTypes[NumFields];
5877 const char *FieldNames[NumFields];
5878
5879 // unsigned char gpr;
5880 FieldTypes[0] = Context->UnsignedCharTy;
5881 FieldNames[0] = "gpr";
5882
5883 // unsigned char fpr;
5884 FieldTypes[1] = Context->UnsignedCharTy;
5885 FieldNames[1] = "fpr";
5886
5887 // unsigned short reserved;
5888 FieldTypes[2] = Context->UnsignedShortTy;
5889 FieldNames[2] = "reserved";
5890
5891 // void* overflow_arg_area;
5892 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5893 FieldNames[3] = "overflow_arg_area";
5894
5895 // void* reg_save_area;
5896 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5897 FieldNames[4] = "reg_save_area";
5898
5899 // Create fields
5900 for (unsigned i = 0; i < NumFields; ++i) {
5901 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5902 SourceLocation(),
5903 SourceLocation(),
5904 &Context->Idents.get(FieldNames[i]),
5905 FieldTypes[i], /*TInfo=*/0,
5906 /*BitWidth=*/0,
5907 /*Mutable=*/false,
5908 ICIS_NoInit);
5909 Field->setAccess(AS_public);
5910 VaListTagDecl->addDecl(Field);
5911 }
5912 VaListTagDecl->completeDefinition();
5913 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005914 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005915
5916 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00005917 TypedefDecl *VaListTagTypedefDecl =
5918 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
5919
Meador Inge5d3fb222012-06-16 03:34:49 +00005920 QualType VaListTagTypedefType =
5921 Context->getTypedefType(VaListTagTypedefDecl);
5922
5923 // typedef __va_list_tag __builtin_va_list[1];
5924 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5925 QualType VaListTagArrayType
5926 = Context->getConstantArrayType(VaListTagTypedefType,
5927 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005928 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005929}
5930
5931static TypedefDecl *
5932CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5933 // typedef struct __va_list_tag {
5934 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00005935 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00005936 VaListTagDecl->startDefinition();
5937
5938 const size_t NumFields = 4;
5939 QualType FieldTypes[NumFields];
5940 const char *FieldNames[NumFields];
5941
5942 // unsigned gp_offset;
5943 FieldTypes[0] = Context->UnsignedIntTy;
5944 FieldNames[0] = "gp_offset";
5945
5946 // unsigned fp_offset;
5947 FieldTypes[1] = Context->UnsignedIntTy;
5948 FieldNames[1] = "fp_offset";
5949
5950 // void* overflow_arg_area;
5951 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5952 FieldNames[2] = "overflow_arg_area";
5953
5954 // void* reg_save_area;
5955 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5956 FieldNames[3] = "reg_save_area";
5957
5958 // Create fields
5959 for (unsigned i = 0; i < NumFields; ++i) {
5960 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5961 VaListTagDecl,
5962 SourceLocation(),
5963 SourceLocation(),
5964 &Context->Idents.get(FieldNames[i]),
5965 FieldTypes[i], /*TInfo=*/0,
5966 /*BitWidth=*/0,
5967 /*Mutable=*/false,
5968 ICIS_NoInit);
5969 Field->setAccess(AS_public);
5970 VaListTagDecl->addDecl(Field);
5971 }
5972 VaListTagDecl->completeDefinition();
5973 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005974 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005975
5976 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00005977 TypedefDecl *VaListTagTypedefDecl =
5978 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
5979
Meador Inge5d3fb222012-06-16 03:34:49 +00005980 QualType VaListTagTypedefType =
5981 Context->getTypedefType(VaListTagTypedefDecl);
5982
5983 // typedef __va_list_tag __builtin_va_list[1];
5984 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5985 QualType VaListTagArrayType
5986 = Context->getConstantArrayType(VaListTagTypedefType,
5987 Size, ArrayType::Normal,0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005988 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005989}
5990
5991static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5992 // typedef int __builtin_va_list[4];
5993 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5994 QualType IntArrayType
5995 = Context->getConstantArrayType(Context->IntTy,
5996 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005997 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005998}
5999
Logan Chien57086ce2012-10-10 06:56:20 +00006000static TypedefDecl *
6001CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006002 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006003 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006004 if (Context->getLangOpts().CPlusPlus) {
6005 // namespace std { struct __va_list {
6006 NamespaceDecl *NS;
6007 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6008 Context->getTranslationUnitDecl(),
6009 /*Inline*/false, SourceLocation(),
6010 SourceLocation(), &Context->Idents.get("std"),
6011 /*PrevDecl*/0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006012 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006013 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006014 }
6015
6016 VaListDecl->startDefinition();
6017
6018 // void * __ap;
6019 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6020 VaListDecl,
6021 SourceLocation(),
6022 SourceLocation(),
6023 &Context->Idents.get("__ap"),
6024 Context->getPointerType(Context->VoidTy),
6025 /*TInfo=*/0,
6026 /*BitWidth=*/0,
6027 /*Mutable=*/false,
6028 ICIS_NoInit);
6029 Field->setAccess(AS_public);
6030 VaListDecl->addDecl(Field);
6031
6032 // };
6033 VaListDecl->completeDefinition();
6034
6035 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006036 QualType T = Context->getRecordType(VaListDecl);
6037 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006038}
6039
Ulrich Weigand47445072013-05-06 16:26:41 +00006040static TypedefDecl *
6041CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6042 // typedef struct __va_list_tag {
6043 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006044 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006045 VaListTagDecl->startDefinition();
6046
6047 const size_t NumFields = 4;
6048 QualType FieldTypes[NumFields];
6049 const char *FieldNames[NumFields];
6050
6051 // long __gpr;
6052 FieldTypes[0] = Context->LongTy;
6053 FieldNames[0] = "__gpr";
6054
6055 // long __fpr;
6056 FieldTypes[1] = Context->LongTy;
6057 FieldNames[1] = "__fpr";
6058
6059 // void *__overflow_arg_area;
6060 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6061 FieldNames[2] = "__overflow_arg_area";
6062
6063 // void *__reg_save_area;
6064 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6065 FieldNames[3] = "__reg_save_area";
6066
6067 // Create fields
6068 for (unsigned i = 0; i < NumFields; ++i) {
6069 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6070 VaListTagDecl,
6071 SourceLocation(),
6072 SourceLocation(),
6073 &Context->Idents.get(FieldNames[i]),
6074 FieldTypes[i], /*TInfo=*/0,
6075 /*BitWidth=*/0,
6076 /*Mutable=*/false,
6077 ICIS_NoInit);
6078 Field->setAccess(AS_public);
6079 VaListTagDecl->addDecl(Field);
6080 }
6081 VaListTagDecl->completeDefinition();
6082 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6083 Context->VaListTagTy = VaListTagType;
6084
6085 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006086 TypedefDecl *VaListTagTypedefDecl =
6087 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006088 QualType VaListTagTypedefType =
6089 Context->getTypedefType(VaListTagTypedefDecl);
6090
6091 // typedef __va_list_tag __builtin_va_list[1];
6092 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6093 QualType VaListTagArrayType
6094 = Context->getConstantArrayType(VaListTagTypedefType,
6095 Size, ArrayType::Normal,0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006096
Alp Toker56b5cc92013-12-15 10:36:26 +00006097 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006098}
6099
Meador Inge5d3fb222012-06-16 03:34:49 +00006100static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6101 TargetInfo::BuiltinVaListKind Kind) {
6102 switch (Kind) {
6103 case TargetInfo::CharPtrBuiltinVaList:
6104 return CreateCharPtrBuiltinVaListDecl(Context);
6105 case TargetInfo::VoidPtrBuiltinVaList:
6106 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006107 case TargetInfo::AArch64ABIBuiltinVaList:
6108 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006109 case TargetInfo::PowerABIBuiltinVaList:
6110 return CreatePowerABIBuiltinVaListDecl(Context);
6111 case TargetInfo::X86_64ABIBuiltinVaList:
6112 return CreateX86_64ABIBuiltinVaListDecl(Context);
6113 case TargetInfo::PNaClABIBuiltinVaList:
6114 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006115 case TargetInfo::AAPCSABIBuiltinVaList:
6116 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006117 case TargetInfo::SystemZBuiltinVaList:
6118 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006119 }
6120
6121 llvm_unreachable("Unhandled __builtin_va_list type kind");
6122}
6123
6124TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006125 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006126 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006127 assert(BuiltinVaListDecl->isImplicit());
6128 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006129
6130 return BuiltinVaListDecl;
6131}
6132
Meador Ingecfb60902012-07-01 15:57:25 +00006133QualType ASTContext::getVaListTagType() const {
6134 // Force the creation of VaListTagTy by building the __builtin_va_list
6135 // declaration.
6136 if (VaListTagTy.isNull())
6137 (void) getBuiltinVaListDecl();
6138
6139 return VaListTagTy;
6140}
6141
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006142void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006143 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006144 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006145
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006146 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006147}
6148
John McCalld28ae272009-12-02 08:04:21 +00006149/// \brief Retrieve the template name that corresponds to a non-empty
6150/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006151TemplateName
6152ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6153 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006154 unsigned size = End - Begin;
6155 assert(size > 1 && "set is not overloaded!");
6156
6157 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6158 size * sizeof(FunctionTemplateDecl*));
6159 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6160
6161 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006162 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006163 NamedDecl *D = *I;
6164 assert(isa<FunctionTemplateDecl>(D) ||
6165 (isa<UsingShadowDecl>(D) &&
6166 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6167 *Storage++ = D;
6168 }
6169
6170 return TemplateName(OT);
6171}
6172
Douglas Gregordc572a32009-03-30 22:58:21 +00006173/// \brief Retrieve the template name that represents a qualified
6174/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006175TemplateName
6176ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6177 bool TemplateKeyword,
6178 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006179 assert(NNS && "Missing nested-name-specifier in qualified template name");
6180
Douglas Gregorc42075a2010-02-04 18:10:26 +00006181 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006182 llvm::FoldingSetNodeID ID;
6183 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6184
6185 void *InsertPos = 0;
6186 QualifiedTemplateName *QTN =
6187 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6188 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006189 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6190 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006191 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6192 }
6193
6194 return TemplateName(QTN);
6195}
6196
6197/// \brief Retrieve the template name that represents a dependent
6198/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006199TemplateName
6200ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6201 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006202 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006203 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006204
6205 llvm::FoldingSetNodeID ID;
6206 DependentTemplateName::Profile(ID, NNS, Name);
6207
6208 void *InsertPos = 0;
6209 DependentTemplateName *QTN =
6210 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6211
6212 if (QTN)
6213 return TemplateName(QTN);
6214
6215 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6216 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006217 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6218 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006219 } else {
6220 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006221 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6222 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006223 DependentTemplateName *CheckQTN =
6224 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6225 assert(!CheckQTN && "Dependent type name canonicalization broken");
6226 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006227 }
6228
6229 DependentTemplateNames.InsertNode(QTN, InsertPos);
6230 return TemplateName(QTN);
6231}
6232
Douglas Gregor71395fa2009-11-04 00:56:37 +00006233/// \brief Retrieve the template name that represents a dependent
6234/// template name such as \c MetaFun::template operator+.
6235TemplateName
6236ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006237 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006238 assert((!NNS || NNS->isDependent()) &&
6239 "Nested name specifier must be dependent");
6240
6241 llvm::FoldingSetNodeID ID;
6242 DependentTemplateName::Profile(ID, NNS, Operator);
6243
6244 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006245 DependentTemplateName *QTN
6246 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006247
6248 if (QTN)
6249 return TemplateName(QTN);
6250
6251 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6252 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006253 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6254 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006255 } else {
6256 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006257 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6258 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006259
6260 DependentTemplateName *CheckQTN
6261 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6262 assert(!CheckQTN && "Dependent template name canonicalization broken");
6263 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006264 }
6265
6266 DependentTemplateNames.InsertNode(QTN, InsertPos);
6267 return TemplateName(QTN);
6268}
6269
Douglas Gregor5590be02011-01-15 06:45:20 +00006270TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006271ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6272 TemplateName replacement) const {
6273 llvm::FoldingSetNodeID ID;
6274 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6275
6276 void *insertPos = 0;
6277 SubstTemplateTemplateParmStorage *subst
6278 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6279
6280 if (!subst) {
6281 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6282 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6283 }
6284
6285 return TemplateName(subst);
6286}
6287
6288TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006289ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6290 const TemplateArgument &ArgPack) const {
6291 ASTContext &Self = const_cast<ASTContext &>(*this);
6292 llvm::FoldingSetNodeID ID;
6293 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6294
6295 void *InsertPos = 0;
6296 SubstTemplateTemplateParmPackStorage *Subst
6297 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6298
6299 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006300 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006301 ArgPack.pack_size(),
6302 ArgPack.pack_begin());
6303 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6304 }
6305
6306 return TemplateName(Subst);
6307}
6308
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006309/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006310/// TargetInfo, produce the corresponding type. The unsigned @p Type
6311/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006312CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006313 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006314 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006315 case TargetInfo::SignedChar: return SignedCharTy;
6316 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006317 case TargetInfo::SignedShort: return ShortTy;
6318 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6319 case TargetInfo::SignedInt: return IntTy;
6320 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6321 case TargetInfo::SignedLong: return LongTy;
6322 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6323 case TargetInfo::SignedLongLong: return LongLongTy;
6324 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6325 }
6326
David Blaikie83d382b2011-09-23 05:06:16 +00006327 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006328}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006329
6330//===----------------------------------------------------------------------===//
6331// Type Predicates.
6332//===----------------------------------------------------------------------===//
6333
Fariborz Jahanian96207692009-02-18 21:49:28 +00006334/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6335/// garbage collection attribute.
6336///
John McCall553d45a2011-01-12 00:34:59 +00006337Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006338 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006339 return Qualifiers::GCNone;
6340
David Blaikiebbafb8a2012-03-11 07:00:24 +00006341 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006342 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6343
6344 // Default behaviour under objective-C's gc is for ObjC pointers
6345 // (or pointers to them) be treated as though they were declared
6346 // as __strong.
6347 if (GCAttrs == Qualifiers::GCNone) {
6348 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6349 return Qualifiers::Strong;
6350 else if (Ty->isPointerType())
6351 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6352 } else {
6353 // It's not valid to set GC attributes on anything that isn't a
6354 // pointer.
6355#ifndef NDEBUG
6356 QualType CT = Ty->getCanonicalTypeInternal();
6357 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6358 CT = AT->getElementType();
6359 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6360#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006361 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006362 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006363}
6364
Chris Lattner49af6a42008-04-07 06:51:04 +00006365//===----------------------------------------------------------------------===//
6366// Type Compatibility Testing
6367//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006368
Mike Stump11289f42009-09-09 15:08:12 +00006369/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006370/// compatible.
6371static bool areCompatVectorTypes(const VectorType *LHS,
6372 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006373 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006374 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006375 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006376}
6377
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006378bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6379 QualType SecondVec) {
6380 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6381 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6382
6383 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6384 return true;
6385
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006386 // Treat Neon vector types and most AltiVec vector types as if they are the
6387 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006388 const VectorType *First = FirstVec->getAs<VectorType>();
6389 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006390 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006391 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006392 First->getVectorKind() != VectorType::AltiVecPixel &&
6393 First->getVectorKind() != VectorType::AltiVecBool &&
6394 Second->getVectorKind() != VectorType::AltiVecPixel &&
6395 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006396 return true;
6397
6398 return false;
6399}
6400
Steve Naroff8e6aee52009-07-23 01:01:38 +00006401//===----------------------------------------------------------------------===//
6402// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6403//===----------------------------------------------------------------------===//
6404
6405/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6406/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006407bool
6408ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6409 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006410 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006411 return true;
6412 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6413 E = rProto->protocol_end(); PI != E; ++PI)
6414 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6415 return true;
6416 return false;
6417}
6418
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006419/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6420/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006421bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6422 QualType rhs) {
6423 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6424 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6425 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6426
6427 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6428 E = lhsQID->qual_end(); I != E; ++I) {
6429 bool match = false;
6430 ObjCProtocolDecl *lhsProto = *I;
6431 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6432 E = rhsOPT->qual_end(); J != E; ++J) {
6433 ObjCProtocolDecl *rhsProto = *J;
6434 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6435 match = true;
6436 break;
6437 }
6438 }
6439 if (!match)
6440 return false;
6441 }
6442 return true;
6443}
6444
Steve Naroff8e6aee52009-07-23 01:01:38 +00006445/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6446/// ObjCQualifiedIDType.
6447bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6448 bool compare) {
6449 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006450 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006451 lhs->isObjCIdType() || lhs->isObjCClassType())
6452 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006453 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006454 rhs->isObjCIdType() || rhs->isObjCClassType())
6455 return true;
6456
6457 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006458 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006459
Steve Naroff8e6aee52009-07-23 01:01:38 +00006460 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006461
Steve Naroff8e6aee52009-07-23 01:01:38 +00006462 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006463 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006464 // make sure we check the class hierarchy.
6465 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6466 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6467 E = lhsQID->qual_end(); I != E; ++I) {
6468 // when comparing an id<P> on lhs with a static type on rhs,
6469 // see if static class implements all of id's protocols, directly or
6470 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006471 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006472 return false;
6473 }
6474 }
6475 // If there are no qualifiers and no interface, we have an 'id'.
6476 return true;
6477 }
Mike Stump11289f42009-09-09 15:08:12 +00006478 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006479 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6480 E = lhsQID->qual_end(); I != E; ++I) {
6481 ObjCProtocolDecl *lhsProto = *I;
6482 bool match = false;
6483
6484 // when comparing an id<P> on lhs with a static type on rhs,
6485 // see if static class implements all of id's protocols, directly or
6486 // through its super class and categories.
6487 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6488 E = rhsOPT->qual_end(); J != E; ++J) {
6489 ObjCProtocolDecl *rhsProto = *J;
6490 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6491 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6492 match = true;
6493 break;
6494 }
6495 }
Mike Stump11289f42009-09-09 15:08:12 +00006496 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006497 // make sure we check the class hierarchy.
6498 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6499 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6500 E = lhsQID->qual_end(); I != E; ++I) {
6501 // when comparing an id<P> on lhs with a static type on rhs,
6502 // see if static class implements all of id's protocols, directly or
6503 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006504 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006505 match = true;
6506 break;
6507 }
6508 }
6509 }
6510 if (!match)
6511 return false;
6512 }
Mike Stump11289f42009-09-09 15:08:12 +00006513
Steve Naroff8e6aee52009-07-23 01:01:38 +00006514 return true;
6515 }
Mike Stump11289f42009-09-09 15:08:12 +00006516
Steve Naroff8e6aee52009-07-23 01:01:38 +00006517 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6518 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6519
Mike Stump11289f42009-09-09 15:08:12 +00006520 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006521 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006522 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006523 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6524 E = lhsOPT->qual_end(); I != E; ++I) {
6525 ObjCProtocolDecl *lhsProto = *I;
6526 bool match = false;
6527
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006528 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006529 // see if static class implements all of id's protocols, directly or
6530 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006531 // First, lhs protocols in the qualifier list must be found, direct
6532 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006533 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6534 E = rhsQID->qual_end(); J != E; ++J) {
6535 ObjCProtocolDecl *rhsProto = *J;
6536 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6537 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6538 match = true;
6539 break;
6540 }
6541 }
6542 if (!match)
6543 return false;
6544 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006545
6546 // Static class's protocols, or its super class or category protocols
6547 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6548 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6549 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6550 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6551 // This is rather dubious but matches gcc's behavior. If lhs has
6552 // no type qualifier and its class has no static protocol(s)
6553 // assume that it is mismatch.
6554 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6555 return false;
6556 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6557 LHSInheritedProtocols.begin(),
6558 E = LHSInheritedProtocols.end(); I != E; ++I) {
6559 bool match = false;
6560 ObjCProtocolDecl *lhsProto = (*I);
6561 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6562 E = rhsQID->qual_end(); J != E; ++J) {
6563 ObjCProtocolDecl *rhsProto = *J;
6564 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6565 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6566 match = true;
6567 break;
6568 }
6569 }
6570 if (!match)
6571 return false;
6572 }
6573 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006574 return true;
6575 }
6576 return false;
6577}
6578
Eli Friedman47f77112008-08-22 00:56:42 +00006579/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006580/// compatible for assignment from RHS to LHS. This handles validation of any
6581/// protocol qualifiers on the LHS or RHS.
6582///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006583bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6584 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006585 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6586 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6587
Steve Naroff1329fa02009-07-15 18:40:39 +00006588 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006589 if (LHS->isObjCUnqualifiedIdOrClass() ||
6590 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006591 return true;
6592
John McCall8b07ec22010-05-15 11:32:37 +00006593 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006594 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6595 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006596 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006597
6598 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6599 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6600 QualType(RHSOPT,0));
6601
John McCall8b07ec22010-05-15 11:32:37 +00006602 // If we have 2 user-defined types, fall into that path.
6603 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006604 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006605
Steve Naroff8e6aee52009-07-23 01:01:38 +00006606 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006607}
6608
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006609/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006610/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006611/// arguments in block literals. When passed as arguments, passing 'A*' where
6612/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6613/// not OK. For the return type, the opposite is not OK.
6614bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6615 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006616 const ObjCObjectPointerType *RHSOPT,
6617 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006618 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006619 return true;
6620
6621 if (LHSOPT->isObjCBuiltinType()) {
6622 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6623 }
6624
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006625 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006626 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6627 QualType(RHSOPT,0),
6628 false);
6629
6630 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6631 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6632 if (LHS && RHS) { // We have 2 user-defined types.
6633 if (LHS != RHS) {
6634 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006635 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006636 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006637 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006638 }
6639 else
6640 return true;
6641 }
6642 return false;
6643}
6644
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006645/// getIntersectionOfProtocols - This routine finds the intersection of set
6646/// of protocols inherited from two distinct objective-c pointer objects.
6647/// It is used to build composite qualifier list of the composite type of
6648/// the conditional expression involving two objective-c pointer objects.
6649static
6650void getIntersectionOfProtocols(ASTContext &Context,
6651 const ObjCObjectPointerType *LHSOPT,
6652 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006653 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006654
John McCall8b07ec22010-05-15 11:32:37 +00006655 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6656 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6657 assert(LHS->getInterface() && "LHS must have an interface base");
6658 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006659
6660 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6661 unsigned LHSNumProtocols = LHS->getNumProtocols();
6662 if (LHSNumProtocols > 0)
6663 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6664 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006665 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006666 Context.CollectInheritedProtocols(LHS->getInterface(),
6667 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006668 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6669 LHSInheritedProtocols.end());
6670 }
6671
6672 unsigned RHSNumProtocols = RHS->getNumProtocols();
6673 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006674 ObjCProtocolDecl **RHSProtocols =
6675 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006676 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6677 if (InheritedProtocolSet.count(RHSProtocols[i]))
6678 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006679 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006680 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006681 Context.CollectInheritedProtocols(RHS->getInterface(),
6682 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006683 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6684 RHSInheritedProtocols.begin(),
6685 E = RHSInheritedProtocols.end(); I != E; ++I)
6686 if (InheritedProtocolSet.count((*I)))
6687 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006688 }
6689}
6690
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006691/// areCommonBaseCompatible - Returns common base class of the two classes if
6692/// one found. Note that this is O'2 algorithm. But it will be called as the
6693/// last type comparison in a ?-exp of ObjC pointer types before a
6694/// warning is issued. So, its invokation is extremely rare.
6695QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006696 const ObjCObjectPointerType *Lptr,
6697 const ObjCObjectPointerType *Rptr) {
6698 const ObjCObjectType *LHS = Lptr->getObjectType();
6699 const ObjCObjectType *RHS = Rptr->getObjectType();
6700 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6701 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006702 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006703 return QualType();
6704
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006705 do {
John McCall8b07ec22010-05-15 11:32:37 +00006706 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006707 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006708 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006709 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6710
6711 QualType Result = QualType(LHS, 0);
6712 if (!Protocols.empty())
6713 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6714 Result = getObjCObjectPointerType(Result);
6715 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006716 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006717 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006718
6719 return QualType();
6720}
6721
John McCall8b07ec22010-05-15 11:32:37 +00006722bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6723 const ObjCObjectType *RHS) {
6724 assert(LHS->getInterface() && "LHS is not an interface type");
6725 assert(RHS->getInterface() && "RHS is not an interface type");
6726
Chris Lattner49af6a42008-04-07 06:51:04 +00006727 // Verify that the base decls are compatible: the RHS must be a subclass of
6728 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006729 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006730 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006731
Chris Lattner49af6a42008-04-07 06:51:04 +00006732 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6733 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006734 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006735 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006736
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006737 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6738 // more detailed analysis is required.
6739 if (RHS->getNumProtocols() == 0) {
6740 // OK, if LHS is a superclass of RHS *and*
6741 // this superclass is assignment compatible with LHS.
6742 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006743 bool IsSuperClass =
6744 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6745 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006746 // OK if conversion of LHS to SuperClass results in narrowing of types
6747 // ; i.e., SuperClass may implement at least one of the protocols
6748 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6749 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6750 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006751 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006752 // If super class has no protocols, it is not a match.
6753 if (SuperClassInheritedProtocols.empty())
6754 return false;
6755
6756 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6757 LHSPE = LHS->qual_end();
6758 LHSPI != LHSPE; LHSPI++) {
6759 bool SuperImplementsProtocol = false;
6760 ObjCProtocolDecl *LHSProto = (*LHSPI);
6761
6762 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6763 SuperClassInheritedProtocols.begin(),
6764 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6765 ObjCProtocolDecl *SuperClassProto = (*I);
6766 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6767 SuperImplementsProtocol = true;
6768 break;
6769 }
6770 }
6771 if (!SuperImplementsProtocol)
6772 return false;
6773 }
6774 return true;
6775 }
6776 return false;
6777 }
Mike Stump11289f42009-09-09 15:08:12 +00006778
John McCall8b07ec22010-05-15 11:32:37 +00006779 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6780 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00006781 LHSPI != LHSPE; LHSPI++) {
6782 bool RHSImplementsProtocol = false;
6783
6784 // If the RHS doesn't implement the protocol on the left, the types
6785 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00006786 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6787 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00006788 RHSPI != RHSPE; RHSPI++) {
6789 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006790 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00006791 break;
6792 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006793 }
6794 // FIXME: For better diagnostics, consider passing back the protocol name.
6795 if (!RHSImplementsProtocol)
6796 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006797 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006798 // The RHS implements all protocols listed on the LHS.
6799 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006800}
6801
Steve Naroffb7605152009-02-12 17:52:19 +00006802bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6803 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006804 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6805 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006806
Steve Naroff7cae42b2009-07-10 23:34:53 +00006807 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006808 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006809
6810 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6811 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006812}
6813
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006814bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6815 return canAssignObjCInterfaces(
6816 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6817 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6818}
6819
Mike Stump11289f42009-09-09 15:08:12 +00006820/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006821/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006822/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006823/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006824bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6825 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006826 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006827 return hasSameType(LHS, RHS);
6828
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006829 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006830}
6831
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006832bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006833 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006834}
6835
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006836bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6837 return !mergeTypes(LHS, RHS, true).isNull();
6838}
6839
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006840/// mergeTransparentUnionType - if T is a transparent union type and a member
6841/// of T is compatible with SubType, return the merged type, else return
6842/// QualType()
6843QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6844 bool OfBlockPointer,
6845 bool Unqualified) {
6846 if (const RecordType *UT = T->getAsUnionType()) {
6847 RecordDecl *UD = UT->getDecl();
6848 if (UD->hasAttr<TransparentUnionAttr>()) {
6849 for (RecordDecl::field_iterator it = UD->field_begin(),
6850 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00006851 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006852 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6853 if (!MT.isNull())
6854 return MT;
6855 }
6856 }
6857 }
6858
6859 return QualType();
6860}
6861
Alp Toker9cacbab2014-01-20 20:26:09 +00006862/// mergeFunctionParameterTypes - merge two types which appear as function
6863/// parameter types
6864QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
6865 bool OfBlockPointer,
6866 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006867 // GNU extension: two types are compatible if they appear as a function
6868 // argument, one of the types is a transparent union type and the other
6869 // type is compatible with a union member
6870 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6871 Unqualified);
6872 if (!lmerge.isNull())
6873 return lmerge;
6874
6875 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6876 Unqualified);
6877 if (!rmerge.isNull())
6878 return rmerge;
6879
6880 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6881}
6882
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006883QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006884 bool OfBlockPointer,
6885 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006886 const FunctionType *lbase = lhs->getAs<FunctionType>();
6887 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006888 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6889 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006890 bool allLTypes = true;
6891 bool allRTypes = true;
6892
6893 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006894 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006895 if (OfBlockPointer) {
6896 QualType RHS = rbase->getResultType();
6897 QualType LHS = lbase->getResultType();
6898 bool UnqualifiedResult = Unqualified;
6899 if (!UnqualifiedResult)
6900 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006901 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006902 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006903 else
John McCall8c6b56f2010-12-15 01:06:38 +00006904 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6905 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006906 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006907
6908 if (Unqualified)
6909 retType = retType.getUnqualifiedType();
6910
6911 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6912 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6913 if (Unqualified) {
6914 LRetType = LRetType.getUnqualifiedType();
6915 RRetType = RRetType.getUnqualifiedType();
6916 }
6917
6918 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006919 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006920 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006921 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006922
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006923 // FIXME: double check this
6924 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6925 // rbase->getRegParmAttr() != 0 &&
6926 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006927 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6928 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006929
Douglas Gregor8c940862010-01-18 17:14:39 +00006930 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00006931 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00006932 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006933
John McCall8c6b56f2010-12-15 01:06:38 +00006934 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006935 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6936 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006937 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6938 return QualType();
6939
John McCall31168b02011-06-15 23:02:42 +00006940 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6941 return QualType();
6942
John McCall8c6b56f2010-12-15 01:06:38 +00006943 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6944 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006945
Rafael Espindola8778c282012-11-29 16:09:03 +00006946 if (lbaseInfo.getNoReturn() != NoReturn)
6947 allLTypes = false;
6948 if (rbaseInfo.getNoReturn() != NoReturn)
6949 allRTypes = false;
6950
John McCall31168b02011-06-15 23:02:42 +00006951 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006952
Eli Friedman47f77112008-08-22 00:56:42 +00006953 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006954 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6955 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00006956 // Compatible functions must have the same number of parameters
6957 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00006958 return QualType();
6959
6960 // Variadic and non-variadic functions aren't compatible
6961 if (lproto->isVariadic() != rproto->isVariadic())
6962 return QualType();
6963
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006964 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6965 return QualType();
6966
Fariborz Jahanian97676972011-09-28 21:52:05 +00006967 if (LangOpts.ObjCAutoRefCount &&
6968 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6969 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00006970
6971 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006972 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00006973 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
6974 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
6975 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
6976 QualType paramType = mergeFunctionParameterTypes(
6977 lParamType, rParamType, OfBlockPointer, Unqualified);
6978 if (paramType.isNull())
6979 return QualType();
6980
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006981 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00006982 paramType = paramType.getUnqualifiedType();
6983
6984 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006985 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00006986 lParamType = lParamType.getUnqualifiedType();
6987 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006988 }
Alp Toker601b22c2014-01-21 23:35:24 +00006989
6990 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00006991 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00006992 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00006993 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006994 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006995
Eli Friedman47f77112008-08-22 00:56:42 +00006996 if (allLTypes) return lhs;
6997 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006998
6999 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7000 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007001 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007002 }
7003
7004 if (lproto) allRTypes = false;
7005 if (rproto) allLTypes = false;
7006
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007007 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007008 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007009 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007010 if (proto->isVariadic()) return QualType();
7011 // Check that the types are compatible with the types that
7012 // would result from default argument promotions (C99 6.7.5.3p15).
7013 // The only types actually affected are promotable integer
7014 // types and floats, which would be passed as a different
7015 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007016 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7017 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007018
Eli Friedman448ce402012-08-30 00:44:15 +00007019 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007020 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007021 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7022 paramTy = Enum->getDecl()->getIntegerType();
7023 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007024 return QualType();
7025 }
Alp Toker601b22c2014-01-21 23:35:24 +00007026
7027 if (paramTy->isPromotableIntegerType() ||
7028 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007029 return QualType();
7030 }
7031
7032 if (allLTypes) return lhs;
7033 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007034
7035 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7036 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007037 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007038 }
7039
7040 if (allLTypes) return lhs;
7041 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007042 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007043}
7044
John McCall433c2e62013-03-21 00:10:07 +00007045/// Given that we have an enum type and a non-enum type, try to merge them.
7046static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7047 QualType other, bool isBlockReturnType) {
7048 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7049 // a signed integer type, or an unsigned integer type.
7050 // Compatibility is based on the underlying type, not the promotion
7051 // type.
7052 QualType underlyingType = ET->getDecl()->getIntegerType();
7053 if (underlyingType.isNull()) return QualType();
7054 if (Context.hasSameType(underlyingType, other))
7055 return other;
7056
7057 // In block return types, we're more permissive and accept any
7058 // integral type of the same size.
7059 if (isBlockReturnType && other->isIntegerType() &&
7060 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7061 return other;
7062
7063 return QualType();
7064}
7065
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007066QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007067 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007068 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007069 // C++ [expr]: If an expression initially has the type "reference to T", the
7070 // type is adjusted to "T" prior to any further analysis, the expression
7071 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007072 // expression is an lvalue unless the reference is an rvalue reference and
7073 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007074 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7075 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007076
7077 if (Unqualified) {
7078 LHS = LHS.getUnqualifiedType();
7079 RHS = RHS.getUnqualifiedType();
7080 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007081
Eli Friedman47f77112008-08-22 00:56:42 +00007082 QualType LHSCan = getCanonicalType(LHS),
7083 RHSCan = getCanonicalType(RHS);
7084
7085 // If two types are identical, they are compatible.
7086 if (LHSCan == RHSCan)
7087 return LHS;
7088
John McCall8ccfcb52009-09-24 19:53:00 +00007089 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007090 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7091 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007092 if (LQuals != RQuals) {
7093 // If any of these qualifiers are different, we have a type
7094 // mismatch.
7095 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007096 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7097 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007098 return QualType();
7099
7100 // Exactly one GC qualifier difference is allowed: __strong is
7101 // okay if the other type has no GC qualifier but is an Objective
7102 // C object pointer (i.e. implicitly strong by default). We fix
7103 // this by pretending that the unqualified type was actually
7104 // qualified __strong.
7105 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7106 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7107 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7108
7109 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7110 return QualType();
7111
7112 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7113 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7114 }
7115 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7116 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7117 }
Eli Friedman47f77112008-08-22 00:56:42 +00007118 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007119 }
7120
7121 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007122
Eli Friedmandcca6332009-06-01 01:22:52 +00007123 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7124 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007125
Chris Lattnerfd652912008-01-14 05:45:46 +00007126 // We want to consider the two function types to be the same for these
7127 // comparisons, just force one to the other.
7128 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7129 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007130
7131 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007132 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7133 LHSClass = Type::ConstantArray;
7134 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7135 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007136
John McCall8b07ec22010-05-15 11:32:37 +00007137 // ObjCInterfaces are just specialized ObjCObjects.
7138 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7139 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7140
Nate Begemance4d7fc2008-04-18 23:10:10 +00007141 // Canonicalize ExtVector -> Vector.
7142 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7143 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007144
Chris Lattner95554662008-04-07 05:43:21 +00007145 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007146 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007147 // Note that we only have special rules for turning block enum
7148 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007149 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007150 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007151 }
John McCall9dd450b2009-09-21 23:43:11 +00007152 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007153 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007154 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007155 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007156 if (OfBlockPointer && !BlockReturnType) {
7157 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7158 return LHS;
7159 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7160 return RHS;
7161 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007162
Eli Friedman47f77112008-08-22 00:56:42 +00007163 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007164 }
Eli Friedman47f77112008-08-22 00:56:42 +00007165
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007166 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007167 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007168#define TYPE(Class, Base)
7169#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007170#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007171#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7172#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7173#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007174 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007175
Richard Smith27d807c2013-04-30 13:56:41 +00007176 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007177 case Type::LValueReference:
7178 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007179 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007180 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007181
John McCall8b07ec22010-05-15 11:32:37 +00007182 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007183 case Type::IncompleteArray:
7184 case Type::VariableArray:
7185 case Type::FunctionProto:
7186 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007187 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007188
Chris Lattnerfd652912008-01-14 05:45:46 +00007189 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007190 {
7191 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007192 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7193 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007194 if (Unqualified) {
7195 LHSPointee = LHSPointee.getUnqualifiedType();
7196 RHSPointee = RHSPointee.getUnqualifiedType();
7197 }
7198 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7199 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007200 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007201 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007202 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007203 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007204 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007205 return getPointerType(ResultType);
7206 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007207 case Type::BlockPointer:
7208 {
7209 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007210 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7211 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007212 if (Unqualified) {
7213 LHSPointee = LHSPointee.getUnqualifiedType();
7214 RHSPointee = RHSPointee.getUnqualifiedType();
7215 }
7216 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7217 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007218 if (ResultType.isNull()) return QualType();
7219 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7220 return LHS;
7221 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7222 return RHS;
7223 return getBlockPointerType(ResultType);
7224 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007225 case Type::Atomic:
7226 {
7227 // Merge two pointer types, while trying to preserve typedef info
7228 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7229 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7230 if (Unqualified) {
7231 LHSValue = LHSValue.getUnqualifiedType();
7232 RHSValue = RHSValue.getUnqualifiedType();
7233 }
7234 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7235 Unqualified);
7236 if (ResultType.isNull()) return QualType();
7237 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7238 return LHS;
7239 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7240 return RHS;
7241 return getAtomicType(ResultType);
7242 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007243 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007244 {
7245 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7246 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7247 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7248 return QualType();
7249
7250 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7251 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007252 if (Unqualified) {
7253 LHSElem = LHSElem.getUnqualifiedType();
7254 RHSElem = RHSElem.getUnqualifiedType();
7255 }
7256
7257 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007258 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007259 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7260 return LHS;
7261 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7262 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007263 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7264 ArrayType::ArraySizeModifier(), 0);
7265 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7266 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007267 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7268 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007269 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7270 return LHS;
7271 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7272 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007273 if (LVAT) {
7274 // FIXME: This isn't correct! But tricky to implement because
7275 // the array's size has to be the size of LHS, but the type
7276 // has to be different.
7277 return LHS;
7278 }
7279 if (RVAT) {
7280 // FIXME: This isn't correct! But tricky to implement because
7281 // the array's size has to be the size of RHS, but the type
7282 // has to be different.
7283 return RHS;
7284 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007285 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7286 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007287 return getIncompleteArrayType(ResultType,
7288 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007289 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007290 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007291 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007292 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007293 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007294 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007295 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007296 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007297 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007298 case Type::Complex:
7299 // Distinct complex types are incompatible.
7300 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007301 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007302 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007303 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7304 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007305 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007306 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007307 case Type::ObjCObject: {
7308 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007309 // FIXME: This should be type compatibility, e.g. whether
7310 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007311 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7312 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7313 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007314 return LHS;
7315
Eli Friedman47f77112008-08-22 00:56:42 +00007316 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007317 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007318 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007319 if (OfBlockPointer) {
7320 if (canAssignObjCInterfacesInBlockPointer(
7321 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007322 RHS->getAs<ObjCObjectPointerType>(),
7323 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007324 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007325 return QualType();
7326 }
John McCall9dd450b2009-09-21 23:43:11 +00007327 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7328 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007329 return LHS;
7330
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007331 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007332 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007333 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007334
David Blaikie8a40f702012-01-17 06:56:22 +00007335 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007336}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007337
Fariborz Jahanian97676972011-09-28 21:52:05 +00007338bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7339 const FunctionProtoType *FromFunctionType,
7340 const FunctionProtoType *ToFunctionType) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007341 if (FromFunctionType->hasAnyConsumedParams() !=
7342 ToFunctionType->hasAnyConsumedParams())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007343 return false;
7344 FunctionProtoType::ExtProtoInfo FromEPI =
7345 FromFunctionType->getExtProtoInfo();
7346 FunctionProtoType::ExtProtoInfo ToEPI =
7347 ToFunctionType->getExtProtoInfo();
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007348 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
Alp Toker601b22c2014-01-21 23:35:24 +00007349 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7350 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
Fariborz Jahanian97676972011-09-28 21:52:05 +00007351 return false;
7352 }
7353 return true;
7354}
7355
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007356/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7357/// 'RHS' attributes and returns the merged version; including for function
7358/// return types.
7359QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7360 QualType LHSCan = getCanonicalType(LHS),
7361 RHSCan = getCanonicalType(RHS);
7362 // If two types are identical, they are compatible.
7363 if (LHSCan == RHSCan)
7364 return LHS;
7365 if (RHSCan->isFunctionType()) {
7366 if (!LHSCan->isFunctionType())
7367 return QualType();
7368 QualType OldReturnType =
7369 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
7370 QualType NewReturnType =
7371 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
7372 QualType ResReturnType =
7373 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7374 if (ResReturnType.isNull())
7375 return QualType();
7376 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7377 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7378 // In either case, use OldReturnType to build the new function type.
7379 const FunctionType *F = LHS->getAs<FunctionType>();
7380 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007381 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7382 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007383 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00007384 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007385 return ResultType;
7386 }
7387 }
7388 return QualType();
7389 }
7390
7391 // If the qualifiers are different, the types can still be merged.
7392 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7393 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7394 if (LQuals != RQuals) {
7395 // If any of these qualifiers are different, we have a type mismatch.
7396 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7397 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7398 return QualType();
7399
7400 // Exactly one GC qualifier difference is allowed: __strong is
7401 // okay if the other type has no GC qualifier but is an Objective
7402 // C object pointer (i.e. implicitly strong by default). We fix
7403 // this by pretending that the unqualified type was actually
7404 // qualified __strong.
7405 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7406 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7407 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7408
7409 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7410 return QualType();
7411
7412 if (GC_L == Qualifiers::Strong)
7413 return LHS;
7414 if (GC_R == Qualifiers::Strong)
7415 return RHS;
7416 return QualType();
7417 }
7418
7419 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7420 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7421 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7422 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7423 if (ResQT == LHSBaseQT)
7424 return LHS;
7425 if (ResQT == RHSBaseQT)
7426 return RHS;
7427 }
7428 return QualType();
7429}
7430
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007431//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007432// Integer Predicates
7433//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007434
Jay Foad39c79802011-01-12 09:06:06 +00007435unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00007436 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00007437 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007438 if (T->isBooleanType())
7439 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007440 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007441 return (unsigned)getTypeSize(T);
7442}
7443
Abramo Bagnara13640492012-09-09 10:21:24 +00007444QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007445 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007446
7447 // Turn <4 x signed int> -> <4 x unsigned int>
7448 if (const VectorType *VTy = T->getAs<VectorType>())
7449 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007450 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007451
7452 // For enums, we return the unsigned version of the base type.
7453 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007454 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007455
7456 const BuiltinType *BTy = T->getAs<BuiltinType>();
7457 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007458 switch (BTy->getKind()) {
7459 case BuiltinType::Char_S:
7460 case BuiltinType::SChar:
7461 return UnsignedCharTy;
7462 case BuiltinType::Short:
7463 return UnsignedShortTy;
7464 case BuiltinType::Int:
7465 return UnsignedIntTy;
7466 case BuiltinType::Long:
7467 return UnsignedLongTy;
7468 case BuiltinType::LongLong:
7469 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007470 case BuiltinType::Int128:
7471 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007472 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007473 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007474 }
7475}
7476
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007477ASTMutationListener::~ASTMutationListener() { }
7478
Richard Smith1fa5d642013-05-11 05:45:24 +00007479void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7480 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00007481
7482//===----------------------------------------------------------------------===//
7483// Builtin Type Computation
7484//===----------------------------------------------------------------------===//
7485
7486/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007487/// pointer over the consumed characters. This returns the resultant type. If
7488/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7489/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7490/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007491///
7492/// RequiresICE is filled in on return to indicate whether the value is required
7493/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007494static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007495 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007496 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007497 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007498 // Modifiers.
7499 int HowLong = 0;
7500 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007501 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007502
Chris Lattnerdc226c22010-10-01 22:42:38 +00007503 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007504 bool Done = false;
7505 while (!Done) {
7506 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007507 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007508 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007509 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007510 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007511 case 'S':
7512 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7513 assert(!Signed && "Can't use 'S' modifier multiple times!");
7514 Signed = true;
7515 break;
7516 case 'U':
7517 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7518 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7519 Unsigned = true;
7520 break;
7521 case 'L':
7522 assert(HowLong <= 2 && "Can't have LLLL modifier");
7523 ++HowLong;
7524 break;
7525 }
7526 }
7527
7528 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007529
Chris Lattnerecd79c62009-06-14 00:45:47 +00007530 // Read the base type.
7531 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007532 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007533 case 'v':
7534 assert(HowLong == 0 && !Signed && !Unsigned &&
7535 "Bad modifiers used with 'v'!");
7536 Type = Context.VoidTy;
7537 break;
Jack Carter24bef982013-08-15 15:16:57 +00007538 case 'h':
7539 assert(HowLong == 0 && !Signed && !Unsigned &&
7540 "Bad modifiers used with 'f'!");
7541 Type = Context.HalfTy;
7542 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007543 case 'f':
7544 assert(HowLong == 0 && !Signed && !Unsigned &&
7545 "Bad modifiers used with 'f'!");
7546 Type = Context.FloatTy;
7547 break;
7548 case 'd':
7549 assert(HowLong < 2 && !Signed && !Unsigned &&
7550 "Bad modifiers used with 'd'!");
7551 if (HowLong)
7552 Type = Context.LongDoubleTy;
7553 else
7554 Type = Context.DoubleTy;
7555 break;
7556 case 's':
7557 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7558 if (Unsigned)
7559 Type = Context.UnsignedShortTy;
7560 else
7561 Type = Context.ShortTy;
7562 break;
7563 case 'i':
7564 if (HowLong == 3)
7565 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7566 else if (HowLong == 2)
7567 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7568 else if (HowLong == 1)
7569 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7570 else
7571 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7572 break;
7573 case 'c':
7574 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7575 if (Signed)
7576 Type = Context.SignedCharTy;
7577 else if (Unsigned)
7578 Type = Context.UnsignedCharTy;
7579 else
7580 Type = Context.CharTy;
7581 break;
7582 case 'b': // boolean
7583 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7584 Type = Context.BoolTy;
7585 break;
7586 case 'z': // size_t.
7587 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7588 Type = Context.getSizeType();
7589 break;
7590 case 'F':
7591 Type = Context.getCFConstantStringType();
7592 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007593 case 'G':
7594 Type = Context.getObjCIdType();
7595 break;
7596 case 'H':
7597 Type = Context.getObjCSelType();
7598 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00007599 case 'M':
7600 Type = Context.getObjCSuperType();
7601 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007602 case 'a':
7603 Type = Context.getBuiltinVaListType();
7604 assert(!Type.isNull() && "builtin va list type not initialized!");
7605 break;
7606 case 'A':
7607 // This is a "reference" to a va_list; however, what exactly
7608 // this means depends on how va_list is defined. There are two
7609 // different kinds of va_list: ones passed by value, and ones
7610 // passed by reference. An example of a by-value va_list is
7611 // x86, where va_list is a char*. An example of by-ref va_list
7612 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7613 // we want this argument to be a char*&; for x86-64, we want
7614 // it to be a __va_list_tag*.
7615 Type = Context.getBuiltinVaListType();
7616 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007617 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007618 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007619 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007620 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007621 break;
7622 case 'V': {
7623 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007624 unsigned NumElements = strtoul(Str, &End, 10);
7625 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007626 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007627
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007628 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7629 RequiresICE, false);
7630 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007631
7632 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007633 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007634 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007635 break;
7636 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007637 case 'E': {
7638 char *End;
7639
7640 unsigned NumElements = strtoul(Str, &End, 10);
7641 assert(End != Str && "Missing vector size");
7642
7643 Str = End;
7644
7645 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7646 false);
7647 Type = Context.getExtVectorType(ElementType, NumElements);
7648 break;
7649 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007650 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007651 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7652 false);
7653 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007654 Type = Context.getComplexType(ElementType);
7655 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007656 }
7657 case 'Y' : {
7658 Type = Context.getPointerDiffType();
7659 break;
7660 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007661 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007662 Type = Context.getFILEType();
7663 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007664 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007665 return QualType();
7666 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007667 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007668 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007669 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007670 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007671 else
7672 Type = Context.getjmp_bufType();
7673
Mike Stump2adb4da2009-07-28 23:47:15 +00007674 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007675 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007676 return QualType();
7677 }
7678 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007679 case 'K':
7680 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7681 Type = Context.getucontext_tType();
7682
7683 if (Type.isNull()) {
7684 Error = ASTContext::GE_Missing_ucontext;
7685 return QualType();
7686 }
7687 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00007688 case 'p':
7689 Type = Context.getProcessIDType();
7690 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007691 }
Mike Stump11289f42009-09-09 15:08:12 +00007692
Chris Lattnerdc226c22010-10-01 22:42:38 +00007693 // If there are modifiers and if we're allowed to parse them, go for it.
7694 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007695 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007696 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007697 default: Done = true; --Str; break;
7698 case '*':
7699 case '&': {
7700 // Both pointers and references can have their pointee types
7701 // qualified with an address space.
7702 char *End;
7703 unsigned AddrSpace = strtoul(Str, &End, 10);
7704 if (End != Str && AddrSpace != 0) {
7705 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7706 Str = End;
7707 }
7708 if (c == '*')
7709 Type = Context.getPointerType(Type);
7710 else
7711 Type = Context.getLValueReferenceType(Type);
7712 break;
7713 }
7714 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7715 case 'C':
7716 Type = Type.withConst();
7717 break;
7718 case 'D':
7719 Type = Context.getVolatileType(Type);
7720 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007721 case 'R':
7722 Type = Type.withRestrict();
7723 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007724 }
7725 }
Chris Lattner84733392010-10-01 07:13:18 +00007726
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007727 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007728 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007729
Chris Lattnerecd79c62009-06-14 00:45:47 +00007730 return Type;
7731}
7732
7733/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007734QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007735 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007736 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007737 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007738
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007739 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007740
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007741 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007742 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007743 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7744 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007745 if (Error != GE_None)
7746 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007747
7748 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7749
Chris Lattnerecd79c62009-06-14 00:45:47 +00007750 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007751 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007752 if (Error != GE_None)
7753 return QualType();
7754
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007755 // If this argument is required to be an IntegerConstantExpression and the
7756 // caller cares, fill in the bitmask we return.
7757 if (RequiresICE && IntegerConstantArgs)
7758 *IntegerConstantArgs |= 1 << ArgTypes.size();
7759
Chris Lattnerecd79c62009-06-14 00:45:47 +00007760 // Do array -> pointer decay. The builtin should use the decayed type.
7761 if (Ty->isArrayType())
7762 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007763
Chris Lattnerecd79c62009-06-14 00:45:47 +00007764 ArgTypes.push_back(Ty);
7765 }
7766
7767 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7768 "'.' should only occur at end of builtin type list!");
7769
Reid Kleckner78af0702013-08-27 23:08:25 +00007770 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00007771 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7772
7773 bool Variadic = (TypeStr[0] == '.');
7774
7775 // We really shouldn't be making a no-proto type here, especially in C++.
7776 if (ArgTypes.empty() && Variadic)
7777 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007778
John McCalldb40c7f2010-12-14 08:05:40 +00007779 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007780 EPI.ExtInfo = EI;
7781 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007782
Jordan Rose5c382722013-03-08 21:51:21 +00007783 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007784}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007785
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007786GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007787 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007788 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007789
Rafael Espindola3ae00052013-05-13 00:12:11 +00007790 GVALinkage External = GVA_StrongExternal;
7791 switch (FD->getTemplateSpecializationKind()) {
7792 case TSK_Undeclared:
7793 case TSK_ExplicitSpecialization:
7794 External = GVA_StrongExternal;
7795 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007796
Rafael Espindola3ae00052013-05-13 00:12:11 +00007797 case TSK_ExplicitInstantiationDefinition:
7798 return GVA_ExplicitTemplateInstantiation;
7799
7800 case TSK_ExplicitInstantiationDeclaration:
7801 case TSK_ImplicitInstantiation:
7802 External = GVA_TemplateInstantiation;
7803 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007804 }
7805
7806 if (!FD->isInlined())
7807 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00007808
Alp Tokerbfa39342014-01-14 12:51:41 +00007809 if ((!getLangOpts().CPlusPlus && !getLangOpts().MSVCCompat) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00007810 FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007811 // GNU or C99 inline semantics. Determine whether this symbol should be
7812 // externally visible.
7813 if (FD->isInlineDefinitionExternallyVisible())
7814 return External;
7815
7816 // C99 inline semantics, where the symbol is not externally visible.
7817 return GVA_C99Inline;
7818 }
7819
7820 // C++0x [temp.explicit]p9:
7821 // [ Note: The intent is that an inline function that is the subject of
7822 // an explicit instantiation declaration will still be implicitly
7823 // instantiated when used so that the body can be considered for
7824 // inlining, but that no out-of-line copy of the inline function would be
7825 // generated in the translation unit. -- end note ]
7826 if (FD->getTemplateSpecializationKind()
7827 == TSK_ExplicitInstantiationDeclaration)
7828 return GVA_C99Inline;
7829
7830 return GVA_CXXInline;
7831}
7832
7833GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007834 if (!VD->isExternallyVisible())
7835 return GVA_Internal;
7836
Richard Smith8809a0c2013-09-27 20:14:12 +00007837 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007838 case TSK_Undeclared:
7839 case TSK_ExplicitSpecialization:
7840 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007841
Rafael Espindola3ae00052013-05-13 00:12:11 +00007842 case TSK_ExplicitInstantiationDeclaration:
7843 llvm_unreachable("Variable should not be instantiated");
7844 // Fall through to treat this like any other instantiation.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007845
Rafael Espindola3ae00052013-05-13 00:12:11 +00007846 case TSK_ExplicitInstantiationDefinition:
7847 return GVA_ExplicitTemplateInstantiation;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007848
Rafael Espindola3ae00052013-05-13 00:12:11 +00007849 case TSK_ImplicitInstantiation:
7850 return GVA_TemplateInstantiation;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007851 }
Rafael Espindola27699c82013-05-13 14:05:53 +00007852
7853 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007854}
7855
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007856bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007857 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7858 if (!VD->isFileVarDecl())
7859 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00007860 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7861 // We never need to emit an uninstantiated function template.
7862 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7863 return false;
7864 } else
7865 return false;
7866
7867 // If this is a member of a class template, we do not need to emit it.
7868 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007869 return false;
7870
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007871 // Weak references don't produce any output by themselves.
7872 if (D->hasAttr<WeakRefAttr>())
7873 return false;
7874
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007875 // Aliases and used decls are required.
7876 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7877 return true;
7878
7879 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7880 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007881 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007882 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007883
7884 // Constructors and destructors are required.
7885 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7886 return true;
7887
John McCall6bd2a892013-01-25 22:31:03 +00007888 // The key function for a class is required. This rule only comes
7889 // into play when inline functions can be key functions, though.
7890 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7891 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7892 const CXXRecordDecl *RD = MD->getParent();
7893 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7894 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7895 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7896 return true;
7897 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007898 }
7899 }
7900
7901 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7902
7903 // static, static inline, always_inline, and extern inline functions can
7904 // always be deferred. Normal inline functions can be deferred in C99/C++.
7905 // Implicit template instantiations can also be deferred in C++.
7906 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007907 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007908 return false;
7909 return true;
7910 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007911
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007912 const VarDecl *VD = cast<VarDecl>(D);
7913 assert(VD->isFileVarDecl() && "Expected file scoped var");
7914
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007915 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7916 return false;
7917
Richard Smitha0e5e542012-11-12 21:38:00 +00007918 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007919 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smitha0e5e542012-11-12 21:38:00 +00007920 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7921 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007922
Richard Smitha0e5e542012-11-12 21:38:00 +00007923 // Variables that have destruction with side-effects are required.
7924 if (VD->getType().isDestructedType())
7925 return true;
7926
7927 // Variables that have initialization with side-effects are required.
7928 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7929 return true;
7930
7931 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007932}
Charles Davis53c59df2010-08-16 03:33:14 +00007933
Reid Kleckner78af0702013-08-27 23:08:25 +00007934CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
7935 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00007936 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00007937 if (IsCXXMethod)
7938 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007939
Reid Kleckner78af0702013-08-27 23:08:25 +00007940 return (LangOpts.MRTD && !IsVariadic) ? CC_X86StdCall : CC_C;
Charles Davis99202b32010-11-09 18:04:24 +00007941}
7942
Jay Foad39c79802011-01-12 09:06:06 +00007943bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007944 // Pass through to the C++ ABI object
7945 return ABI->isNearlyEmpty(RD);
7946}
7947
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007948MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00007949 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00007950 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00007951 case TargetCXXABI::GenericItanium:
7952 case TargetCXXABI::GenericARM:
7953 case TargetCXXABI::iOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00007954 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00007955 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00007956 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007957 }
David Blaikie83d382b2011-09-23 05:06:16 +00007958 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007959}
7960
Charles Davis53c59df2010-08-16 03:33:14 +00007961CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007962
7963size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00007964 return ASTRecordLayouts.getMemorySize() +
7965 llvm::capacity_in_bytes(ObjCLayouts) +
7966 llvm::capacity_in_bytes(KeyFunctions) +
7967 llvm::capacity_in_bytes(ObjCImpls) +
7968 llvm::capacity_in_bytes(BlockVarCopyInits) +
7969 llvm::capacity_in_bytes(DeclAttrs) +
7970 llvm::capacity_in_bytes(TemplateOrInstantiation) +
7971 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
7972 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
7973 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
7974 llvm::capacity_in_bytes(OverriddenMethods) +
7975 llvm::capacity_in_bytes(Types) +
7976 llvm::capacity_in_bytes(VariableArrayTypes) +
7977 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007978}
Ted Kremenek540017e2011-10-06 05:00:56 +00007979
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00007980/// getIntTypeForBitwidth -
7981/// sets integer QualTy according to specified details:
7982/// bitwidth, signed/unsigned.
7983/// Returns empty type if there is no appropriate target types.
7984QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
7985 unsigned Signed) const {
7986 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
7987 CanQualType QualTy = getFromTargetType(Ty);
7988 if (!QualTy && DestWidth == 128)
7989 return Signed ? Int128Ty : UnsignedInt128Ty;
7990 return QualTy;
7991}
7992
7993/// getRealTypeForBitwidth -
7994/// sets floating point QualTy according to specified bitwidth.
7995/// Returns empty type if there is no appropriate target types.
7996QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
7997 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
7998 switch (Ty) {
7999 case TargetInfo::Float:
8000 return FloatTy;
8001 case TargetInfo::Double:
8002 return DoubleTy;
8003 case TargetInfo::LongDouble:
8004 return LongDoubleTy;
8005 case TargetInfo::NoFloat:
8006 return QualType();
8007 }
8008
8009 llvm_unreachable("Unhandled TargetInfo::RealType value");
8010}
8011
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008012void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8013 if (Number > 1)
8014 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008015}
8016
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008017unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8018 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8019 MangleNumbers.find(ND);
8020 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008021}
8022
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008023MangleNumberingContext &
8024ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008025 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8026 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8027 if (!MCtx)
8028 MCtx = createMangleNumberingContext();
8029 return *MCtx;
8030}
8031
8032MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8033 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008034}
8035
Ted Kremenek540017e2011-10-06 05:00:56 +00008036void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8037 ParamIndices[D] = index;
8038}
8039
8040unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8041 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8042 assert(I != ParamIndices.end() &&
8043 "ParmIndices lacks entry set by ParmVarDecl");
8044 return I->second;
8045}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008046
Richard Smithe6c01442013-06-05 00:46:14 +00008047APValue *
8048ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8049 bool MayCreate) {
8050 assert(E && E->getStorageDuration() == SD_Static &&
8051 "don't need to cache the computed value for this temporary");
8052 if (MayCreate)
8053 return &MaterializedTemporaryValues[E];
8054
8055 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8056 MaterializedTemporaryValues.find(E);
8057 return I == MaterializedTemporaryValues.end() ? 0 : &I->second;
8058}
8059
Fariborz Jahanian615de762013-05-28 17:37:39 +00008060bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8061 const llvm::Triple &T = getTargetInfo().getTriple();
8062 if (!T.isOSDarwin())
8063 return false;
8064
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008065 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8066 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8067 return false;
8068
Fariborz Jahanian615de762013-05-28 17:37:39 +00008069 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8070 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8071 uint64_t Size = sizeChars.getQuantity();
8072 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8073 unsigned Align = alignChars.getQuantity();
8074 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8075 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8076}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008077
8078namespace {
8079
8080 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8081 /// parents as defined by the \c RecursiveASTVisitor.
8082 ///
8083 /// Note that the relationship described here is purely in terms of AST
8084 /// traversal - there are other relationships (for example declaration context)
8085 /// in the AST that are better modeled by special matchers.
8086 ///
8087 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8088 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8089
8090 public:
8091 /// \brief Builds and returns the translation unit's parent map.
8092 ///
8093 /// The caller takes ownership of the returned \c ParentMap.
8094 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8095 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8096 Visitor.TraverseDecl(&TU);
8097 return Visitor.Parents;
8098 }
8099
8100 private:
8101 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8102
8103 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8104 }
8105
8106 bool shouldVisitTemplateInstantiations() const {
8107 return true;
8108 }
8109 bool shouldVisitImplicitCode() const {
8110 return true;
8111 }
8112 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8113 // are not triggered during data recursion.
8114 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8115 return false;
8116 }
8117
8118 template <typename T>
8119 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
8120 if (Node == NULL)
8121 return true;
8122 if (ParentStack.size() > 0)
8123 // FIXME: Currently we add the same parent multiple times, for example
8124 // when we visit all subexpressions of template instantiations; this is
8125 // suboptimal, bug benign: the only way to visit those is with
8126 // hasAncestor / hasParent, and those do not create new matches.
8127 // The plan is to enable DynTypedNode to be storable in a map or hash
8128 // map. The main problem there is to implement hash functions /
8129 // comparison operators for all types that DynTypedNode supports that
8130 // do not have pointer identity.
8131 (*Parents)[Node].push_back(ParentStack.back());
8132 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8133 bool Result = (this ->* traverse) (Node);
8134 ParentStack.pop_back();
8135 return Result;
8136 }
8137
8138 bool TraverseDecl(Decl *DeclNode) {
8139 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8140 }
8141
8142 bool TraverseStmt(Stmt *StmtNode) {
8143 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8144 }
8145
8146 ASTContext::ParentMap *Parents;
8147 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8148
8149 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8150 };
8151
8152} // end namespace
8153
8154ASTContext::ParentVector
8155ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8156 assert(Node.getMemoizationData() &&
8157 "Invariant broken: only nodes that support memoization may be "
8158 "used in the parent map.");
8159 if (!AllParents) {
8160 // We always need to run over the whole translation unit, as
8161 // hasAncestor can escape any subtree.
8162 AllParents.reset(
8163 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8164 }
8165 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8166 if (I == AllParents->end()) {
8167 return ParentVector();
8168 }
8169 return I->second;
8170}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008171
8172bool
8173ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8174 const ObjCMethodDecl *MethodImpl) {
8175 // No point trying to match an unavailable/deprecated mothod.
8176 if (MethodDecl->hasAttr<UnavailableAttr>()
8177 || MethodDecl->hasAttr<DeprecatedAttr>())
8178 return false;
8179 if (MethodDecl->getObjCDeclQualifier() !=
8180 MethodImpl->getObjCDeclQualifier())
8181 return false;
8182 if (!hasSameType(MethodDecl->getResultType(),
8183 MethodImpl->getResultType()))
8184 return false;
8185
8186 if (MethodDecl->param_size() != MethodImpl->param_size())
8187 return false;
8188
8189 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8190 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8191 EF = MethodDecl->param_end();
8192 IM != EM && IF != EF; ++IM, ++IF) {
8193 const ParmVarDecl *DeclVar = (*IF);
8194 const ParmVarDecl *ImplVar = (*IM);
8195 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8196 return false;
8197 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8198 return false;
8199 }
8200 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8201
8202}