blob: ace9dc0146a4153e1bf156fd340e59587ab9100b [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"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000028#include "clang/AST/RecordLayout.h"
29#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000030#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000031#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000032#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000033#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000034#include "llvm/ADT/StringExtras.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000035#include "llvm/Support/Capacity.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000036#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000037#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000038#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000039
Chris Lattnerddc135e2006-11-10 06:34:16 +000040using namespace clang;
41
Douglas Gregor9672f922010-07-03 00:47:00 +000042unsigned ASTContext::NumImplicitDefaultConstructors;
43unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000044unsigned ASTContext::NumImplicitCopyConstructors;
45unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000046unsigned ASTContext::NumImplicitMoveConstructors;
47unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000048unsigned ASTContext::NumImplicitCopyAssignmentOperators;
49unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000050unsigned ASTContext::NumImplicitMoveAssignmentOperators;
51unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000052unsigned ASTContext::NumImplicitDestructors;
53unsigned ASTContext::NumImplicitDestructorsDeclared;
54
Steve Naroff0af91202007-04-27 21:51:21 +000055enum FloatingRank {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000056 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Steve Naroff0af91202007-04-27 21:51:21 +000057};
58
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000059RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000060 if (!CommentsLoaded && ExternalSource) {
61 ExternalSource->ReadComments();
62 CommentsLoaded = true;
63 }
64
65 assert(D);
66
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000067 // User can not attach documentation to implicit declarations.
68 if (D->isImplicit())
69 return NULL;
70
Dmitri Gribenkob2610882012-08-14 17:17:18 +000071 // User can not attach documentation to implicit instantiations.
72 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
73 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
74 return NULL;
75 }
76
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000077 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
78 if (VD->isStaticDataMember() &&
79 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
80 return NULL;
81 }
82
83 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
84 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
85 return NULL;
86 }
87
88 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
89 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
90 return NULL;
91 }
92
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000093 // TODO: handle comments for function parameters properly.
94 if (isa<ParmVarDecl>(D))
95 return NULL;
96
Dmitri Gribenko34df2202012-07-31 22:37:06 +000097 // TODO: we could look up template parameter documentation in the template
98 // documentation.
99 if (isa<TemplateTypeParmDecl>(D) ||
100 isa<NonTypeTemplateParmDecl>(D) ||
101 isa<TemplateTemplateParmDecl>(D))
102 return NULL;
103
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000104 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000105
106 // If there are no comments anywhere, we won't find anything.
107 if (RawComments.empty())
108 return NULL;
109
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000110 // Find declaration location.
111 // For Objective-C declarations we generally don't expect to have multiple
112 // declarators, thus use declaration starting location as the "declaration
113 // location".
114 // For all other declarations multiple declarators are used quite frequently,
115 // so we use the location of the identifier as the "declaration location".
116 SourceLocation DeclLoc;
117 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000118 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000119 isa<RedeclarableTemplateDecl>(D) ||
120 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000121 DeclLoc = D->getLocStart();
122 else
123 DeclLoc = D->getLocation();
124
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000125 // If the declaration doesn't map directly to a location in a file, we
126 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000127 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
128 return NULL;
129
130 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000131 ArrayRef<RawComment *>::iterator Comment;
132 {
133 // When searching for comments during parsing, the comment we are looking
134 // for is usually among the last two comments we parsed -- check them
135 // first.
136 RawComment CommentAtDeclLoc(SourceMgr, SourceRange(DeclLoc));
137 BeforeThanCompare<RawComment> Compare(SourceMgr);
138 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
139 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
140 if (!Found && RawComments.size() >= 2) {
141 MaybeBeforeDecl--;
142 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
143 }
144
145 if (Found) {
146 Comment = MaybeBeforeDecl + 1;
147 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
148 &CommentAtDeclLoc, Compare));
149 } else {
150 // Slow path.
151 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
152 &CommentAtDeclLoc, Compare);
153 }
154 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000155
156 // Decompose the location for the declaration and find the beginning of the
157 // file buffer.
158 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
159
160 // First check whether we have a trailing comment.
161 if (Comment != RawComments.end() &&
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000162 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Dmitri Gribenko44cd7e62012-07-06 23:27:33 +0000163 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000164 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000165 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000166 // Check that Doxygen trailing comment comes after the declaration, starts
167 // on the same line and in the same file as the declaration.
168 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
169 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
170 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
171 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000172 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000173 }
174 }
175
176 // The comment just after the declaration was not a trailing comment.
177 // Let's look at the previous comment.
178 if (Comment == RawComments.begin())
179 return NULL;
180 --Comment;
181
182 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000183 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000184 return NULL;
185
186 // Decompose the end of the comment.
187 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000188 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000189
190 // If the comment and the declaration aren't in the same file, then they
191 // aren't related.
192 if (DeclLocDecomp.first != CommentEndDecomp.first)
193 return NULL;
194
195 // Get the corresponding buffer.
196 bool Invalid = false;
197 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
198 &Invalid).data();
199 if (Invalid)
200 return NULL;
201
202 // Extract text between the comment and declaration.
203 StringRef Text(Buffer + CommentEndDecomp.second,
204 DeclLocDecomp.second - CommentEndDecomp.second);
205
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000206 // There should be no other declarations or preprocessor directives between
207 // comment and declaration.
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000208 if (Text.find_first_of(",;{}#@") != StringRef::npos)
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000209 return NULL;
210
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000211 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000212}
213
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000214namespace {
215/// If we have a 'templated' declaration for a template, adjust 'D' to
216/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000217/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000218const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregor35ceb272012-08-13 16:37:30 +0000219 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000220 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000221 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000222 return FTD;
223
224 // Nothing to do if function is not an implicit instantiation.
225 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
226 return D;
227
228 // Function is an implicit instantiation of a function template?
229 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
230 return FTD;
231
232 // Function is instantiated from a member definition of a class template?
233 if (const FunctionDecl *MemberDecl =
234 FD->getInstantiatedFromMemberFunction())
235 return MemberDecl;
236
237 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000238 }
Dmitri Gribenko90631802012-08-22 17:44:32 +0000239 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
240 // Static data member is instantiated from a member definition of a class
241 // template?
242 if (VD->isStaticDataMember())
243 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
244 return MemberDecl;
245
246 return D;
247 }
248 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
249 // Is this class declaration part of a class template?
250 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
251 return CTD;
252
253 // Class is an implicit instantiation of a class template or partial
254 // specialization?
255 if (const ClassTemplateSpecializationDecl *CTSD =
256 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
257 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
258 return D;
259 llvm::PointerUnion<ClassTemplateDecl *,
260 ClassTemplatePartialSpecializationDecl *>
261 PU = CTSD->getSpecializedTemplateOrPartial();
262 return PU.is<ClassTemplateDecl*>() ?
263 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
264 static_cast<const Decl*>(
265 PU.get<ClassTemplatePartialSpecializationDecl *>());
266 }
267
268 // Class is instantiated from a member definition of a class template?
269 if (const MemberSpecializationInfo *Info =
270 CRD->getMemberSpecializationInfo())
271 return Info->getInstantiatedFrom();
272
273 return D;
274 }
275 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
276 // Enum is instantiated from a member definition of a class template?
277 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
278 return MemberDecl;
279
280 return D;
281 }
282 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000283 return D;
284}
285} // unnamed namespace
286
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000287const RawComment *ASTContext::getRawCommentForAnyRedecl(
288 const Decl *D,
289 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000290 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000291
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000292 // Check whether we have cached a comment for this declaration already.
293 {
294 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
295 RedeclComments.find(D);
296 if (Pos != RedeclComments.end()) {
297 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000298 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
299 if (OriginalDecl)
300 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000301 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000302 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000303 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000304 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000305
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000306 // Search for comments attached to declarations in the redeclaration chain.
307 const RawComment *RC = NULL;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000308 const Decl *OriginalDeclForRC = NULL;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000309 for (Decl::redecl_iterator I = D->redecls_begin(),
310 E = D->redecls_end();
311 I != E; ++I) {
312 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
313 RedeclComments.find(*I);
314 if (Pos != RedeclComments.end()) {
315 const RawCommentAndCacheFlags &Raw = Pos->second;
316 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
317 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000318 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000319 break;
320 }
321 } else {
322 RC = getRawCommentForDeclNoCache(*I);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000323 OriginalDeclForRC = *I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000324 RawCommentAndCacheFlags Raw;
325 if (RC) {
326 Raw.setRaw(RC);
327 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
328 } else
329 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000330 Raw.setOriginalDecl(*I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000331 RedeclComments[*I] = Raw;
332 if (RC)
333 break;
334 }
335 }
336
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000337 // If we found a comment, it should be a documentation comment.
338 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000339
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000340 if (OriginalDecl)
341 *OriginalDecl = OriginalDeclForRC;
342
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000343 // Update cache for every declaration in the redeclaration chain.
344 RawCommentAndCacheFlags Raw;
345 Raw.setRaw(RC);
346 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000347 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000348
349 for (Decl::redecl_iterator I = D->redecls_begin(),
350 E = D->redecls_end();
351 I != E; ++I) {
352 RawCommentAndCacheFlags &R = RedeclComments[*I];
353 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
354 R = Raw;
355 }
356
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000357 return RC;
358}
359
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000360static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
361 SmallVectorImpl<const NamedDecl *> &Redeclared) {
362 const DeclContext *DC = ObjCMethod->getDeclContext();
363 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
364 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
365 if (!ID)
366 return;
367 // Add redeclared method here.
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000368 for (ObjCInterfaceDecl::known_extensions_iterator
369 Ext = ID->known_extensions_begin(),
370 ExtEnd = ID->known_extensions_end();
371 Ext != ExtEnd; ++Ext) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000372 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000373 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000374 ObjCMethod->isInstanceMethod()))
375 Redeclared.push_back(RedeclaredMethod);
376 }
377 }
378}
379
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000380comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
381 const Decl *D) const {
382 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
383 ThisDeclInfo->CommentDecl = D;
384 ThisDeclInfo->IsFilled = false;
385 ThisDeclInfo->fill();
386 ThisDeclInfo->CommentDecl = FC->getDecl();
387 comments::FullComment *CFC =
388 new (*this) comments::FullComment(FC->getBlocks(),
389 ThisDeclInfo);
390 return CFC;
391
392}
393
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000394comments::FullComment *ASTContext::getCommentForDecl(
395 const Decl *D,
396 const Preprocessor *PP) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000397 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000398
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000399 const Decl *Canonical = D->getCanonicalDecl();
400 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
401 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000402
403 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000404 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000405 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000406 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000407 return CFC;
408 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000409 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000410 }
411
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000412 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000413
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000414 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000415 if (!RC) {
416 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000417 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000418 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
419 if (OMD && OMD->isPropertyAccessor()) {
420 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl()) {
421 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP)) {
422 comments::FullComment *CFC = cloneFullComment(FC, D);
423 return CFC;
424 }
425 }
426 }
427 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000428 addRedeclaredMethods(OMD, Overridden);
429 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
430 for (unsigned i = 0, e = Overridden.size(); i < e; i++) {
431 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP)) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000432 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000433 return CFC;
434 }
435 }
436 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000437 return NULL;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000438 }
439
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000440 // If the RawComment was attached to other redeclaration of this Decl, we
441 // should parse the comment in context of that other Decl. This is important
442 // because comments can contain references to parameter names which can be
443 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000444 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000445 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000446
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000447 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000448 ParsedComments[Canonical] = FC;
449 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000450}
451
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000452void
453ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
454 TemplateTemplateParmDecl *Parm) {
455 ID.AddInteger(Parm->getDepth());
456 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000457 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000458
459 TemplateParameterList *Params = Parm->getTemplateParameters();
460 ID.AddInteger(Params->size());
461 for (TemplateParameterList::const_iterator P = Params->begin(),
462 PEnd = Params->end();
463 P != PEnd; ++P) {
464 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
465 ID.AddInteger(0);
466 ID.AddBoolean(TTP->isParameterPack());
467 continue;
468 }
469
470 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
471 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000472 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000473 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000474 if (NTTP->isExpandedParameterPack()) {
475 ID.AddBoolean(true);
476 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000477 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
478 QualType T = NTTP->getExpansionType(I);
479 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
480 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000481 } else
482 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000483 continue;
484 }
485
486 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
487 ID.AddInteger(2);
488 Profile(ID, TTP);
489 }
490}
491
492TemplateTemplateParmDecl *
493ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000494 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000495 // Check if we already have a canonical template template parameter.
496 llvm::FoldingSetNodeID ID;
497 CanonicalTemplateTemplateParm::Profile(ID, TTP);
498 void *InsertPos = 0;
499 CanonicalTemplateTemplateParm *Canonical
500 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
501 if (Canonical)
502 return Canonical->getParam();
503
504 // Build a canonical template parameter list.
505 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000506 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000507 CanonParams.reserve(Params->size());
508 for (TemplateParameterList::const_iterator P = Params->begin(),
509 PEnd = Params->end();
510 P != PEnd; ++P) {
511 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
512 CanonParams.push_back(
513 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000514 SourceLocation(),
515 SourceLocation(),
516 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000517 TTP->getIndex(), 0, false,
518 TTP->isParameterPack()));
519 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000520 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
521 QualType T = getCanonicalType(NTTP->getType());
522 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
523 NonTypeTemplateParmDecl *Param;
524 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000525 SmallVector<QualType, 2> ExpandedTypes;
526 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000527 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
528 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
529 ExpandedTInfos.push_back(
530 getTrivialTypeSourceInfo(ExpandedTypes.back()));
531 }
532
533 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000534 SourceLocation(),
535 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000536 NTTP->getDepth(),
537 NTTP->getPosition(), 0,
538 T,
539 TInfo,
540 ExpandedTypes.data(),
541 ExpandedTypes.size(),
542 ExpandedTInfos.data());
543 } else {
544 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000545 SourceLocation(),
546 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000547 NTTP->getDepth(),
548 NTTP->getPosition(), 0,
549 T,
550 NTTP->isParameterPack(),
551 TInfo);
552 }
553 CanonParams.push_back(Param);
554
555 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000556 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
557 cast<TemplateTemplateParmDecl>(*P)));
558 }
559
560 TemplateTemplateParmDecl *CanonTTP
561 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
562 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000563 TTP->getPosition(),
564 TTP->isParameterPack(),
565 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000566 TemplateParameterList::Create(*this, SourceLocation(),
567 SourceLocation(),
568 CanonParams.data(),
569 CanonParams.size(),
570 SourceLocation()));
571
572 // Get the new insert position for the node we care about.
573 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
574 assert(Canonical == 0 && "Shouldn't be in the map!");
575 (void)Canonical;
576
577 // Create the canonical template template parameter entry.
578 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
579 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
580 return CanonTTP;
581}
582
Charles Davis53c59df2010-08-16 03:33:14 +0000583CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000584 if (!LangOpts.CPlusPlus) return 0;
585
Charles Davis6bcb07a2010-08-19 02:18:14 +0000586 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000587 case CXXABI_ARM:
588 return CreateARMCXXABI(*this);
589 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000590 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000591 case CXXABI_Microsoft:
592 return CreateMicrosoftCXXABI(*this);
593 }
David Blaikie8a40f702012-01-17 06:56:22 +0000594 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000595}
596
Douglas Gregore8bbc122011-09-02 00:18:52 +0000597static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000598 const LangOptions &LOpts) {
599 if (LOpts.FakeAddressSpaceMap) {
600 // The fake address space map must have a distinct entry for each
601 // language-specific address space.
602 static const unsigned FakeAddrSpaceMap[] = {
603 1, // opencl_global
604 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000605 3, // opencl_constant
606 4, // cuda_device
607 5, // cuda_constant
608 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000609 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000610 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000611 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000612 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000613 }
614}
615
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000616ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000617 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000618 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000619 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000620 unsigned size_reserve,
621 bool DelayInitialization)
622 : FunctionProtoTypes(this_()),
623 TemplateSpecializationTypes(this_()),
624 DependentTemplateSpecializationTypes(this_()),
625 SubstTemplateTemplateParmPacks(this_()),
626 GlobalNestedNameSpecifier(0),
627 Int128Decl(0), UInt128Decl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000628 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000629 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanianf2578572012-08-30 18:49:41 +0000630 BOOLDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000631 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000632 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000633 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
634 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
635 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000636 NullTypeSourceInfo(QualType()),
637 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000638 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000639 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000640 Idents(idents), Selectors(sels),
641 BuiltinInfo(builtins),
642 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000643 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000644 Comments(SM), CommentsLoaded(false),
Dmitri Gribenko7acbf002012-09-10 20:32:42 +0000645 CommentCommandTraits(BumpAlloc),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000646 LastSDM(0, 0),
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +0000647 UniqueBlockByRefTypeID(0)
Douglas Gregore8bbc122011-09-02 00:18:52 +0000648{
Mike Stump11289f42009-09-09 15:08:12 +0000649 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000650 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000651
652 if (!DelayInitialization) {
653 assert(t && "No target supplied for ASTContext initialization");
654 InitBuiltinTypes(*t);
655 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000656}
657
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000658ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000659 // Release the DenseMaps associated with DeclContext objects.
660 // FIXME: Is this the ideal solution?
661 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000662
Douglas Gregor5b11d492010-07-25 17:53:33 +0000663 // Call all of the deallocation functions.
664 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
665 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000666
Ted Kremenek076baeb2010-06-08 23:00:58 +0000667 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000668 // because they can contain DenseMaps.
669 for (llvm::DenseMap<const ObjCContainerDecl*,
670 const ASTRecordLayout*>::iterator
671 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
672 // Increment in loop to prevent using deallocated memory.
673 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
674 R->Destroy(*this);
675
Ted Kremenek076baeb2010-06-08 23:00:58 +0000676 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
677 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
678 // Increment in loop to prevent using deallocated memory.
679 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
680 R->Destroy(*this);
681 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000682
683 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
684 AEnd = DeclAttrs.end();
685 A != AEnd; ++A)
686 A->second->~AttrVec();
687}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000688
Douglas Gregor1a809332010-05-23 18:26:36 +0000689void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
690 Deallocations.push_back(std::make_pair(Callback, Data));
691}
692
Mike Stump11289f42009-09-09 15:08:12 +0000693void
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000694ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000695 ExternalSource.reset(Source.take());
696}
697
Chris Lattner4eb445d2007-01-26 01:27:23 +0000698void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000699 llvm::errs() << "\n*** AST Context Stats:\n";
700 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000701
Douglas Gregora30d0462009-05-26 14:40:08 +0000702 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000703#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000704#define ABSTRACT_TYPE(Name, Parent)
705#include "clang/AST/TypeNodes.def"
706 0 // Extra
707 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000708
Chris Lattner4eb445d2007-01-26 01:27:23 +0000709 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
710 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000711 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000712 }
713
Douglas Gregora30d0462009-05-26 14:40:08 +0000714 unsigned Idx = 0;
715 unsigned TotalBytes = 0;
716#define TYPE(Name, Parent) \
717 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000718 llvm::errs() << " " << counts[Idx] << " " << #Name \
719 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000720 TotalBytes += counts[Idx] * sizeof(Name##Type); \
721 ++Idx;
722#define ABSTRACT_TYPE(Name, Parent)
723#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000724
Chandler Carruth3c147a72011-07-04 05:32:14 +0000725 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
726
Douglas Gregor7454c562010-07-02 20:37:36 +0000727 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000728 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
729 << NumImplicitDefaultConstructors
730 << " implicit default constructors created\n";
731 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
732 << NumImplicitCopyConstructors
733 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000734 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000735 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
736 << NumImplicitMoveConstructors
737 << " implicit move constructors created\n";
738 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
739 << NumImplicitCopyAssignmentOperators
740 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000741 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000742 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
743 << NumImplicitMoveAssignmentOperators
744 << " implicit move assignment operators created\n";
745 llvm::errs() << NumImplicitDestructorsDeclared << "/"
746 << NumImplicitDestructors
747 << " implicit destructors created\n";
748
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000749 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000750 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000751 ExternalSource->PrintStats();
752 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000753
Douglas Gregor5b11d492010-07-25 17:53:33 +0000754 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000755}
756
Douglas Gregor801c99d2011-08-12 06:49:56 +0000757TypedefDecl *ASTContext::getInt128Decl() const {
758 if (!Int128Decl) {
759 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
760 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
761 getTranslationUnitDecl(),
762 SourceLocation(),
763 SourceLocation(),
764 &Idents.get("__int128_t"),
765 TInfo);
766 }
767
768 return Int128Decl;
769}
770
771TypedefDecl *ASTContext::getUInt128Decl() const {
772 if (!UInt128Decl) {
773 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
774 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
775 getTranslationUnitDecl(),
776 SourceLocation(),
777 SourceLocation(),
778 &Idents.get("__uint128_t"),
779 TInfo);
780 }
781
782 return UInt128Decl;
783}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000784
John McCall48f2d582009-10-23 23:03:21 +0000785void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000786 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000787 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000788 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000789}
790
Douglas Gregore8bbc122011-09-02 00:18:52 +0000791void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
792 assert((!this->Target || this->Target == &Target) &&
793 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000794 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000795
Douglas Gregore8bbc122011-09-02 00:18:52 +0000796 this->Target = &Target;
797
798 ABI.reset(createCXXABI(Target));
799 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
800
Chris Lattner970e54e2006-11-12 00:37:36 +0000801 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000802 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000803
Chris Lattner970e54e2006-11-12 00:37:36 +0000804 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000805 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000806 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000807 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000808 InitBuiltinType(CharTy, BuiltinType::Char_S);
809 else
810 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000811 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000812 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
813 InitBuiltinType(ShortTy, BuiltinType::Short);
814 InitBuiltinType(IntTy, BuiltinType::Int);
815 InitBuiltinType(LongTy, BuiltinType::Long);
816 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000817
Chris Lattner970e54e2006-11-12 00:37:36 +0000818 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000819 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
820 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
821 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
822 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
823 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000824
Chris Lattner970e54e2006-11-12 00:37:36 +0000825 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000826 InitBuiltinType(FloatTy, BuiltinType::Float);
827 InitBuiltinType(DoubleTy, BuiltinType::Double);
828 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000829
Chris Lattnerf122cef2009-04-30 02:43:43 +0000830 // GNU extension, 128-bit integers.
831 InitBuiltinType(Int128Ty, BuiltinType::Int128);
832 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
833
Abramo Bagnara06782942012-09-09 10:13:32 +0000834 if (LangOpts.CPlusPlus && LangOpts.WChar) { // C++ 3.9.1p5
Eli Friedman786d0872011-04-30 19:24:24 +0000835 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000836 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
837 else // -fshort-wchar makes wchar_t be unsigned.
838 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
Abramo Bagnara06782942012-09-09 10:13:32 +0000839 } else // C99 (or C++ using -fno-wchar)
Chris Lattner007cb022009-02-26 23:43:47 +0000840 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000841
James Molloy36365542012-05-04 10:55:22 +0000842 WIntTy = getFromTargetType(Target.getWIntType());
843
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000844 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
845 InitBuiltinType(Char16Ty, BuiltinType::Char16);
846 else // C99
847 Char16Ty = getFromTargetType(Target.getChar16Type());
848
849 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
850 InitBuiltinType(Char32Ty, BuiltinType::Char32);
851 else // C99
852 Char32Ty = getFromTargetType(Target.getChar32Type());
853
Douglas Gregor4619e432008-12-05 23:32:09 +0000854 // Placeholder type for type-dependent expressions whose type is
855 // completely unknown. No code should ever check a type against
856 // DependentTy and users should never see it; however, it is here to
857 // help diagnose failures to properly check for type-dependent
858 // expressions.
859 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000860
John McCall36e7fe32010-10-12 00:20:44 +0000861 // Placeholder type for functions.
862 InitBuiltinType(OverloadTy, BuiltinType::Overload);
863
John McCall0009fcc2011-04-26 20:42:42 +0000864 // Placeholder type for bound members.
865 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
866
John McCall526ab472011-10-25 17:37:35 +0000867 // Placeholder type for pseudo-objects.
868 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
869
John McCall31996342011-04-07 08:22:57 +0000870 // "any" type; useful for debugger-like clients.
871 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
872
John McCall8a6b59a2011-10-17 18:09:15 +0000873 // Placeholder type for unbridged ARC casts.
874 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
875
Eli Friedman34866c72012-08-31 00:14:07 +0000876 // Placeholder type for builtin functions.
877 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
878
Chris Lattner970e54e2006-11-12 00:37:36 +0000879 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000880 FloatComplexTy = getComplexType(FloatTy);
881 DoubleComplexTy = getComplexType(DoubleTy);
882 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000883
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000884 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000885 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
886 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000887 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000888
889 if (LangOpts.OpenCL) {
890 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
891 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
892 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
893 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
894 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
895 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
896 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000897
898 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +0000899 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
900 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000901
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000902 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +0000903
904 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000905
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000906 // void * type
907 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000908
909 // nullptr type (C++0x 2.14.7)
910 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000911
912 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
913 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +0000914
915 // Builtin type used to help define __builtin_va_list.
916 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +0000917}
918
David Blaikie9c902b52011-09-25 23:23:43 +0000919DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000920 return SourceMgr.getDiagnostics();
921}
922
Douglas Gregor561eceb2010-08-30 16:49:28 +0000923AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
924 AttrVec *&Result = DeclAttrs[D];
925 if (!Result) {
926 void *Mem = Allocate(sizeof(AttrVec));
927 Result = new (Mem) AttrVec;
928 }
929
930 return *Result;
931}
932
933/// \brief Erase the attributes corresponding to the given declaration.
934void ASTContext::eraseDeclAttrs(const Decl *D) {
935 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
936 if (Pos != DeclAttrs.end()) {
937 Pos->second->~AttrVec();
938 DeclAttrs.erase(Pos);
939 }
940}
941
Douglas Gregor86d142a2009-10-08 07:24:58 +0000942MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000943ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000944 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000945 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000946 = InstantiatedFromStaticDataMember.find(Var);
947 if (Pos == InstantiatedFromStaticDataMember.end())
948 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000949
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000950 return Pos->second;
951}
952
Mike Stump11289f42009-09-09 15:08:12 +0000953void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000954ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000955 TemplateSpecializationKind TSK,
956 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000957 assert(Inst->isStaticDataMember() && "Not a static data member");
958 assert(Tmpl->isStaticDataMember() && "Not a static data member");
959 assert(!InstantiatedFromStaticDataMember[Inst] &&
960 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000961 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000962 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000963}
964
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000965FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
966 const FunctionDecl *FD){
967 assert(FD && "Specialization is 0");
968 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +0000969 = ClassScopeSpecializationPattern.find(FD);
970 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000971 return 0;
972
973 return Pos->second;
974}
975
976void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
977 FunctionDecl *Pattern) {
978 assert(FD && "Specialization is 0");
979 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +0000980 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000981}
982
John McCalle61f2ba2009-11-18 02:36:19 +0000983NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000984ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000985 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000986 = InstantiatedFromUsingDecl.find(UUD);
987 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000988 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000989
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000990 return Pos->second;
991}
992
993void
John McCallb96ec562009-12-04 22:46:56 +0000994ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
995 assert((isa<UsingDecl>(Pattern) ||
996 isa<UnresolvedUsingValueDecl>(Pattern) ||
997 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
998 "pattern decl is not a using decl");
999 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1000 InstantiatedFromUsingDecl[Inst] = Pattern;
1001}
1002
1003UsingShadowDecl *
1004ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1005 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1006 = InstantiatedFromUsingShadowDecl.find(Inst);
1007 if (Pos == InstantiatedFromUsingShadowDecl.end())
1008 return 0;
1009
1010 return Pos->second;
1011}
1012
1013void
1014ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1015 UsingShadowDecl *Pattern) {
1016 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1017 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001018}
1019
Anders Carlsson5da84842009-09-01 04:26:58 +00001020FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1021 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1022 = InstantiatedFromUnnamedFieldDecl.find(Field);
1023 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1024 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001025
Anders Carlsson5da84842009-09-01 04:26:58 +00001026 return Pos->second;
1027}
1028
1029void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1030 FieldDecl *Tmpl) {
1031 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1032 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1033 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1034 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001035
Anders Carlsson5da84842009-09-01 04:26:58 +00001036 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1037}
1038
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +00001039bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
1040 const FieldDecl *LastFD) const {
1041 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001042 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +00001043}
1044
Fariborz Jahanianeb397412011-05-02 17:20:56 +00001045bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
1046 const FieldDecl *LastFD) const {
1047 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001048 FD->getBitWidthValue(*this) == 0 &&
1049 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +00001050}
1051
Fariborz Jahanian84335f72011-05-04 18:51:37 +00001052bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
1053 const FieldDecl *LastFD) const {
1054 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001055 FD->getBitWidthValue(*this) &&
1056 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +00001057}
1058
Chad Rosierf01a7dd2011-08-04 23:34:15 +00001059bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001060 const FieldDecl *LastFD) const {
1061 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001062 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001063}
1064
Chad Rosierf01a7dd2011-08-04 23:34:15 +00001065bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001066 const FieldDecl *LastFD) const {
1067 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001068 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001069}
1070
Douglas Gregor832940b2010-03-02 23:58:15 +00001071ASTContext::overridden_cxx_method_iterator
1072ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1073 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001074 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001075 if (Pos == OverriddenMethods.end())
1076 return 0;
1077
1078 return Pos->second.begin();
1079}
1080
1081ASTContext::overridden_cxx_method_iterator
1082ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1083 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001084 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001085 if (Pos == OverriddenMethods.end())
1086 return 0;
1087
1088 return Pos->second.end();
1089}
1090
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001091unsigned
1092ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1093 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001094 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001095 if (Pos == OverriddenMethods.end())
1096 return 0;
1097
1098 return Pos->second.size();
1099}
1100
Douglas Gregor832940b2010-03-02 23:58:15 +00001101void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1102 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001103 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001104 OverriddenMethods[Method].push_back(Overridden);
1105}
1106
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001107void ASTContext::getOverriddenMethods(
1108 const NamedDecl *D,
1109 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001110 assert(D);
1111
1112 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001113 Overridden.append(CXXMethod->begin_overridden_methods(),
1114 CXXMethod->end_overridden_methods());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001115 return;
1116 }
1117
1118 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1119 if (!Method)
1120 return;
1121
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001122 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1123 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001124 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001125}
1126
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001127void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1128 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1129 assert(!Import->isFromASTFile() && "Non-local import declaration");
1130 if (!FirstLocalImport) {
1131 FirstLocalImport = Import;
1132 LastLocalImport = Import;
1133 return;
1134 }
1135
1136 LastLocalImport->NextLocalImport = Import;
1137 LastLocalImport = Import;
1138}
1139
Chris Lattner53cfe802007-07-18 17:52:12 +00001140//===----------------------------------------------------------------------===//
1141// Type Sizing and Analysis
1142//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001143
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001144/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1145/// scalar floating point type.
1146const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001147 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001148 assert(BT && "Not a floating point type!");
1149 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001150 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001151 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001152 case BuiltinType::Float: return Target->getFloatFormat();
1153 case BuiltinType::Double: return Target->getDoubleFormat();
1154 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001155 }
1156}
1157
Ken Dyck160146e2010-01-27 17:10:57 +00001158/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +00001159/// specified decl. Note that bitfields do not have a valid alignment, so
1160/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001161/// If @p RefAsPointee, references are treated like their underlying type
1162/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +00001163CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001164 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001165
John McCall94268702010-10-08 18:24:19 +00001166 bool UseAlignAttrOnly = false;
1167 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1168 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001169
John McCall94268702010-10-08 18:24:19 +00001170 // __attribute__((aligned)) can increase or decrease alignment
1171 // *except* on a struct or struct member, where it only increases
1172 // alignment unless 'packed' is also specified.
1173 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001174 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001175 // ignore that possibility; Sema should diagnose it.
1176 if (isa<FieldDecl>(D)) {
1177 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1178 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1179 } else {
1180 UseAlignAttrOnly = true;
1181 }
1182 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001183 else if (isa<FieldDecl>(D))
1184 UseAlignAttrOnly =
1185 D->hasAttr<PackedAttr>() ||
1186 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001187
John McCall4e819612011-01-20 07:57:12 +00001188 // If we're using the align attribute only, just ignore everything
1189 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001190 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001191 // do nothing
1192
John McCall94268702010-10-08 18:24:19 +00001193 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001194 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001195 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001196 if (RefAsPointee)
1197 T = RT->getPointeeType();
1198 else
1199 T = getPointerType(RT->getPointeeType());
1200 }
1201 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001202 // Adjust alignments of declarations with array type by the
1203 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +00001204 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +00001205 const ArrayType *arrayType;
1206 if (MinWidth && (arrayType = getAsArrayType(T))) {
1207 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001208 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +00001209 else if (isa<ConstantArrayType>(arrayType) &&
1210 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001211 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +00001212
John McCall33ddac02011-01-19 10:06:00 +00001213 // Walk through any array types while we're at it.
1214 T = getBaseElementType(arrayType);
1215 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001216 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +00001217 }
John McCall4e819612011-01-20 07:57:12 +00001218
1219 // Fields can be subject to extra alignment constraints, like if
1220 // the field is packed, the struct is packed, or the struct has a
1221 // a max-field-alignment constraint (#pragma pack). So calculate
1222 // the actual alignment of the field within the struct, and then
1223 // (as we're expected to) constrain that by the alignment of the type.
1224 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
1225 // So calculate the alignment of the field.
1226 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
1227
1228 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +00001229 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001230
1231 // Use the GCD of that and the offset within the record.
1232 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
1233 if (offset > 0) {
1234 // Alignment is always a power of 2, so the GCD will be a power of 2,
1235 // which means we get to do this crazy thing instead of Euclid's.
1236 uint64_t lowBitOfOffset = offset & (~offset + 1);
1237 if (lowBitOfOffset < fieldAlign)
1238 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
1239 }
1240
1241 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +00001242 }
Chris Lattner68061312009-01-24 21:53:27 +00001243 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001244
Ken Dyckcc56c542011-01-15 18:38:59 +00001245 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001246}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001247
John McCallf1249922012-08-21 04:10:00 +00001248// getTypeInfoDataSizeInChars - Return the size of a type, in
1249// chars. If the type is a record, its data size is returned. This is
1250// the size of the memcpy that's performed when assigning this type
1251// using a trivial copy/move assignment operator.
1252std::pair<CharUnits, CharUnits>
1253ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1254 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1255
1256 // In C++, objects can sometimes be allocated into the tail padding
1257 // of a base-class subobject. We decide whether that's possible
1258 // during class layout, so here we can just trust the layout results.
1259 if (getLangOpts().CPlusPlus) {
1260 if (const RecordType *RT = T->getAs<RecordType>()) {
1261 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1262 sizeAndAlign.first = layout.getDataSize();
1263 }
1264 }
1265
1266 return sizeAndAlign;
1267}
1268
John McCall87fe5d52010-05-20 01:18:31 +00001269std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001270ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001271 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +00001272 return std::make_pair(toCharUnitsFromBits(Info.first),
1273 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +00001274}
1275
1276std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001277ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001278 return getTypeInfoInChars(T.getTypePtr());
1279}
1280
Daniel Dunbarc6475872012-03-09 04:12:54 +00001281std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1282 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1283 if (it != MemoizedTypeInfo.end())
1284 return it->second;
1285
1286 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1287 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1288 return Info;
1289}
1290
1291/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1292/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001293///
1294/// FIXME: Pointers into different addr spaces could have different sizes and
1295/// alignment requirements: getPointerInfo should take an AddrSpace, this
1296/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +00001297std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +00001298ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +00001299 uint64_t Width=0;
1300 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001301 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001302#define TYPE(Class, Base)
1303#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001304#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001305#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1306#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001307 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001308
Chris Lattner355332d2007-07-13 22:27:08 +00001309 case Type::FunctionNoProto:
1310 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001311 // GCC extension: alignof(function) = 32 bits
1312 Width = 0;
1313 Align = 32;
1314 break;
1315
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001316 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001317 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001318 Width = 0;
1319 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1320 break;
1321
Steve Naroff5c131802007-08-30 01:06:46 +00001322 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001323 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001324
Chris Lattner37e05872008-03-05 18:54:05 +00001325 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001326 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +00001327 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1328 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001329 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001330 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +00001331 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001332 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001333 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001334 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001335 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001336 const VectorType *VT = cast<VectorType>(T);
1337 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1338 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001339 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001340 // If the alignment is not a power of 2, round up to the next power of 2.
1341 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001342 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001343 Align = llvm::NextPowerOf2(Align);
1344 Width = llvm::RoundUpToAlignment(Width, Align);
1345 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001346 // Adjust the alignment based on the target max.
1347 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1348 if (TargetVectorAlign && TargetVectorAlign < Align)
1349 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001350 break;
1351 }
Chris Lattner647fb222007-07-18 18:26:58 +00001352
Chris Lattner7570e9c2008-03-08 08:52:55 +00001353 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001354 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001355 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001356 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001357 // GCC extension: alignof(void) = 8 bits.
1358 Width = 0;
1359 Align = 8;
1360 break;
1361
Chris Lattner6a4f7452007-12-19 19:23:28 +00001362 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001363 Width = Target->getBoolWidth();
1364 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001365 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001366 case BuiltinType::Char_S:
1367 case BuiltinType::Char_U:
1368 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001369 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001370 Width = Target->getCharWidth();
1371 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001372 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001373 case BuiltinType::WChar_S:
1374 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001375 Width = Target->getWCharWidth();
1376 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001377 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001378 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001379 Width = Target->getChar16Width();
1380 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001381 break;
1382 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001383 Width = Target->getChar32Width();
1384 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001385 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001386 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001387 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001388 Width = Target->getShortWidth();
1389 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001390 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001391 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001392 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001393 Width = Target->getIntWidth();
1394 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001395 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001396 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001397 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001398 Width = Target->getLongWidth();
1399 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001400 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001401 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001402 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001403 Width = Target->getLongLongWidth();
1404 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001405 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001406 case BuiltinType::Int128:
1407 case BuiltinType::UInt128:
1408 Width = 128;
1409 Align = 128; // int128_t is 128-bit aligned on all targets.
1410 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001411 case BuiltinType::Half:
1412 Width = Target->getHalfWidth();
1413 Align = Target->getHalfAlign();
1414 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001415 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001416 Width = Target->getFloatWidth();
1417 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001418 break;
1419 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001420 Width = Target->getDoubleWidth();
1421 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001422 break;
1423 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001424 Width = Target->getLongDoubleWidth();
1425 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001426 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001427 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001428 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1429 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001430 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001431 case BuiltinType::ObjCId:
1432 case BuiltinType::ObjCClass:
1433 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001434 Width = Target->getPointerWidth(0);
1435 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001436 break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001437 case BuiltinType::OCLImage1d:
1438 case BuiltinType::OCLImage1dArray:
1439 case BuiltinType::OCLImage1dBuffer:
1440 case BuiltinType::OCLImage2d:
1441 case BuiltinType::OCLImage2dArray:
1442 case BuiltinType::OCLImage3d:
1443 // Currently these types are pointers to opaque types.
1444 Width = Target->getPointerWidth(0);
1445 Align = Target->getPointerAlign(0);
1446 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001447 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001448 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001449 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001450 Width = Target->getPointerWidth(0);
1451 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001452 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001453 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001454 unsigned AS = getTargetAddressSpace(
1455 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001456 Width = Target->getPointerWidth(AS);
1457 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001458 break;
1459 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001460 case Type::LValueReference:
1461 case Type::RValueReference: {
1462 // alignof and sizeof should never enter this code path here, so we go
1463 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001464 unsigned AS = getTargetAddressSpace(
1465 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001466 Width = Target->getPointerWidth(AS);
1467 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001468 break;
1469 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001470 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001471 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001472 Width = Target->getPointerWidth(AS);
1473 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001474 break;
1475 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001476 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001477 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001478 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +00001479 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +00001480 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001481 Align = PtrDiffInfo.second;
1482 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001483 }
Chris Lattner647fb222007-07-18 18:26:58 +00001484 case Type::Complex: {
1485 // Complex types have the same alignment as their elements, but twice the
1486 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001487 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001488 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001489 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001490 Align = EltInfo.second;
1491 break;
1492 }
John McCall8b07ec22010-05-15 11:32:37 +00001493 case Type::ObjCObject:
1494 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001495 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001496 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001497 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001498 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001499 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001500 break;
1501 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001502 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001503 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001504 const TagType *TT = cast<TagType>(T);
1505
1506 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001507 Width = 8;
1508 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001509 break;
1510 }
Mike Stump11289f42009-09-09 15:08:12 +00001511
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001512 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001513 return getTypeInfo(ET->getDecl()->getIntegerType());
1514
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001515 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001516 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001517 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001518 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001519 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001520 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001521
Chris Lattner63d2b362009-10-22 05:17:15 +00001522 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001523 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1524 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001525
Richard Smith30482bc2011-02-20 03:19:35 +00001526 case Type::Auto: {
1527 const AutoType *A = cast<AutoType>(T);
1528 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001529 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001530 }
1531
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001532 case Type::Paren:
1533 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1534
Douglas Gregoref462e62009-04-30 17:32:17 +00001535 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001536 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001537 std::pair<uint64_t, unsigned> Info
1538 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001539 // If the typedef has an aligned attribute on it, it overrides any computed
1540 // alignment we have. This violates the GCC documentation (which says that
1541 // attribute(aligned) can only round up) but matches its implementation.
1542 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1543 Align = AttrAlign;
1544 else
1545 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001546 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001547 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001548 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001549
1550 case Type::TypeOfExpr:
1551 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1552 .getTypePtr());
1553
1554 case Type::TypeOf:
1555 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1556
Anders Carlsson81df7b82009-06-24 19:06:50 +00001557 case Type::Decltype:
1558 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1559 .getTypePtr());
1560
Alexis Hunte852b102011-05-24 22:41:36 +00001561 case Type::UnaryTransform:
1562 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1563
Abramo Bagnara6150c882010-05-11 21:36:43 +00001564 case Type::Elaborated:
1565 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001566
John McCall81904512011-01-06 01:58:22 +00001567 case Type::Attributed:
1568 return getTypeInfo(
1569 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1570
Richard Smith3f1b5d02011-05-05 21:57:07 +00001571 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001572 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001573 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001574 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1575 // A type alias template specialization may refer to a typedef with the
1576 // aligned attribute on it.
1577 if (TST->isTypeAlias())
1578 return getTypeInfo(TST->getAliasedType().getTypePtr());
1579 else
1580 return getTypeInfo(getCanonicalType(T));
1581 }
1582
Eli Friedman0dfb8892011-10-06 23:00:33 +00001583 case Type::Atomic: {
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001584 std::pair<uint64_t, unsigned> Info
1585 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1586 Width = Info.first;
1587 Align = Info.second;
1588 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1589 llvm::isPowerOf2_64(Width)) {
1590 // We can potentially perform lock-free atomic operations for this
1591 // type; promote the alignment appropriately.
1592 // FIXME: We could potentially promote the width here as well...
1593 // is that worthwhile? (Non-struct atomic types generally have
1594 // power-of-two size anyway, but structs might not. Requires a bit
1595 // of implementation work to make sure we zero out the extra bits.)
1596 Align = static_cast<unsigned>(Width);
1597 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001598 }
1599
Douglas Gregoref462e62009-04-30 17:32:17 +00001600 }
Mike Stump11289f42009-09-09 15:08:12 +00001601
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001602 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001603 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001604}
1605
Ken Dyckcc56c542011-01-15 18:38:59 +00001606/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1607CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1608 return CharUnits::fromQuantity(BitSize / getCharWidth());
1609}
1610
Ken Dyckb0fcc592011-02-11 01:54:29 +00001611/// toBits - Convert a size in characters to a size in characters.
1612int64_t ASTContext::toBits(CharUnits CharSize) const {
1613 return CharSize.getQuantity() * getCharWidth();
1614}
1615
Ken Dyck8c89d592009-12-22 14:23:30 +00001616/// getTypeSizeInChars - Return the size of the specified type, in characters.
1617/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001618CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001619 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001620}
Jay Foad39c79802011-01-12 09:06:06 +00001621CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001622 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001623}
1624
Ken Dycka6046ab2010-01-26 17:25:18 +00001625/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001626/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001627CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001628 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001629}
Jay Foad39c79802011-01-12 09:06:06 +00001630CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001631 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001632}
1633
Chris Lattnera3402cd2009-01-27 18:08:34 +00001634/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1635/// type for the current target in bits. This can be different than the ABI
1636/// alignment in cases where it is beneficial for performance to overalign
1637/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001638unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001639 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001640
1641 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001642 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001643 T = CT->getElementType().getTypePtr();
1644 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001645 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1646 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001647 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1648
Chris Lattnera3402cd2009-01-27 18:08:34 +00001649 return ABIAlign;
1650}
1651
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001652/// DeepCollectObjCIvars -
1653/// This routine first collects all declared, but not synthesized, ivars in
1654/// super class and then collects all ivars, including those synthesized for
1655/// current class. This routine is used for implementation of current class
1656/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001657///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001658void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1659 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001660 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001661 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1662 DeepCollectObjCIvars(SuperClass, false, Ivars);
1663 if (!leafClass) {
1664 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1665 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001666 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001667 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001668 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001669 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001670 Iv= Iv->getNextIvar())
1671 Ivars.push_back(Iv);
1672 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001673}
1674
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001675/// CollectInheritedProtocols - Collect all protocols in current class and
1676/// those inherited by it.
1677void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001678 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001679 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001680 // We can use protocol_iterator here instead of
1681 // all_referenced_protocol_iterator since we are walking all categories.
1682 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1683 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001684 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001685 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001686 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001687 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001688 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001689 CollectInheritedProtocols(*P, Protocols);
1690 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001691 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001692
1693 // Categories of this Interface.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001694 for (ObjCInterfaceDecl::visible_categories_iterator
1695 Cat = OI->visible_categories_begin(),
1696 CatEnd = OI->visible_categories_end();
1697 Cat != CatEnd; ++Cat) {
1698 CollectInheritedProtocols(*Cat, Protocols);
1699 }
1700
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001701 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1702 while (SD) {
1703 CollectInheritedProtocols(SD, Protocols);
1704 SD = SD->getSuperClass();
1705 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001706 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001707 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001708 PE = OC->protocol_end(); P != PE; ++P) {
1709 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001710 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001711 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1712 PE = Proto->protocol_end(); P != PE; ++P)
1713 CollectInheritedProtocols(*P, Protocols);
1714 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001715 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001716 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1717 PE = OP->protocol_end(); P != PE; ++P) {
1718 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001719 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001720 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1721 PE = Proto->protocol_end(); P != PE; ++P)
1722 CollectInheritedProtocols(*P, Protocols);
1723 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001724 }
1725}
1726
Jay Foad39c79802011-01-12 09:06:06 +00001727unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001728 unsigned count = 0;
1729 // Count ivars declared in class extension.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001730 for (ObjCInterfaceDecl::known_extensions_iterator
1731 Ext = OI->known_extensions_begin(),
1732 ExtEnd = OI->known_extensions_end();
1733 Ext != ExtEnd; ++Ext) {
1734 count += Ext->ivar_size();
1735 }
1736
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001737 // Count ivar defined in this class's implementation. This
1738 // includes synthesized ivars.
1739 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001740 count += ImplDecl->ivar_size();
1741
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001742 return count;
1743}
1744
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001745bool ASTContext::isSentinelNullExpr(const Expr *E) {
1746 if (!E)
1747 return false;
1748
1749 // nullptr_t is always treated as null.
1750 if (E->getType()->isNullPtrType()) return true;
1751
1752 if (E->getType()->isAnyPointerType() &&
1753 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1754 Expr::NPC_ValueDependentIsNull))
1755 return true;
1756
1757 // Unfortunately, __null has type 'int'.
1758 if (isa<GNUNullExpr>(E)) return true;
1759
1760 return false;
1761}
1762
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001763/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1764ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1765 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1766 I = ObjCImpls.find(D);
1767 if (I != ObjCImpls.end())
1768 return cast<ObjCImplementationDecl>(I->second);
1769 return 0;
1770}
1771/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1772ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1773 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1774 I = ObjCImpls.find(D);
1775 if (I != ObjCImpls.end())
1776 return cast<ObjCCategoryImplDecl>(I->second);
1777 return 0;
1778}
1779
1780/// \brief Set the implementation of ObjCInterfaceDecl.
1781void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1782 ObjCImplementationDecl *ImplD) {
1783 assert(IFaceD && ImplD && "Passed null params");
1784 ObjCImpls[IFaceD] = ImplD;
1785}
1786/// \brief Set the implementation of ObjCCategoryDecl.
1787void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1788 ObjCCategoryImplDecl *ImplD) {
1789 assert(CatD && ImplD && "Passed null params");
1790 ObjCImpls[CatD] = ImplD;
1791}
1792
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001793ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1794 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1795 return ID;
1796 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1797 return CD->getClassInterface();
1798 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1799 return IMD->getClassInterface();
1800
1801 return 0;
1802}
1803
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001804/// \brief Get the copy initialization expression of VarDecl,or NULL if
1805/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001806Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001807 assert(VD && "Passed null params");
1808 assert(VD->hasAttr<BlocksAttr>() &&
1809 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001810 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001811 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001812 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1813}
1814
1815/// \brief Set the copy inialization expression of a block var decl.
1816void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1817 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001818 assert(VD->hasAttr<BlocksAttr>() &&
1819 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001820 BlockVarCopyInits[VD] = Init;
1821}
1822
John McCallbcd03502009-12-07 02:54:59 +00001823TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001824 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001825 if (!DataSize)
1826 DataSize = TypeLoc::getFullDataSizeForType(T);
1827 else
1828 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001829 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001830
John McCallbcd03502009-12-07 02:54:59 +00001831 TypeSourceInfo *TInfo =
1832 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1833 new (TInfo) TypeSourceInfo(T);
1834 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001835}
1836
John McCallbcd03502009-12-07 02:54:59 +00001837TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001838 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001839 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001840 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001841 return DI;
1842}
1843
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001844const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001845ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001846 return getObjCLayout(D, 0);
1847}
1848
1849const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001850ASTContext::getASTObjCImplementationLayout(
1851 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001852 return getObjCLayout(D->getClassInterface(), D);
1853}
1854
Chris Lattner983a8bb2007-07-13 22:13:22 +00001855//===----------------------------------------------------------------------===//
1856// Type creation/memoization methods
1857//===----------------------------------------------------------------------===//
1858
Jay Foad39c79802011-01-12 09:06:06 +00001859QualType
John McCall33ddac02011-01-19 10:06:00 +00001860ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1861 unsigned fastQuals = quals.getFastQualifiers();
1862 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001863
1864 // Check if we've already instantiated this type.
1865 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001866 ExtQuals::Profile(ID, baseType, quals);
1867 void *insertPos = 0;
1868 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1869 assert(eq->getQualifiers() == quals);
1870 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001871 }
1872
John McCall33ddac02011-01-19 10:06:00 +00001873 // If the base type is not canonical, make the appropriate canonical type.
1874 QualType canon;
1875 if (!baseType->isCanonicalUnqualified()) {
1876 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00001877 canonSplit.Quals.addConsistentQualifiers(quals);
1878 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001879
1880 // Re-find the insert position.
1881 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1882 }
1883
1884 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1885 ExtQualNodes.InsertNode(eq, insertPos);
1886 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001887}
1888
Jay Foad39c79802011-01-12 09:06:06 +00001889QualType
1890ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001891 QualType CanT = getCanonicalType(T);
1892 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001893 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001894
John McCall8ccfcb52009-09-24 19:53:00 +00001895 // If we are composing extended qualifiers together, merge together
1896 // into one ExtQuals node.
1897 QualifierCollector Quals;
1898 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001899
John McCall8ccfcb52009-09-24 19:53:00 +00001900 // If this type already has an address space specified, it cannot get
1901 // another one.
1902 assert(!Quals.hasAddressSpace() &&
1903 "Type cannot be in multiple addr spaces!");
1904 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001905
John McCall8ccfcb52009-09-24 19:53:00 +00001906 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001907}
1908
Chris Lattnerd60183d2009-02-18 22:53:11 +00001909QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001910 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001911 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001912 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001913 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001914
John McCall53fa7142010-12-24 02:08:15 +00001915 if (const PointerType *ptr = T->getAs<PointerType>()) {
1916 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001917 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001918 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1919 return getPointerType(ResultType);
1920 }
1921 }
Mike Stump11289f42009-09-09 15:08:12 +00001922
John McCall8ccfcb52009-09-24 19:53:00 +00001923 // If we are composing extended qualifiers together, merge together
1924 // into one ExtQuals node.
1925 QualifierCollector Quals;
1926 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001927
John McCall8ccfcb52009-09-24 19:53:00 +00001928 // If this type already has an ObjCGC specified, it cannot get
1929 // another one.
1930 assert(!Quals.hasObjCGCAttr() &&
1931 "Type cannot have multiple ObjCGCs!");
1932 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001933
John McCall8ccfcb52009-09-24 19:53:00 +00001934 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001935}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001936
John McCall4f5019e2010-12-19 02:44:49 +00001937const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1938 FunctionType::ExtInfo Info) {
1939 if (T->getExtInfo() == Info)
1940 return T;
1941
1942 QualType Result;
1943 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1944 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1945 } else {
1946 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1947 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1948 EPI.ExtInfo = Info;
1949 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1950 FPT->getNumArgs(), EPI);
1951 }
1952
1953 return cast<FunctionType>(Result.getTypePtr());
1954}
1955
Chris Lattnerc6395932007-06-22 20:56:16 +00001956/// getComplexType - Return the uniqued reference to the type for a complex
1957/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001958QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001959 // Unique pointers, to guarantee there is only one pointer of a particular
1960 // structure.
1961 llvm::FoldingSetNodeID ID;
1962 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001963
Chris Lattnerc6395932007-06-22 20:56:16 +00001964 void *InsertPos = 0;
1965 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1966 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001967
Chris Lattnerc6395932007-06-22 20:56:16 +00001968 // If the pointee type isn't canonical, this won't be a canonical type either,
1969 // so fill in the canonical type field.
1970 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001971 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001972 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001973
Chris Lattnerc6395932007-06-22 20:56:16 +00001974 // Get the new insert position for the node we care about.
1975 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001976 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001977 }
John McCall90d1c2d2009-09-24 23:30:46 +00001978 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001979 Types.push_back(New);
1980 ComplexTypes.InsertNode(New, InsertPos);
1981 return QualType(New, 0);
1982}
1983
Chris Lattner970e54e2006-11-12 00:37:36 +00001984/// getPointerType - Return the uniqued reference to the type for a pointer to
1985/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001986QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001987 // Unique pointers, to guarantee there is only one pointer of a particular
1988 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001989 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001990 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001991
Chris Lattner67521df2007-01-27 01:29:36 +00001992 void *InsertPos = 0;
1993 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001994 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001995
Chris Lattner7ccecb92006-11-12 08:50:50 +00001996 // If the pointee type isn't canonical, this won't be a canonical type either,
1997 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001998 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001999 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002000 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002001
Chris Lattner67521df2007-01-27 01:29:36 +00002002 // Get the new insert position for the node we care about.
2003 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002004 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00002005 }
John McCall90d1c2d2009-09-24 23:30:46 +00002006 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002007 Types.push_back(New);
2008 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002009 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002010}
2011
Mike Stump11289f42009-09-09 15:08:12 +00002012/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002013/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002014QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002015 assert(T->isFunctionType() && "block of function types only");
2016 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002017 // structure.
2018 llvm::FoldingSetNodeID ID;
2019 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002020
Steve Naroffec33ed92008-08-27 16:04:49 +00002021 void *InsertPos = 0;
2022 if (BlockPointerType *PT =
2023 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2024 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002025
2026 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002027 // type either so fill in the canonical type field.
2028 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002029 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002030 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002031
Steve Naroffec33ed92008-08-27 16:04:49 +00002032 // Get the new insert position for the node we care about.
2033 BlockPointerType *NewIP =
2034 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002035 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002036 }
John McCall90d1c2d2009-09-24 23:30:46 +00002037 BlockPointerType *New
2038 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002039 Types.push_back(New);
2040 BlockPointerTypes.InsertNode(New, InsertPos);
2041 return QualType(New, 0);
2042}
2043
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002044/// getLValueReferenceType - Return the uniqued reference to the type for an
2045/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002046QualType
2047ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002048 assert(getCanonicalType(T) != OverloadTy &&
2049 "Unresolved overloaded function type");
2050
Bill Wendling3708c182007-05-27 10:15:43 +00002051 // Unique pointers, to guarantee there is only one pointer of a particular
2052 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002053 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002054 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002055
2056 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002057 if (LValueReferenceType *RT =
2058 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002059 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002060
John McCallfc93cf92009-10-22 22:37:11 +00002061 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2062
Bill Wendling3708c182007-05-27 10:15:43 +00002063 // If the referencee type isn't canonical, this won't be a canonical type
2064 // either, so fill in the canonical type field.
2065 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002066 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2067 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2068 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002069
Bill Wendling3708c182007-05-27 10:15:43 +00002070 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002071 LValueReferenceType *NewIP =
2072 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002073 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002074 }
2075
John McCall90d1c2d2009-09-24 23:30:46 +00002076 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002077 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2078 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002079 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002080 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002081
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002082 return QualType(New, 0);
2083}
2084
2085/// getRValueReferenceType - Return the uniqued reference to the type for an
2086/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002087QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002088 // Unique pointers, to guarantee there is only one pointer of a particular
2089 // structure.
2090 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002091 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002092
2093 void *InsertPos = 0;
2094 if (RValueReferenceType *RT =
2095 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2096 return QualType(RT, 0);
2097
John McCallfc93cf92009-10-22 22:37:11 +00002098 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2099
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002100 // If the referencee type isn't canonical, this won't be a canonical type
2101 // either, so fill in the canonical type field.
2102 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002103 if (InnerRef || !T.isCanonical()) {
2104 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2105 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002106
2107 // Get the new insert position for the node we care about.
2108 RValueReferenceType *NewIP =
2109 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002110 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002111 }
2112
John McCall90d1c2d2009-09-24 23:30:46 +00002113 RValueReferenceType *New
2114 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002115 Types.push_back(New);
2116 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002117 return QualType(New, 0);
2118}
2119
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002120/// getMemberPointerType - Return the uniqued reference to the type for a
2121/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002122QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002123 // Unique pointers, to guarantee there is only one pointer of a particular
2124 // structure.
2125 llvm::FoldingSetNodeID ID;
2126 MemberPointerType::Profile(ID, T, Cls);
2127
2128 void *InsertPos = 0;
2129 if (MemberPointerType *PT =
2130 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2131 return QualType(PT, 0);
2132
2133 // If the pointee or class type isn't canonical, this won't be a canonical
2134 // type either, so fill in the canonical type field.
2135 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002136 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002137 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2138
2139 // Get the new insert position for the node we care about.
2140 MemberPointerType *NewIP =
2141 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002142 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002143 }
John McCall90d1c2d2009-09-24 23:30:46 +00002144 MemberPointerType *New
2145 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002146 Types.push_back(New);
2147 MemberPointerTypes.InsertNode(New, InsertPos);
2148 return QualType(New, 0);
2149}
2150
Mike Stump11289f42009-09-09 15:08:12 +00002151/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002152/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002153QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002154 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002155 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002156 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002157 assert((EltTy->isDependentType() ||
2158 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002159 "Constant array of VLAs is illegal!");
2160
Chris Lattnere2df3f92009-05-13 04:12:56 +00002161 // Convert the array size into a canonical width matching the pointer size for
2162 // the target.
2163 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002164 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002165 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002166
Chris Lattner23b7eb62007-06-15 23:05:46 +00002167 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002168 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002169
Chris Lattner36f8e652007-01-27 08:31:04 +00002170 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002171 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002172 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002173 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002174
John McCall33ddac02011-01-19 10:06:00 +00002175 // If the element type isn't canonical or has qualifiers, this won't
2176 // be a canonical type either, so fill in the canonical type field.
2177 QualType Canon;
2178 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2179 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002180 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002181 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002182 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002183
Chris Lattner36f8e652007-01-27 08:31:04 +00002184 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002185 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002186 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002187 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002188 }
Mike Stump11289f42009-09-09 15:08:12 +00002189
John McCall90d1c2d2009-09-24 23:30:46 +00002190 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002191 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002192 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002193 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002194 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002195}
2196
John McCall06549462011-01-18 08:40:38 +00002197/// getVariableArrayDecayedType - Turns the given type, which may be
2198/// variably-modified, into the corresponding type with all the known
2199/// sizes replaced with [*].
2200QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2201 // Vastly most common case.
2202 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002203
John McCall06549462011-01-18 08:40:38 +00002204 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002205
John McCall06549462011-01-18 08:40:38 +00002206 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002207 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002208 switch (ty->getTypeClass()) {
2209#define TYPE(Class, Base)
2210#define ABSTRACT_TYPE(Class, Base)
2211#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2212#include "clang/AST/TypeNodes.def"
2213 llvm_unreachable("didn't desugar past all non-canonical types?");
2214
2215 // These types should never be variably-modified.
2216 case Type::Builtin:
2217 case Type::Complex:
2218 case Type::Vector:
2219 case Type::ExtVector:
2220 case Type::DependentSizedExtVector:
2221 case Type::ObjCObject:
2222 case Type::ObjCInterface:
2223 case Type::ObjCObjectPointer:
2224 case Type::Record:
2225 case Type::Enum:
2226 case Type::UnresolvedUsing:
2227 case Type::TypeOfExpr:
2228 case Type::TypeOf:
2229 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002230 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002231 case Type::DependentName:
2232 case Type::InjectedClassName:
2233 case Type::TemplateSpecialization:
2234 case Type::DependentTemplateSpecialization:
2235 case Type::TemplateTypeParm:
2236 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002237 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002238 case Type::PackExpansion:
2239 llvm_unreachable("type should never be variably-modified");
2240
2241 // These types can be variably-modified but should never need to
2242 // further decay.
2243 case Type::FunctionNoProto:
2244 case Type::FunctionProto:
2245 case Type::BlockPointer:
2246 case Type::MemberPointer:
2247 return type;
2248
2249 // These types can be variably-modified. All these modifications
2250 // preserve structure except as noted by comments.
2251 // TODO: if we ever care about optimizing VLAs, there are no-op
2252 // optimizations available here.
2253 case Type::Pointer:
2254 result = getPointerType(getVariableArrayDecayedType(
2255 cast<PointerType>(ty)->getPointeeType()));
2256 break;
2257
2258 case Type::LValueReference: {
2259 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2260 result = getLValueReferenceType(
2261 getVariableArrayDecayedType(lv->getPointeeType()),
2262 lv->isSpelledAsLValue());
2263 break;
2264 }
2265
2266 case Type::RValueReference: {
2267 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2268 result = getRValueReferenceType(
2269 getVariableArrayDecayedType(lv->getPointeeType()));
2270 break;
2271 }
2272
Eli Friedman0dfb8892011-10-06 23:00:33 +00002273 case Type::Atomic: {
2274 const AtomicType *at = cast<AtomicType>(ty);
2275 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2276 break;
2277 }
2278
John McCall06549462011-01-18 08:40:38 +00002279 case Type::ConstantArray: {
2280 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2281 result = getConstantArrayType(
2282 getVariableArrayDecayedType(cat->getElementType()),
2283 cat->getSize(),
2284 cat->getSizeModifier(),
2285 cat->getIndexTypeCVRQualifiers());
2286 break;
2287 }
2288
2289 case Type::DependentSizedArray: {
2290 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2291 result = getDependentSizedArrayType(
2292 getVariableArrayDecayedType(dat->getElementType()),
2293 dat->getSizeExpr(),
2294 dat->getSizeModifier(),
2295 dat->getIndexTypeCVRQualifiers(),
2296 dat->getBracketsRange());
2297 break;
2298 }
2299
2300 // Turn incomplete types into [*] types.
2301 case Type::IncompleteArray: {
2302 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2303 result = getVariableArrayType(
2304 getVariableArrayDecayedType(iat->getElementType()),
2305 /*size*/ 0,
2306 ArrayType::Normal,
2307 iat->getIndexTypeCVRQualifiers(),
2308 SourceRange());
2309 break;
2310 }
2311
2312 // Turn VLA types into [*] types.
2313 case Type::VariableArray: {
2314 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2315 result = getVariableArrayType(
2316 getVariableArrayDecayedType(vat->getElementType()),
2317 /*size*/ 0,
2318 ArrayType::Star,
2319 vat->getIndexTypeCVRQualifiers(),
2320 vat->getBracketsRange());
2321 break;
2322 }
2323 }
2324
2325 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002326 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002327}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002328
Steve Naroffcadebd02007-08-30 18:14:25 +00002329/// getVariableArrayType - Returns a non-unique reference to the type for a
2330/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002331QualType ASTContext::getVariableArrayType(QualType EltTy,
2332 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002333 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002334 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002335 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002336 // Since we don't unique expressions, it isn't possible to unique VLA's
2337 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002338 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002339
John McCall33ddac02011-01-19 10:06:00 +00002340 // Be sure to pull qualifiers off the element type.
2341 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2342 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002343 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002344 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002345 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002346 }
2347
John McCall90d1c2d2009-09-24 23:30:46 +00002348 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002349 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002350
2351 VariableArrayTypes.push_back(New);
2352 Types.push_back(New);
2353 return QualType(New, 0);
2354}
2355
Douglas Gregor4619e432008-12-05 23:32:09 +00002356/// getDependentSizedArrayType - Returns a non-unique reference to
2357/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002358/// type.
John McCall33ddac02011-01-19 10:06:00 +00002359QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2360 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002361 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002362 unsigned elementTypeQuals,
2363 SourceRange brackets) const {
2364 assert((!numElements || numElements->isTypeDependent() ||
2365 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002366 "Size must be type- or value-dependent!");
2367
John McCall33ddac02011-01-19 10:06:00 +00002368 // Dependently-sized array types that do not have a specified number
2369 // of elements will have their sizes deduced from a dependent
2370 // initializer. We do no canonicalization here at all, which is okay
2371 // because they can't be used in most locations.
2372 if (!numElements) {
2373 DependentSizedArrayType *newType
2374 = new (*this, TypeAlignment)
2375 DependentSizedArrayType(*this, elementType, QualType(),
2376 numElements, ASM, elementTypeQuals,
2377 brackets);
2378 Types.push_back(newType);
2379 return QualType(newType, 0);
2380 }
2381
2382 // Otherwise, we actually build a new type every time, but we
2383 // also build a canonical type.
2384
2385 SplitQualType canonElementType = getCanonicalType(elementType).split();
2386
2387 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002388 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002389 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002390 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002391 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002392
John McCall33ddac02011-01-19 10:06:00 +00002393 // Look for an existing type with these properties.
2394 DependentSizedArrayType *canonTy =
2395 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002396
John McCall33ddac02011-01-19 10:06:00 +00002397 // If we don't have one, build one.
2398 if (!canonTy) {
2399 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002400 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002401 QualType(), numElements, ASM, elementTypeQuals,
2402 brackets);
2403 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2404 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002405 }
2406
John McCall33ddac02011-01-19 10:06:00 +00002407 // Apply qualifiers from the element type to the array.
2408 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002409 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002410
John McCall33ddac02011-01-19 10:06:00 +00002411 // If we didn't need extra canonicalization for the element type,
2412 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002413 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002414 return canon;
2415
2416 // Otherwise, we need to build a type which follows the spelling
2417 // of the element type.
2418 DependentSizedArrayType *sugaredType
2419 = new (*this, TypeAlignment)
2420 DependentSizedArrayType(*this, elementType, canon, numElements,
2421 ASM, elementTypeQuals, brackets);
2422 Types.push_back(sugaredType);
2423 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002424}
2425
John McCall33ddac02011-01-19 10:06:00 +00002426QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002427 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002428 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002429 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002430 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002431
John McCall33ddac02011-01-19 10:06:00 +00002432 void *insertPos = 0;
2433 if (IncompleteArrayType *iat =
2434 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2435 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002436
2437 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002438 // either, so fill in the canonical type field. We also have to pull
2439 // qualifiers off the element type.
2440 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002441
John McCall33ddac02011-01-19 10:06:00 +00002442 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2443 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002444 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002445 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002446 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002447
2448 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002449 IncompleteArrayType *existing =
2450 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2451 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002452 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002453
John McCall33ddac02011-01-19 10:06:00 +00002454 IncompleteArrayType *newType = new (*this, TypeAlignment)
2455 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002456
John McCall33ddac02011-01-19 10:06:00 +00002457 IncompleteArrayTypes.InsertNode(newType, insertPos);
2458 Types.push_back(newType);
2459 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002460}
2461
Steve Naroff91fcddb2007-07-18 18:00:27 +00002462/// getVectorType - Return the unique reference to a vector type of
2463/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002464QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002465 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002466 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002467
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002468 // Check if we've already instantiated a vector of this type.
2469 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002470 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002471
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002472 void *InsertPos = 0;
2473 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2474 return QualType(VTP, 0);
2475
2476 // If the element type isn't canonical, this won't be a canonical type either,
2477 // so fill in the canonical type field.
2478 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002479 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002480 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002481
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002482 // Get the new insert position for the node we care about.
2483 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002484 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002485 }
John McCall90d1c2d2009-09-24 23:30:46 +00002486 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002487 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002488 VectorTypes.InsertNode(New, InsertPos);
2489 Types.push_back(New);
2490 return QualType(New, 0);
2491}
2492
Nate Begemance4d7fc2008-04-18 23:10:10 +00002493/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002494/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002495QualType
2496ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002497 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002498
Steve Naroff91fcddb2007-07-18 18:00:27 +00002499 // Check if we've already instantiated a vector of this type.
2500 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002501 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002502 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002503 void *InsertPos = 0;
2504 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2505 return QualType(VTP, 0);
2506
2507 // If the element type isn't canonical, this won't be a canonical type either,
2508 // so fill in the canonical type field.
2509 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002510 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002511 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002512
Steve Naroff91fcddb2007-07-18 18:00:27 +00002513 // Get the new insert position for the node we care about.
2514 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002515 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002516 }
John McCall90d1c2d2009-09-24 23:30:46 +00002517 ExtVectorType *New = new (*this, TypeAlignment)
2518 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002519 VectorTypes.InsertNode(New, InsertPos);
2520 Types.push_back(New);
2521 return QualType(New, 0);
2522}
2523
Jay Foad39c79802011-01-12 09:06:06 +00002524QualType
2525ASTContext::getDependentSizedExtVectorType(QualType vecType,
2526 Expr *SizeExpr,
2527 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002528 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002529 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002530 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002531
Douglas Gregor352169a2009-07-31 03:54:25 +00002532 void *InsertPos = 0;
2533 DependentSizedExtVectorType *Canon
2534 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2535 DependentSizedExtVectorType *New;
2536 if (Canon) {
2537 // We already have a canonical version of this array type; use it as
2538 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002539 New = new (*this, TypeAlignment)
2540 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2541 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002542 } else {
2543 QualType CanonVecTy = getCanonicalType(vecType);
2544 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002545 New = new (*this, TypeAlignment)
2546 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2547 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002548
2549 DependentSizedExtVectorType *CanonCheck
2550 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2551 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2552 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002553 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2554 } else {
2555 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2556 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002557 New = new (*this, TypeAlignment)
2558 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002559 }
2560 }
Mike Stump11289f42009-09-09 15:08:12 +00002561
Douglas Gregor758a8692009-06-17 21:51:59 +00002562 Types.push_back(New);
2563 return QualType(New, 0);
2564}
2565
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002566/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002567///
Jay Foad39c79802011-01-12 09:06:06 +00002568QualType
2569ASTContext::getFunctionNoProtoType(QualType ResultTy,
2570 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002571 const CallingConv DefaultCC = Info.getCC();
2572 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2573 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002574 // Unique functions, to guarantee there is only one function of a particular
2575 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002576 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002577 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002578
Chris Lattner47955de2007-01-27 08:37:20 +00002579 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002580 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002581 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002582 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002583
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002584 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002585 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002586 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002587 Canonical =
2588 getFunctionNoProtoType(getCanonicalType(ResultTy),
2589 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002590
Chris Lattner47955de2007-01-27 08:37:20 +00002591 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002592 FunctionNoProtoType *NewIP =
2593 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002594 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002595 }
Mike Stump11289f42009-09-09 15:08:12 +00002596
Roman Divacky65b88cd2011-03-01 17:40:53 +00002597 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002598 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002599 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002600 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002601 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002602 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002603}
2604
Douglas Gregorcd780372013-01-17 23:36:45 +00002605/// \brief Determine whether \p T is canonical as the result type of a function.
2606static bool isCanonicalResultType(QualType T) {
2607 return T.isCanonical() &&
2608 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2609 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2610}
2611
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002612/// getFunctionType - Return a normal function type with a typed argument
2613/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002614QualType
2615ASTContext::getFunctionType(QualType ResultTy,
2616 const QualType *ArgArray, unsigned NumArgs,
2617 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002618 // Unique functions, to guarantee there is only one function of a particular
2619 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002620 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002621 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002622
2623 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002624 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002625 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002626 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002627
2628 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002629 bool isCanonical =
Douglas Gregorcd780372013-01-17 23:36:45 +00002630 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00002631 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002632 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002633 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002634 isCanonical = false;
2635
Roman Divacky65b88cd2011-03-01 17:40:53 +00002636 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2637 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2638 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002639
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002640 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002641 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002642 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002643 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002644 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002645 CanonicalArgs.reserve(NumArgs);
2646 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002647 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002648
John McCalldb40c7f2010-12-14 08:05:40 +00002649 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002650 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002651 CanonicalEPI.ExceptionSpecType = EST_None;
2652 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002653 CanonicalEPI.ExtInfo
2654 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2655
Douglas Gregorcd780372013-01-17 23:36:45 +00002656 // Result types do not have ARC lifetime qualifiers.
2657 QualType CanResultTy = getCanonicalType(ResultTy);
2658 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2659 Qualifiers Qs = CanResultTy.getQualifiers();
2660 Qs.removeObjCLifetime();
2661 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2662 }
2663
2664 Canonical = getFunctionType(CanResultTy,
Jay Foad7d0479f2009-05-21 09:52:38 +00002665 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002666 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002667
Chris Lattnerfd4de792007-01-27 01:15:32 +00002668 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002669 FunctionProtoType *NewIP =
2670 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002671 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002672 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002673
John McCall31168b02011-06-15 23:02:42 +00002674 // FunctionProtoType objects are allocated with extra bytes after
2675 // them for three variable size arrays at the end:
2676 // - parameter types
2677 // - exception types
2678 // - consumed-arguments flags
2679 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002680 // expression, or information used to resolve the exception
2681 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002682 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002683 NumArgs * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002684 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002685 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002686 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002687 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002688 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002689 Size += 2 * sizeof(FunctionDecl*);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002690 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2691 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002692 }
John McCall31168b02011-06-15 23:02:42 +00002693 if (EPI.ConsumedArguments)
2694 Size += NumArgs * sizeof(bool);
2695
John McCalldb40c7f2010-12-14 08:05:40 +00002696 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002697 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2698 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002699 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002700 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002701 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002702 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002703}
Chris Lattneref51c202006-11-10 07:17:23 +00002704
John McCalle78aac42010-03-10 03:28:59 +00002705#ifndef NDEBUG
2706static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2707 if (!isa<CXXRecordDecl>(D)) return false;
2708 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2709 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2710 return true;
2711 if (RD->getDescribedClassTemplate() &&
2712 !isa<ClassTemplateSpecializationDecl>(RD))
2713 return true;
2714 return false;
2715}
2716#endif
2717
2718/// getInjectedClassNameType - Return the unique reference to the
2719/// injected class name type for the specified templated declaration.
2720QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002721 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002722 assert(NeedsInjectedClassNameType(Decl));
2723 if (Decl->TypeForDecl) {
2724 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002725 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002726 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2727 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2728 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2729 } else {
John McCall424cec92011-01-19 06:33:43 +00002730 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002731 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002732 Decl->TypeForDecl = newType;
2733 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002734 }
2735 return QualType(Decl->TypeForDecl, 0);
2736}
2737
Douglas Gregor83a586e2008-04-13 21:07:44 +00002738/// getTypeDeclType - Return the unique reference to the type for the
2739/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002740QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002741 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002742 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002743
Richard Smithdda56e42011-04-15 14:24:37 +00002744 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002745 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002746
John McCall96f0b5f2010-03-10 06:48:02 +00002747 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2748 "Template type parameter types are always available.");
2749
John McCall81e38502010-02-16 03:57:14 +00002750 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002751 assert(!Record->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002752 "struct/union has previous declaration");
2753 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002754 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002755 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002756 assert(!Enum->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002757 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002758 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002759 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002760 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002761 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2762 Decl->TypeForDecl = newType;
2763 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002764 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002765 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002766
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002767 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002768}
2769
Chris Lattner32d920b2007-01-26 02:01:53 +00002770/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002771/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002772QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002773ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2774 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002775 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002776
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002777 if (Canonical.isNull())
2778 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002779 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002780 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002781 Decl->TypeForDecl = newType;
2782 Types.push_back(newType);
2783 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002784}
2785
Jay Foad39c79802011-01-12 09:06:06 +00002786QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002787 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2788
Douglas Gregorec9fd132012-01-14 16:38:05 +00002789 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002790 if (PrevDecl->TypeForDecl)
2791 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2792
John McCall424cec92011-01-19 06:33:43 +00002793 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2794 Decl->TypeForDecl = newType;
2795 Types.push_back(newType);
2796 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002797}
2798
Jay Foad39c79802011-01-12 09:06:06 +00002799QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002800 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2801
Douglas Gregorec9fd132012-01-14 16:38:05 +00002802 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002803 if (PrevDecl->TypeForDecl)
2804 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2805
John McCall424cec92011-01-19 06:33:43 +00002806 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2807 Decl->TypeForDecl = newType;
2808 Types.push_back(newType);
2809 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002810}
2811
John McCall81904512011-01-06 01:58:22 +00002812QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2813 QualType modifiedType,
2814 QualType equivalentType) {
2815 llvm::FoldingSetNodeID id;
2816 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2817
2818 void *insertPos = 0;
2819 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2820 if (type) return QualType(type, 0);
2821
2822 QualType canon = getCanonicalType(equivalentType);
2823 type = new (*this, TypeAlignment)
2824 AttributedType(canon, attrKind, modifiedType, equivalentType);
2825
2826 Types.push_back(type);
2827 AttributedTypes.InsertNode(type, insertPos);
2828
2829 return QualType(type, 0);
2830}
2831
2832
John McCallcebee162009-10-18 09:09:24 +00002833/// \brief Retrieve a substitution-result type.
2834QualType
2835ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002836 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002837 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002838 && "replacement types must always be canonical");
2839
2840 llvm::FoldingSetNodeID ID;
2841 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2842 void *InsertPos = 0;
2843 SubstTemplateTypeParmType *SubstParm
2844 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2845
2846 if (!SubstParm) {
2847 SubstParm = new (*this, TypeAlignment)
2848 SubstTemplateTypeParmType(Parm, Replacement);
2849 Types.push_back(SubstParm);
2850 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2851 }
2852
2853 return QualType(SubstParm, 0);
2854}
2855
Douglas Gregorada4b792011-01-14 02:55:32 +00002856/// \brief Retrieve a
2857QualType ASTContext::getSubstTemplateTypeParmPackType(
2858 const TemplateTypeParmType *Parm,
2859 const TemplateArgument &ArgPack) {
2860#ifndef NDEBUG
2861 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2862 PEnd = ArgPack.pack_end();
2863 P != PEnd; ++P) {
2864 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2865 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2866 }
2867#endif
2868
2869 llvm::FoldingSetNodeID ID;
2870 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2871 void *InsertPos = 0;
2872 if (SubstTemplateTypeParmPackType *SubstParm
2873 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2874 return QualType(SubstParm, 0);
2875
2876 QualType Canon;
2877 if (!Parm->isCanonicalUnqualified()) {
2878 Canon = getCanonicalType(QualType(Parm, 0));
2879 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2880 ArgPack);
2881 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2882 }
2883
2884 SubstTemplateTypeParmPackType *SubstParm
2885 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2886 ArgPack);
2887 Types.push_back(SubstParm);
2888 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2889 return QualType(SubstParm, 0);
2890}
2891
Douglas Gregoreff93e02009-02-05 23:33:38 +00002892/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002893/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002894/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002895QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002896 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002897 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002898 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002899 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002900 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002901 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002902 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2903
2904 if (TypeParm)
2905 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002906
Chandler Carruth08836322011-05-01 00:51:33 +00002907 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002908 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002909 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002910
2911 TemplateTypeParmType *TypeCheck
2912 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2913 assert(!TypeCheck && "Template type parameter canonical type broken");
2914 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002915 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002916 TypeParm = new (*this, TypeAlignment)
2917 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002918
2919 Types.push_back(TypeParm);
2920 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2921
2922 return QualType(TypeParm, 0);
2923}
2924
John McCalle78aac42010-03-10 03:28:59 +00002925TypeSourceInfo *
2926ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2927 SourceLocation NameLoc,
2928 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002929 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002930 assert(!Name.getAsDependentTemplateName() &&
2931 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002932 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002933
2934 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2935 TemplateSpecializationTypeLoc TL
2936 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002937 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00002938 TL.setTemplateNameLoc(NameLoc);
2939 TL.setLAngleLoc(Args.getLAngleLoc());
2940 TL.setRAngleLoc(Args.getRAngleLoc());
2941 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2942 TL.setArgLocInfo(i, Args[i].getLocInfo());
2943 return DI;
2944}
2945
Mike Stump11289f42009-09-09 15:08:12 +00002946QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002947ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002948 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002949 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002950 assert(!Template.getAsDependentTemplateName() &&
2951 "No dependent template names here!");
2952
John McCall6b51f282009-11-23 01:53:49 +00002953 unsigned NumArgs = Args.size();
2954
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002955 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002956 ArgVec.reserve(NumArgs);
2957 for (unsigned i = 0; i != NumArgs; ++i)
2958 ArgVec.push_back(Args[i].getArgument());
2959
John McCall2408e322010-04-27 00:57:59 +00002960 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002961 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002962}
2963
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002964#ifndef NDEBUG
2965static bool hasAnyPackExpansions(const TemplateArgument *Args,
2966 unsigned NumArgs) {
2967 for (unsigned I = 0; I != NumArgs; ++I)
2968 if (Args[I].isPackExpansion())
2969 return true;
2970
2971 return true;
2972}
2973#endif
2974
John McCall0ad16662009-10-29 08:12:44 +00002975QualType
2976ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002977 const TemplateArgument *Args,
2978 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002979 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002980 assert(!Template.getAsDependentTemplateName() &&
2981 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002982 // Look through qualified template names.
2983 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2984 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002985
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002986 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00002987 Template.getAsTemplateDecl() &&
2988 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00002989 QualType CanonType;
2990 if (!Underlying.isNull())
2991 CanonType = getCanonicalType(Underlying);
2992 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002993 // We can get here with an alias template when the specialization contains
2994 // a pack expansion that does not match up with a parameter pack.
2995 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2996 "Caller must compute aliased type");
2997 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00002998 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2999 NumArgs);
3000 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003001
Douglas Gregora8e02e72009-07-28 23:00:59 +00003002 // Allocate the (non-canonical) template specialization type, but don't
3003 // try to unique it: these types typically have location information that
3004 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003005 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3006 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003007 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003008 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003009 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003010 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3011 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003012
Douglas Gregor8bf42052009-02-09 18:46:07 +00003013 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003014 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003015}
3016
Mike Stump11289f42009-09-09 15:08:12 +00003017QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003018ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3019 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003020 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003021 assert(!Template.getAsDependentTemplateName() &&
3022 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003023
Douglas Gregore29139c2011-03-03 17:04:51 +00003024 // Look through qualified template names.
3025 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3026 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003027
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003028 // Build the canonical template specialization type.
3029 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003030 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003031 CanonArgs.reserve(NumArgs);
3032 for (unsigned I = 0; I != NumArgs; ++I)
3033 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3034
3035 // Determine whether this canonical template specialization type already
3036 // exists.
3037 llvm::FoldingSetNodeID ID;
3038 TemplateSpecializationType::Profile(ID, CanonTemplate,
3039 CanonArgs.data(), NumArgs, *this);
3040
3041 void *InsertPos = 0;
3042 TemplateSpecializationType *Spec
3043 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3044
3045 if (!Spec) {
3046 // Allocate a new canonical template specialization type.
3047 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3048 sizeof(TemplateArgument) * NumArgs),
3049 TypeAlignment);
3050 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3051 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003052 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003053 Types.push_back(Spec);
3054 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3055 }
3056
3057 assert(Spec->isDependentType() &&
3058 "Non-dependent template-id type must have a canonical type");
3059 return QualType(Spec, 0);
3060}
3061
3062QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003063ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3064 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003065 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003066 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003067 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003068
3069 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003070 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003071 if (T)
3072 return QualType(T, 0);
3073
Douglas Gregorc42075a2010-02-04 18:10:26 +00003074 QualType Canon = NamedType;
3075 if (!Canon.isCanonical()) {
3076 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003077 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3078 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003079 (void)CheckT;
3080 }
3081
Abramo Bagnara6150c882010-05-11 21:36:43 +00003082 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003083 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003084 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003085 return QualType(T, 0);
3086}
3087
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003088QualType
Jay Foad39c79802011-01-12 09:06:06 +00003089ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003090 llvm::FoldingSetNodeID ID;
3091 ParenType::Profile(ID, InnerType);
3092
3093 void *InsertPos = 0;
3094 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3095 if (T)
3096 return QualType(T, 0);
3097
3098 QualType Canon = InnerType;
3099 if (!Canon.isCanonical()) {
3100 Canon = getCanonicalType(InnerType);
3101 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3102 assert(!CheckT && "Paren canonical type broken");
3103 (void)CheckT;
3104 }
3105
3106 T = new (*this) ParenType(InnerType, Canon);
3107 Types.push_back(T);
3108 ParenTypes.InsertNode(T, InsertPos);
3109 return QualType(T, 0);
3110}
3111
Douglas Gregor02085352010-03-31 20:19:30 +00003112QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3113 NestedNameSpecifier *NNS,
3114 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003115 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003116 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3117
3118 if (Canon.isNull()) {
3119 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003120 ElaboratedTypeKeyword CanonKeyword = Keyword;
3121 if (Keyword == ETK_None)
3122 CanonKeyword = ETK_Typename;
3123
3124 if (CanonNNS != NNS || CanonKeyword != Keyword)
3125 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003126 }
3127
3128 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003129 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003130
3131 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003132 DependentNameType *T
3133 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003134 if (T)
3135 return QualType(T, 0);
3136
Douglas Gregor02085352010-03-31 20:19:30 +00003137 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003138 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003139 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003140 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003141}
3142
Mike Stump11289f42009-09-09 15:08:12 +00003143QualType
John McCallc392f372010-06-11 00:33:02 +00003144ASTContext::getDependentTemplateSpecializationType(
3145 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003146 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003147 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003148 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003149 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003150 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003151 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3152 ArgCopy.push_back(Args[I].getArgument());
3153 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3154 ArgCopy.size(),
3155 ArgCopy.data());
3156}
3157
3158QualType
3159ASTContext::getDependentTemplateSpecializationType(
3160 ElaboratedTypeKeyword Keyword,
3161 NestedNameSpecifier *NNS,
3162 const IdentifierInfo *Name,
3163 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003164 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003165 assert((!NNS || NNS->isDependent()) &&
3166 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003167
Douglas Gregorc42075a2010-02-04 18:10:26 +00003168 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003169 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3170 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003171
3172 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00003173 DependentTemplateSpecializationType *T
3174 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003175 if (T)
3176 return QualType(T, 0);
3177
John McCallc392f372010-06-11 00:33:02 +00003178 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003179
John McCallc392f372010-06-11 00:33:02 +00003180 ElaboratedTypeKeyword CanonKeyword = Keyword;
3181 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3182
3183 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003184 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003185 for (unsigned I = 0; I != NumArgs; ++I) {
3186 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3187 if (!CanonArgs[I].structurallyEquals(Args[I]))
3188 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003189 }
3190
John McCallc392f372010-06-11 00:33:02 +00003191 QualType Canon;
3192 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3193 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3194 Name, NumArgs,
3195 CanonArgs.data());
3196
3197 // Find the insert position again.
3198 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3199 }
3200
3201 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3202 sizeof(TemplateArgument) * NumArgs),
3203 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003204 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003205 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003206 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003207 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003208 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003209}
3210
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003211QualType ASTContext::getPackExpansionType(QualType Pattern,
3212 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003213 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003214 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003215
3216 assert(Pattern->containsUnexpandedParameterPack() &&
3217 "Pack expansions must expand one or more parameter packs");
3218 void *InsertPos = 0;
3219 PackExpansionType *T
3220 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3221 if (T)
3222 return QualType(T, 0);
3223
3224 QualType Canon;
3225 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003226 Canon = getCanonicalType(Pattern);
3227 // The canonical type might not contain an unexpanded parameter pack, if it
3228 // contains an alias template specialization which ignores one of its
3229 // parameters.
3230 if (Canon->containsUnexpandedParameterPack()) {
3231 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003232
Richard Smith68eea502012-07-16 00:20:35 +00003233 // Find the insert position again, in case we inserted an element into
3234 // PackExpansionTypes and invalidated our insert position.
3235 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3236 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003237 }
3238
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003239 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003240 Types.push_back(T);
3241 PackExpansionTypes.InsertNode(T, InsertPos);
3242 return QualType(T, 0);
3243}
3244
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003245/// CmpProtocolNames - Comparison predicate for sorting protocols
3246/// alphabetically.
3247static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3248 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003249 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003250}
3251
John McCall8b07ec22010-05-15 11:32:37 +00003252static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003253 unsigned NumProtocols) {
3254 if (NumProtocols == 0) return true;
3255
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003256 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3257 return false;
3258
John McCallfc93cf92009-10-22 22:37:11 +00003259 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003260 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3261 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003262 return false;
3263 return true;
3264}
3265
3266static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003267 unsigned &NumProtocols) {
3268 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003269
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003270 // Sort protocols, keyed by name.
3271 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3272
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003273 // Canonicalize.
3274 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3275 Protocols[I] = Protocols[I]->getCanonicalDecl();
3276
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003277 // Remove duplicates.
3278 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3279 NumProtocols = ProtocolsEnd-Protocols;
3280}
3281
John McCall8b07ec22010-05-15 11:32:37 +00003282QualType ASTContext::getObjCObjectType(QualType BaseType,
3283 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003284 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003285 // If the base type is an interface and there aren't any protocols
3286 // to add, then the interface type will do just fine.
3287 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3288 return BaseType;
3289
3290 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003291 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003292 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00003293 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00003294 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3295 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003296
John McCall8b07ec22010-05-15 11:32:37 +00003297 // Build the canonical type, which has the canonical base type and
3298 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003299 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003300 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3301 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3302 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003303 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003304 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003305 unsigned UniqueCount = NumProtocols;
3306
John McCallfc93cf92009-10-22 22:37:11 +00003307 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003308 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3309 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003310 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003311 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3312 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003313 }
3314
3315 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003316 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3317 }
3318
3319 unsigned Size = sizeof(ObjCObjectTypeImpl);
3320 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3321 void *Mem = Allocate(Size, TypeAlignment);
3322 ObjCObjectTypeImpl *T =
3323 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3324
3325 Types.push_back(T);
3326 ObjCObjectTypes.InsertNode(T, InsertPos);
3327 return QualType(T, 0);
3328}
3329
3330/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3331/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003332QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003333 llvm::FoldingSetNodeID ID;
3334 ObjCObjectPointerType::Profile(ID, ObjectT);
3335
3336 void *InsertPos = 0;
3337 if (ObjCObjectPointerType *QT =
3338 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3339 return QualType(QT, 0);
3340
3341 // Find the canonical object type.
3342 QualType Canonical;
3343 if (!ObjectT.isCanonical()) {
3344 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3345
3346 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003347 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3348 }
3349
Douglas Gregorf85bee62010-02-08 22:59:26 +00003350 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003351 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3352 ObjCObjectPointerType *QType =
3353 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003354
Steve Narofffb4330f2009-06-17 22:40:22 +00003355 Types.push_back(QType);
3356 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003357 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003358}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003359
Douglas Gregor1c283312010-08-11 12:19:30 +00003360/// getObjCInterfaceType - Return the unique reference to the type for the
3361/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003362QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3363 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003364 if (Decl->TypeForDecl)
3365 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003366
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003367 if (PrevDecl) {
3368 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3369 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3370 return QualType(PrevDecl->TypeForDecl, 0);
3371 }
3372
Douglas Gregor7671e532011-12-16 16:34:57 +00003373 // Prefer the definition, if there is one.
3374 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3375 Decl = Def;
3376
Douglas Gregor1c283312010-08-11 12:19:30 +00003377 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3378 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3379 Decl->TypeForDecl = T;
3380 Types.push_back(T);
3381 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003382}
3383
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003384/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3385/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003386/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003387/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003388/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003389QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003390 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003391 if (tofExpr->isTypeDependent()) {
3392 llvm::FoldingSetNodeID ID;
3393 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003394
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003395 void *InsertPos = 0;
3396 DependentTypeOfExprType *Canon
3397 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3398 if (Canon) {
3399 // We already have a "canonical" version of an identical, dependent
3400 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003401 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003402 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003403 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003404 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003405 Canon
3406 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003407 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3408 toe = Canon;
3409 }
3410 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003411 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003412 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003413 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003414 Types.push_back(toe);
3415 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003416}
3417
Steve Naroffa773cd52007-08-01 18:02:17 +00003418/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3419/// TypeOfType AST's. The only motivation to unique these nodes would be
3420/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003421/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003422/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003423QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003424 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003425 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003426 Types.push_back(tot);
3427 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003428}
3429
Anders Carlssonad6bd352009-06-24 21:24:56 +00003430
Anders Carlsson81df7b82009-06-24 19:06:50 +00003431/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3432/// DecltypeType AST's. The only motivation to unique these nodes would be
3433/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003434/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003435/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003436QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003437 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003438
3439 // C++0x [temp.type]p2:
3440 // If an expression e involves a template parameter, decltype(e) denotes a
3441 // unique dependent type. Two such decltype-specifiers refer to the same
3442 // type only if their expressions are equivalent (14.5.6.1).
3443 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003444 llvm::FoldingSetNodeID ID;
3445 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003446
Douglas Gregora21f6c32009-07-30 23:36:40 +00003447 void *InsertPos = 0;
3448 DependentDecltypeType *Canon
3449 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3450 if (Canon) {
3451 // We already have a "canonical" version of an equivalent, dependent
3452 // decltype type. Use that as our canonical type.
Richard Smithef8bf432012-08-13 20:08:14 +00003453 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003454 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003455 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003456 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003457 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003458 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3459 dt = Canon;
3460 }
3461 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003462 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3463 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003464 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003465 Types.push_back(dt);
3466 return QualType(dt, 0);
3467}
3468
Alexis Hunte852b102011-05-24 22:41:36 +00003469/// getUnaryTransformationType - We don't unique these, since the memory
3470/// savings are minimal and these are rare.
3471QualType ASTContext::getUnaryTransformType(QualType BaseType,
3472 QualType UnderlyingType,
3473 UnaryTransformType::UTTKind Kind)
3474 const {
3475 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003476 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3477 Kind,
3478 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003479 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003480 Types.push_back(Ty);
3481 return QualType(Ty, 0);
3482}
3483
Richard Smithb2bc2e62011-02-21 20:05:19 +00003484/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003485QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00003486 void *InsertPos = 0;
3487 if (!DeducedType.isNull()) {
3488 // Look in the folding set for an existing type.
3489 llvm::FoldingSetNodeID ID;
3490 AutoType::Profile(ID, DeducedType);
3491 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3492 return QualType(AT, 0);
3493 }
3494
3495 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3496 Types.push_back(AT);
3497 if (InsertPos)
3498 AutoTypes.InsertNode(AT, InsertPos);
3499 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003500}
3501
Eli Friedman0dfb8892011-10-06 23:00:33 +00003502/// getAtomicType - Return the uniqued reference to the atomic type for
3503/// the given value type.
3504QualType ASTContext::getAtomicType(QualType T) const {
3505 // Unique pointers, to guarantee there is only one pointer of a particular
3506 // structure.
3507 llvm::FoldingSetNodeID ID;
3508 AtomicType::Profile(ID, T);
3509
3510 void *InsertPos = 0;
3511 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3512 return QualType(AT, 0);
3513
3514 // If the atomic value type isn't canonical, this won't be a canonical type
3515 // either, so fill in the canonical type field.
3516 QualType Canonical;
3517 if (!T.isCanonical()) {
3518 Canonical = getAtomicType(getCanonicalType(T));
3519
3520 // Get the new insert position for the node we care about.
3521 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3522 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3523 }
3524 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3525 Types.push_back(New);
3526 AtomicTypes.InsertNode(New, InsertPos);
3527 return QualType(New, 0);
3528}
3529
Richard Smith02e85f32011-04-14 22:09:26 +00003530/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3531QualType ASTContext::getAutoDeductType() const {
3532 if (AutoDeductTy.isNull())
3533 AutoDeductTy = getAutoType(QualType());
3534 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3535 return AutoDeductTy;
3536}
3537
3538/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3539QualType ASTContext::getAutoRRefDeductType() const {
3540 if (AutoRRefDeductTy.isNull())
3541 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3542 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3543 return AutoRRefDeductTy;
3544}
3545
Chris Lattnerfb072462007-01-23 05:45:31 +00003546/// getTagDeclType - Return the unique reference to the type for the
3547/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003548QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003549 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003550 // FIXME: What is the design on getTagDeclType when it requires casting
3551 // away const? mutable?
3552 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003553}
3554
Mike Stump11289f42009-09-09 15:08:12 +00003555/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3556/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3557/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003558CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003559 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003560}
Chris Lattnerfb072462007-01-23 05:45:31 +00003561
Hans Wennborg27541db2011-10-27 08:29:09 +00003562/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3563CanQualType ASTContext::getIntMaxType() const {
3564 return getFromTargetType(Target->getIntMaxType());
3565}
3566
3567/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3568CanQualType ASTContext::getUIntMaxType() const {
3569 return getFromTargetType(Target->getUIntMaxType());
3570}
3571
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003572/// getSignedWCharType - Return the type of "signed wchar_t".
3573/// Used when in C++, as a GCC extension.
3574QualType ASTContext::getSignedWCharType() const {
3575 // FIXME: derive from "Target" ?
3576 return WCharTy;
3577}
3578
3579/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3580/// Used when in C++, as a GCC extension.
3581QualType ASTContext::getUnsignedWCharType() const {
3582 // FIXME: derive from "Target" ?
3583 return UnsignedIntTy;
3584}
3585
Hans Wennborg27541db2011-10-27 08:29:09 +00003586/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003587/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3588QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003589 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003590}
3591
Eli Friedman4e91899e2012-11-27 02:58:24 +00003592/// \brief Return the unique type for "pid_t" defined in
3593/// <sys/types.h>. We need this to compute the correct type for vfork().
3594QualType ASTContext::getProcessIDType() const {
3595 return getFromTargetType(Target->getProcessIDType());
3596}
3597
Chris Lattnera21ad802008-04-02 05:18:44 +00003598//===----------------------------------------------------------------------===//
3599// Type Operators
3600//===----------------------------------------------------------------------===//
3601
Jay Foad39c79802011-01-12 09:06:06 +00003602CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003603 // Push qualifiers into arrays, and then discard any remaining
3604 // qualifiers.
3605 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003606 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003607 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003608 QualType Result;
3609 if (isa<ArrayType>(Ty)) {
3610 Result = getArrayDecayedType(QualType(Ty,0));
3611 } else if (isa<FunctionType>(Ty)) {
3612 Result = getPointerType(QualType(Ty, 0));
3613 } else {
3614 Result = QualType(Ty, 0);
3615 }
3616
3617 return CanQualType::CreateUnsafe(Result);
3618}
3619
John McCall6c9dd522011-01-18 07:41:22 +00003620QualType ASTContext::getUnqualifiedArrayType(QualType type,
3621 Qualifiers &quals) {
3622 SplitQualType splitType = type.getSplitUnqualifiedType();
3623
3624 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3625 // the unqualified desugared type and then drops it on the floor.
3626 // We then have to strip that sugar back off with
3627 // getUnqualifiedDesugaredType(), which is silly.
3628 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003629 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003630
3631 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003632 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003633 quals = splitType.Quals;
3634 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003635 }
3636
John McCall6c9dd522011-01-18 07:41:22 +00003637 // Otherwise, recurse on the array's element type.
3638 QualType elementType = AT->getElementType();
3639 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3640
3641 // If that didn't change the element type, AT has no qualifiers, so we
3642 // can just use the results in splitType.
3643 if (elementType == unqualElementType) {
3644 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003645 quals = splitType.Quals;
3646 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003647 }
3648
3649 // Otherwise, add in the qualifiers from the outermost type, then
3650 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003651 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003652
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003653 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003654 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003655 CAT->getSizeModifier(), 0);
3656 }
3657
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003658 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003659 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003660 }
3661
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003662 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003663 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003664 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003665 VAT->getSizeModifier(),
3666 VAT->getIndexTypeCVRQualifiers(),
3667 VAT->getBracketsRange());
3668 }
3669
3670 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003671 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003672 DSAT->getSizeModifier(), 0,
3673 SourceRange());
3674}
3675
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003676/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3677/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3678/// they point to and return true. If T1 and T2 aren't pointer types
3679/// or pointer-to-member types, or if they are not similar at this
3680/// level, returns false and leaves T1 and T2 unchanged. Top-level
3681/// qualifiers on T1 and T2 are ignored. This function will typically
3682/// be called in a loop that successively "unwraps" pointer and
3683/// pointer-to-member types to compare them at each level.
3684bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3685 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3686 *T2PtrType = T2->getAs<PointerType>();
3687 if (T1PtrType && T2PtrType) {
3688 T1 = T1PtrType->getPointeeType();
3689 T2 = T2PtrType->getPointeeType();
3690 return true;
3691 }
3692
3693 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3694 *T2MPType = T2->getAs<MemberPointerType>();
3695 if (T1MPType && T2MPType &&
3696 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3697 QualType(T2MPType->getClass(), 0))) {
3698 T1 = T1MPType->getPointeeType();
3699 T2 = T2MPType->getPointeeType();
3700 return true;
3701 }
3702
David Blaikiebbafb8a2012-03-11 07:00:24 +00003703 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003704 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3705 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3706 if (T1OPType && T2OPType) {
3707 T1 = T1OPType->getPointeeType();
3708 T2 = T2OPType->getPointeeType();
3709 return true;
3710 }
3711 }
3712
3713 // FIXME: Block pointers, too?
3714
3715 return false;
3716}
3717
Jay Foad39c79802011-01-12 09:06:06 +00003718DeclarationNameInfo
3719ASTContext::getNameForTemplate(TemplateName Name,
3720 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003721 switch (Name.getKind()) {
3722 case TemplateName::QualifiedTemplate:
3723 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003724 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003725 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3726 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003727
John McCalld9dfe3a2011-06-30 08:33:18 +00003728 case TemplateName::OverloadedTemplate: {
3729 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3730 // DNInfo work in progress: CHECKME: what about DNLoc?
3731 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3732 }
3733
3734 case TemplateName::DependentTemplate: {
3735 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003736 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003737 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003738 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3739 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003740 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003741 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3742 // DNInfo work in progress: FIXME: source locations?
3743 DeclarationNameLoc DNLoc;
3744 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3745 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3746 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003747 }
3748 }
3749
John McCalld9dfe3a2011-06-30 08:33:18 +00003750 case TemplateName::SubstTemplateTemplateParm: {
3751 SubstTemplateTemplateParmStorage *subst
3752 = Name.getAsSubstTemplateTemplateParm();
3753 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3754 NameLoc);
3755 }
3756
3757 case TemplateName::SubstTemplateTemplateParmPack: {
3758 SubstTemplateTemplateParmPackStorage *subst
3759 = Name.getAsSubstTemplateTemplateParmPack();
3760 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3761 NameLoc);
3762 }
3763 }
3764
3765 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003766}
3767
Jay Foad39c79802011-01-12 09:06:06 +00003768TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003769 switch (Name.getKind()) {
3770 case TemplateName::QualifiedTemplate:
3771 case TemplateName::Template: {
3772 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003773 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003774 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003775 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3776
3777 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003778 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003779 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003780
John McCalld9dfe3a2011-06-30 08:33:18 +00003781 case TemplateName::OverloadedTemplate:
3782 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003783
John McCalld9dfe3a2011-06-30 08:33:18 +00003784 case TemplateName::DependentTemplate: {
3785 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3786 assert(DTN && "Non-dependent template names must refer to template decls.");
3787 return DTN->CanonicalTemplateName;
3788 }
3789
3790 case TemplateName::SubstTemplateTemplateParm: {
3791 SubstTemplateTemplateParmStorage *subst
3792 = Name.getAsSubstTemplateTemplateParm();
3793 return getCanonicalTemplateName(subst->getReplacement());
3794 }
3795
3796 case TemplateName::SubstTemplateTemplateParmPack: {
3797 SubstTemplateTemplateParmPackStorage *subst
3798 = Name.getAsSubstTemplateTemplateParmPack();
3799 TemplateTemplateParmDecl *canonParameter
3800 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3801 TemplateArgument canonArgPack
3802 = getCanonicalTemplateArgument(subst->getArgumentPack());
3803 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3804 }
3805 }
3806
3807 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003808}
3809
Douglas Gregoradee3e32009-11-11 23:06:43 +00003810bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3811 X = getCanonicalTemplateName(X);
3812 Y = getCanonicalTemplateName(Y);
3813 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3814}
3815
Mike Stump11289f42009-09-09 15:08:12 +00003816TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003817ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003818 switch (Arg.getKind()) {
3819 case TemplateArgument::Null:
3820 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003821
Douglas Gregora8e02e72009-07-28 23:00:59 +00003822 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003823 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003824
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003825 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00003826 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
3827 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003828 }
Mike Stump11289f42009-09-09 15:08:12 +00003829
Eli Friedmanb826a002012-09-26 02:36:12 +00003830 case TemplateArgument::NullPtr:
3831 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
3832 /*isNullPtr*/true);
3833
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003834 case TemplateArgument::Template:
3835 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003836
3837 case TemplateArgument::TemplateExpansion:
3838 return TemplateArgument(getCanonicalTemplateName(
3839 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003840 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003841
Douglas Gregora8e02e72009-07-28 23:00:59 +00003842 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00003843 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003844
Douglas Gregora8e02e72009-07-28 23:00:59 +00003845 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003846 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003847
Douglas Gregora8e02e72009-07-28 23:00:59 +00003848 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003849 if (Arg.pack_size() == 0)
3850 return Arg;
3851
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003852 TemplateArgument *CanonArgs
3853 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003854 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003855 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003856 AEnd = Arg.pack_end();
3857 A != AEnd; (void)++A, ++Idx)
3858 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003859
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003860 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003861 }
3862 }
3863
3864 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003865 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003866}
3867
Douglas Gregor333489b2009-03-27 23:10:48 +00003868NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003869ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003870 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003871 return 0;
3872
3873 switch (NNS->getKind()) {
3874 case NestedNameSpecifier::Identifier:
3875 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003876 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003877 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3878 NNS->getAsIdentifier());
3879
3880 case NestedNameSpecifier::Namespace:
3881 // A namespace is canonical; build a nested-name-specifier with
3882 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003883 return NestedNameSpecifier::Create(*this, 0,
3884 NNS->getAsNamespace()->getOriginalNamespace());
3885
3886 case NestedNameSpecifier::NamespaceAlias:
3887 // A namespace is canonical; build a nested-name-specifier with
3888 // this namespace and no prefix.
3889 return NestedNameSpecifier::Create(*this, 0,
3890 NNS->getAsNamespaceAlias()->getNamespace()
3891 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003892
3893 case NestedNameSpecifier::TypeSpec:
3894 case NestedNameSpecifier::TypeSpecWithTemplate: {
3895 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003896
3897 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3898 // break it apart into its prefix and identifier, then reconsititute those
3899 // as the canonical nested-name-specifier. This is required to canonicalize
3900 // a dependent nested-name-specifier involving typedefs of dependent-name
3901 // types, e.g.,
3902 // typedef typename T::type T1;
3903 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00003904 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3905 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00003906 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003907
Eli Friedman5358a0a2012-03-03 04:09:56 +00003908 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3909 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3910 // first place?
John McCall33ddac02011-01-19 10:06:00 +00003911 return NestedNameSpecifier::Create(*this, 0, false,
3912 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003913 }
3914
3915 case NestedNameSpecifier::Global:
3916 // The global specifier is canonical and unique.
3917 return NNS;
3918 }
3919
David Blaikie8a40f702012-01-17 06:56:22 +00003920 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00003921}
3922
Chris Lattner7adf0762008-08-04 07:31:14 +00003923
Jay Foad39c79802011-01-12 09:06:06 +00003924const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003925 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003926 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003927 // Handle the common positive case fast.
3928 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3929 return AT;
3930 }
Mike Stump11289f42009-09-09 15:08:12 +00003931
John McCall8ccfcb52009-09-24 19:53:00 +00003932 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003933 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003934 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003935
John McCall8ccfcb52009-09-24 19:53:00 +00003936 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003937 // implements C99 6.7.3p8: "If the specification of an array type includes
3938 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003939
Chris Lattner7adf0762008-08-04 07:31:14 +00003940 // If we get here, we either have type qualifiers on the type, or we have
3941 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003942 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003943
John McCall33ddac02011-01-19 10:06:00 +00003944 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003945 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00003946
Chris Lattner7adf0762008-08-04 07:31:14 +00003947 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00003948 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00003949 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003950 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003951
Chris Lattner7adf0762008-08-04 07:31:14 +00003952 // Otherwise, we have an array and we have qualifiers on it. Push the
3953 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003954 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003955
Chris Lattner7adf0762008-08-04 07:31:14 +00003956 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3957 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3958 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003959 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003960 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3961 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3962 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003963 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003964
Mike Stump11289f42009-09-09 15:08:12 +00003965 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003966 = dyn_cast<DependentSizedArrayType>(ATy))
3967 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003968 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003969 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003970 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003971 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003972 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003973
Chris Lattner7adf0762008-08-04 07:31:14 +00003974 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003975 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003976 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003977 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003978 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003979 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003980}
3981
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003982QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003983 // C99 6.7.5.3p7:
3984 // A declaration of a parameter as "array of type" shall be
3985 // adjusted to "qualified pointer to type", where the type
3986 // qualifiers (if any) are those specified within the [ and ] of
3987 // the array type derivation.
3988 if (T->isArrayType())
3989 return getArrayDecayedType(T);
3990
3991 // C99 6.7.5.3p8:
3992 // A declaration of a parameter as "function returning type"
3993 // shall be adjusted to "pointer to function returning type", as
3994 // in 6.3.2.1.
3995 if (T->isFunctionType())
3996 return getPointerType(T);
3997
3998 return T;
3999}
4000
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004001QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004002 T = getVariableArrayDecayedType(T);
4003 T = getAdjustedParameterType(T);
4004 return T.getUnqualifiedType();
4005}
4006
Chris Lattnera21ad802008-04-02 05:18:44 +00004007/// getArrayDecayedType - Return the properly qualified result of decaying the
4008/// specified array type to a pointer. This operation is non-trivial when
4009/// handling typedefs etc. The canonical type of "T" must be an array type,
4010/// this returns a pointer to a properly qualified element of the array.
4011///
4012/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004013QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004014 // Get the element type with 'getAsArrayType' so that we don't lose any
4015 // typedefs in the element type of the array. This also handles propagation
4016 // of type qualifiers from the array type into the element type if present
4017 // (C99 6.7.3p8).
4018 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4019 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004020
Chris Lattner7adf0762008-08-04 07:31:14 +00004021 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004022
4023 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004024 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004025}
4026
John McCall33ddac02011-01-19 10:06:00 +00004027QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4028 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004029}
4030
John McCall33ddac02011-01-19 10:06:00 +00004031QualType ASTContext::getBaseElementType(QualType type) const {
4032 Qualifiers qs;
4033 while (true) {
4034 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004035 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004036 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004037
John McCall33ddac02011-01-19 10:06:00 +00004038 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004039 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004040 }
Mike Stump11289f42009-09-09 15:08:12 +00004041
John McCall33ddac02011-01-19 10:06:00 +00004042 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004043}
4044
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004045/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004046uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004047ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4048 uint64_t ElementCount = 1;
4049 do {
4050 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004051 CA = dyn_cast_or_null<ConstantArrayType>(
4052 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004053 } while (CA);
4054 return ElementCount;
4055}
4056
Steve Naroff0af91202007-04-27 21:51:21 +00004057/// getFloatingRank - Return a relative rank for floating point types.
4058/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004059static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004060 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004061 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004062
John McCall9dd450b2009-09-21 23:43:11 +00004063 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4064 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004065 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004066 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004067 case BuiltinType::Float: return FloatRank;
4068 case BuiltinType::Double: return DoubleRank;
4069 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004070 }
4071}
4072
Mike Stump11289f42009-09-09 15:08:12 +00004073/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4074/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004075/// 'typeDomain' is a real floating point or complex type.
4076/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004077QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4078 QualType Domain) const {
4079 FloatingRank EltRank = getFloatingRank(Size);
4080 if (Domain->isComplexType()) {
4081 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004082 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004083 case FloatRank: return FloatComplexTy;
4084 case DoubleRank: return DoubleComplexTy;
4085 case LongDoubleRank: return LongDoubleComplexTy;
4086 }
Steve Naroff0af91202007-04-27 21:51:21 +00004087 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004088
4089 assert(Domain->isRealFloatingType() && "Unknown domain!");
4090 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004091 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004092 case FloatRank: return FloatTy;
4093 case DoubleRank: return DoubleTy;
4094 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004095 }
David Blaikief47fa302012-01-17 02:30:50 +00004096 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004097}
4098
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004099/// getFloatingTypeOrder - Compare the rank of the two specified floating
4100/// point types, ignoring the domain of the type (i.e. 'double' ==
4101/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004102/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004103int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004104 FloatingRank LHSR = getFloatingRank(LHS);
4105 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004106
Chris Lattnerb90739d2008-04-06 23:38:49 +00004107 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004108 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004109 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004110 return 1;
4111 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004112}
4113
Chris Lattner76a00cf2008-04-06 22:59:24 +00004114/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4115/// routine will assert if passed a built-in type that isn't an integer or enum,
4116/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004117unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004118 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004119
Chris Lattner76a00cf2008-04-06 22:59:24 +00004120 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004121 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004122 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004123 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004124 case BuiltinType::Char_S:
4125 case BuiltinType::Char_U:
4126 case BuiltinType::SChar:
4127 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004128 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004129 case BuiltinType::Short:
4130 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004131 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004132 case BuiltinType::Int:
4133 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004134 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004135 case BuiltinType::Long:
4136 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004137 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004138 case BuiltinType::LongLong:
4139 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004140 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004141 case BuiltinType::Int128:
4142 case BuiltinType::UInt128:
4143 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004144 }
4145}
4146
Eli Friedman629ffb92009-08-20 04:21:42 +00004147/// \brief Whether this is a promotable bitfield reference according
4148/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4149///
4150/// \returns the type this bit-field will promote to, or NULL if no
4151/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004152QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004153 if (E->isTypeDependent() || E->isValueDependent())
4154 return QualType();
4155
Eli Friedman629ffb92009-08-20 04:21:42 +00004156 FieldDecl *Field = E->getBitField();
4157 if (!Field)
4158 return QualType();
4159
4160 QualType FT = Field->getType();
4161
Richard Smithcaf33902011-10-10 18:28:20 +00004162 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004163 uint64_t IntSize = getTypeSize(IntTy);
4164 // GCC extension compatibility: if the bit-field size is less than or equal
4165 // to the size of int, it gets promoted no matter what its type is.
4166 // For instance, unsigned long bf : 4 gets promoted to signed int.
4167 if (BitWidth < IntSize)
4168 return IntTy;
4169
4170 if (BitWidth == IntSize)
4171 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4172
4173 // Types bigger than int are not subject to promotions, and therefore act
4174 // like the base type.
4175 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4176 // is ridiculous.
4177 return QualType();
4178}
4179
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004180/// getPromotedIntegerType - Returns the type that Promotable will
4181/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4182/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004183QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004184 assert(!Promotable.isNull());
4185 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004186 if (const EnumType *ET = Promotable->getAs<EnumType>())
4187 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004188
4189 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4190 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4191 // (3.9.1) can be converted to a prvalue of the first of the following
4192 // types that can represent all the values of its underlying type:
4193 // int, unsigned int, long int, unsigned long int, long long int, or
4194 // unsigned long long int [...]
4195 // FIXME: Is there some better way to compute this?
4196 if (BT->getKind() == BuiltinType::WChar_S ||
4197 BT->getKind() == BuiltinType::WChar_U ||
4198 BT->getKind() == BuiltinType::Char16 ||
4199 BT->getKind() == BuiltinType::Char32) {
4200 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4201 uint64_t FromSize = getTypeSize(BT);
4202 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4203 LongLongTy, UnsignedLongLongTy };
4204 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4205 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4206 if (FromSize < ToSize ||
4207 (FromSize == ToSize &&
4208 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4209 return PromoteTypes[Idx];
4210 }
4211 llvm_unreachable("char type should fit into long long");
4212 }
4213 }
4214
4215 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004216 if (Promotable->isSignedIntegerType())
4217 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004218 uint64_t PromotableSize = getIntWidth(Promotable);
4219 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004220 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4221 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4222}
4223
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004224/// \brief Recurses in pointer/array types until it finds an objc retainable
4225/// type and returns its ownership.
4226Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4227 while (!T.isNull()) {
4228 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4229 return T.getObjCLifetime();
4230 if (T->isArrayType())
4231 T = getBaseElementType(T);
4232 else if (const PointerType *PT = T->getAs<PointerType>())
4233 T = PT->getPointeeType();
4234 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004235 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004236 else
4237 break;
4238 }
4239
4240 return Qualifiers::OCL_None;
4241}
4242
Mike Stump11289f42009-09-09 15:08:12 +00004243/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004244/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004245/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004246int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004247 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4248 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004249 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004250
Chris Lattner76a00cf2008-04-06 22:59:24 +00004251 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4252 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004253
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004254 unsigned LHSRank = getIntegerRank(LHSC);
4255 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004256
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004257 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4258 if (LHSRank == RHSRank) return 0;
4259 return LHSRank > RHSRank ? 1 : -1;
4260 }
Mike Stump11289f42009-09-09 15:08:12 +00004261
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004262 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4263 if (LHSUnsigned) {
4264 // If the unsigned [LHS] type is larger, return it.
4265 if (LHSRank >= RHSRank)
4266 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004267
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004268 // If the signed type can represent all values of the unsigned type, it
4269 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004270 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004271 return -1;
4272 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004273
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004274 // If the unsigned [RHS] type is larger, return it.
4275 if (RHSRank >= LHSRank)
4276 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004277
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004278 // If the signed type can represent all values of the unsigned type, it
4279 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004280 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004281 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004282}
Anders Carlsson98f07902007-08-17 05:31:46 +00004283
Anders Carlsson6d417272009-11-14 21:45:58 +00004284static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004285CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4286 DeclContext *DC, IdentifierInfo *Id) {
4287 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004288 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004289 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004290 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004291 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004292}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004293
Mike Stump11289f42009-09-09 15:08:12 +00004294// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004295QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004296 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00004297 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004298 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004299 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00004300 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004301
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004302 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004303
Anders Carlsson98f07902007-08-17 05:31:46 +00004304 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004305 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004306 // int flags;
4307 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004308 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004309 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004310 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004311 FieldTypes[3] = LongTy;
4312
Anders Carlsson98f07902007-08-17 05:31:46 +00004313 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004314 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004315 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004316 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004317 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00004318 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00004319 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004320 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004321 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004322 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004323 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004324 }
4325
Douglas Gregord5058122010-02-11 01:19:42 +00004326 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004327 }
Mike Stump11289f42009-09-09 15:08:12 +00004328
Anders Carlsson98f07902007-08-17 05:31:46 +00004329 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004330}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004331
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004332QualType ASTContext::getObjCSuperType() const {
4333 if (ObjCSuperType.isNull()) {
4334 RecordDecl *ObjCSuperTypeDecl =
4335 CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get("objc_super"));
4336 TUDecl->addDecl(ObjCSuperTypeDecl);
4337 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4338 }
4339 return ObjCSuperType;
4340}
4341
Douglas Gregor512b0772009-04-23 22:29:11 +00004342void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004343 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004344 assert(Rec && "Invalid CFConstantStringType");
4345 CFConstantStringTypeDecl = Rec->getDecl();
4346}
4347
Jay Foad39c79802011-01-12 09:06:06 +00004348QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004349 if (BlockDescriptorType)
4350 return getTagDeclType(BlockDescriptorType);
4351
4352 RecordDecl *T;
4353 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004354 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004355 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00004356 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004357
4358 QualType FieldTypes[] = {
4359 UnsignedLongTy,
4360 UnsignedLongTy,
4361 };
4362
4363 const char *FieldNames[] = {
4364 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004365 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004366 };
4367
4368 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004369 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00004370 SourceLocation(),
4371 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004372 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00004373 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004374 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004375 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004376 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00004377 T->addDecl(Field);
4378 }
4379
Douglas Gregord5058122010-02-11 01:19:42 +00004380 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004381
4382 BlockDescriptorType = T;
4383
4384 return getTagDeclType(BlockDescriptorType);
4385}
4386
Jay Foad39c79802011-01-12 09:06:06 +00004387QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004388 if (BlockDescriptorExtendedType)
4389 return getTagDeclType(BlockDescriptorExtendedType);
4390
4391 RecordDecl *T;
4392 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004393 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004394 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00004395 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004396
4397 QualType FieldTypes[] = {
4398 UnsignedLongTy,
4399 UnsignedLongTy,
4400 getPointerType(VoidPtrTy),
4401 getPointerType(VoidPtrTy)
4402 };
4403
4404 const char *FieldNames[] = {
4405 "reserved",
4406 "Size",
4407 "CopyFuncPtr",
4408 "DestroyFuncPtr"
4409 };
4410
4411 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004412 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004413 SourceLocation(),
4414 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004415 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004416 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004417 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004418 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004419 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004420 T->addDecl(Field);
4421 }
4422
Douglas Gregord5058122010-02-11 01:19:42 +00004423 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004424
4425 BlockDescriptorExtendedType = T;
4426
4427 return getTagDeclType(BlockDescriptorExtendedType);
4428}
4429
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004430/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4431/// requires copy/dispose. Note that this must match the logic
4432/// in buildByrefHelpers.
4433bool ASTContext::BlockRequiresCopying(QualType Ty,
4434 const VarDecl *D) {
4435 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4436 const Expr *copyExpr = getBlockVarCopyInits(D);
4437 if (!copyExpr && record->hasTrivialDestructor()) return false;
4438
Mike Stump94967902009-10-21 18:16:27 +00004439 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004440 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004441
4442 if (!Ty->isObjCRetainableType()) return false;
4443
4444 Qualifiers qs = Ty.getQualifiers();
4445
4446 // If we have lifetime, that dominates.
4447 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4448 assert(getLangOpts().ObjCAutoRefCount);
4449
4450 switch (lifetime) {
4451 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4452
4453 // These are just bits as far as the runtime is concerned.
4454 case Qualifiers::OCL_ExplicitNone:
4455 case Qualifiers::OCL_Autoreleasing:
4456 return false;
4457
4458 // Tell the runtime that this is ARC __weak, called by the
4459 // byref routines.
4460 case Qualifiers::OCL_Weak:
4461 // ARC __strong __block variables need to be retained.
4462 case Qualifiers::OCL_Strong:
4463 return true;
4464 }
4465 llvm_unreachable("fell out of lifetime switch!");
4466 }
4467 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4468 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004469}
4470
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004471bool ASTContext::getByrefLifetime(QualType Ty,
4472 Qualifiers::ObjCLifetime &LifeTime,
4473 bool &HasByrefExtendedLayout) const {
4474
4475 if (!getLangOpts().ObjC1 ||
4476 getLangOpts().getGC() != LangOptions::NonGC)
4477 return false;
4478
4479 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004480 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004481 HasByrefExtendedLayout = true;
4482 LifeTime = Qualifiers::OCL_None;
4483 }
4484 else if (getLangOpts().ObjCAutoRefCount)
4485 LifeTime = Ty.getObjCLifetime();
4486 // MRR.
4487 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4488 LifeTime = Qualifiers::OCL_ExplicitNone;
4489 else
4490 LifeTime = Qualifiers::OCL_None;
4491 return true;
4492}
4493
Douglas Gregorbab8a962011-09-08 01:46:34 +00004494TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4495 if (!ObjCInstanceTypeDecl)
4496 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4497 getTranslationUnitDecl(),
4498 SourceLocation(),
4499 SourceLocation(),
4500 &Idents.get("instancetype"),
4501 getTrivialTypeSourceInfo(getObjCIdType()));
4502 return ObjCInstanceTypeDecl;
4503}
4504
Anders Carlsson18acd442007-10-29 06:33:42 +00004505// This returns true if a type has been typedefed to BOOL:
4506// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004507static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004508 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004509 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4510 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004511
Anders Carlssond8499822007-10-29 05:01:08 +00004512 return false;
4513}
4514
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004515/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004516/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004517CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004518 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4519 return CharUnits::Zero();
4520
Ken Dyck40775002010-01-11 17:06:35 +00004521 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004522
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004523 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004524 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004525 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004526 // Treat arrays as pointers, since that's how they're passed in.
4527 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004528 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004529 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004530}
4531
4532static inline
4533std::string charUnitsToString(const CharUnits &CU) {
4534 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004535}
4536
John McCall351762c2011-02-07 10:33:21 +00004537/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004538/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004539std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4540 std::string S;
4541
David Chisnall950a9512009-11-17 19:33:30 +00004542 const BlockDecl *Decl = Expr->getBlockDecl();
4543 QualType BlockTy =
4544 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4545 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004546 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004547 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4548 BlockTy->getAs<FunctionType>()->getResultType(),
4549 S, true /*Extended*/);
4550 else
4551 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4552 S);
David Chisnall950a9512009-11-17 19:33:30 +00004553 // Compute size of all parameters.
4554 // Start with computing size of a pointer in number of bytes.
4555 // FIXME: There might(should) be a better way of doing this computation!
4556 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004557 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4558 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004559 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004560 E = Decl->param_end(); PI != E; ++PI) {
4561 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004562 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004563 if (sz.isZero())
4564 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004565 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004566 ParmOffset += sz;
4567 }
4568 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004569 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004570 // Block pointer and offset.
4571 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004572
4573 // Argument types.
4574 ParmOffset = PtrSize;
4575 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4576 Decl->param_end(); PI != E; ++PI) {
4577 ParmVarDecl *PVDecl = *PI;
4578 QualType PType = PVDecl->getOriginalType();
4579 if (const ArrayType *AT =
4580 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4581 // Use array's original type only if it has known number of
4582 // elements.
4583 if (!isa<ConstantArrayType>(AT))
4584 PType = PVDecl->getType();
4585 } else if (PType->isFunctionType())
4586 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004587 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004588 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4589 S, true /*Extended*/);
4590 else
4591 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004592 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004593 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004594 }
John McCall351762c2011-02-07 10:33:21 +00004595
4596 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004597}
4598
Douglas Gregora9d84932011-05-27 01:19:52 +00004599bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004600 std::string& S) {
4601 // Encode result type.
4602 getObjCEncodingForType(Decl->getResultType(), S);
4603 CharUnits ParmOffset;
4604 // Compute size of all parameters.
4605 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4606 E = Decl->param_end(); PI != E; ++PI) {
4607 QualType PType = (*PI)->getType();
4608 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004609 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004610 continue;
4611
David Chisnall50e4eba2010-12-30 14:05:53 +00004612 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004613 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004614 ParmOffset += sz;
4615 }
4616 S += charUnitsToString(ParmOffset);
4617 ParmOffset = CharUnits::Zero();
4618
4619 // Argument types.
4620 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4621 E = Decl->param_end(); PI != E; ++PI) {
4622 ParmVarDecl *PVDecl = *PI;
4623 QualType PType = PVDecl->getOriginalType();
4624 if (const ArrayType *AT =
4625 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4626 // Use array's original type only if it has known number of
4627 // elements.
4628 if (!isa<ConstantArrayType>(AT))
4629 PType = PVDecl->getType();
4630 } else if (PType->isFunctionType())
4631 PType = PVDecl->getType();
4632 getObjCEncodingForType(PType, S);
4633 S += charUnitsToString(ParmOffset);
4634 ParmOffset += getObjCEncodingTypeSize(PType);
4635 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004636
4637 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004638}
4639
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004640/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4641/// method parameter or return type. If Extended, include class names and
4642/// block object types.
4643void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4644 QualType T, std::string& S,
4645 bool Extended) const {
4646 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4647 getObjCEncodingForTypeQualifier(QT, S);
4648 // Encode parameter type.
4649 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4650 true /*OutermostType*/,
4651 false /*EncodingProperty*/,
4652 false /*StructField*/,
4653 Extended /*EncodeBlockParameters*/,
4654 Extended /*EncodeClassNames*/);
4655}
4656
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004657/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004658/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004659bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004660 std::string& S,
4661 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004662 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004663 // Encode return type.
4664 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4665 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004666 // Compute size of all parameters.
4667 // Start with computing size of a pointer in number of bytes.
4668 // FIXME: There might(should) be a better way of doing this computation!
4669 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004670 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004671 // The first two arguments (self and _cmd) are pointers; account for
4672 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004673 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004674 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004675 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004676 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004677 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004678 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004679 continue;
4680
Ken Dyck40775002010-01-11 17:06:35 +00004681 assert (sz.isPositive() &&
4682 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004683 ParmOffset += sz;
4684 }
Ken Dyck40775002010-01-11 17:06:35 +00004685 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004686 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004687 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004688
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004689 // Argument types.
4690 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004691 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004692 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004693 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004694 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004695 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004696 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4697 // Use array's original type only if it has known number of
4698 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004699 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004700 PType = PVDecl->getType();
4701 } else if (PType->isFunctionType())
4702 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004703 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4704 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004705 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004706 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004707 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004708
4709 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004710}
4711
Daniel Dunbar4932b362008-08-28 04:38:10 +00004712/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004713/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004714/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4715/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004716/// Property attributes are stored as a comma-delimited C string. The simple
4717/// attributes readonly and bycopy are encoded as single characters. The
4718/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4719/// encoded as single characters, followed by an identifier. Property types
4720/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004721/// these attributes are defined by the following enumeration:
4722/// @code
4723/// enum PropertyAttributes {
4724/// kPropertyReadOnly = 'R', // property is read-only.
4725/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4726/// kPropertyByref = '&', // property is a reference to the value last assigned
4727/// kPropertyDynamic = 'D', // property is dynamic
4728/// kPropertyGetter = 'G', // followed by getter selector name
4729/// kPropertySetter = 'S', // followed by setter selector name
4730/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004731/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004732/// kPropertyWeak = 'W' // 'weak' property
4733/// kPropertyStrong = 'P' // property GC'able
4734/// kPropertyNonAtomic = 'N' // property non-atomic
4735/// };
4736/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004737void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004738 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004739 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004740 // Collect information from the property implementation decl(s).
4741 bool Dynamic = false;
4742 ObjCPropertyImplDecl *SynthesizePID = 0;
4743
4744 // FIXME: Duplicated code due to poor abstraction.
4745 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004746 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004747 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4748 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004749 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004750 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004751 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004752 if (PID->getPropertyDecl() == PD) {
4753 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4754 Dynamic = true;
4755 } else {
4756 SynthesizePID = PID;
4757 }
4758 }
4759 }
4760 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004761 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004762 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004763 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004764 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004765 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004766 if (PID->getPropertyDecl() == PD) {
4767 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4768 Dynamic = true;
4769 } else {
4770 SynthesizePID = PID;
4771 }
4772 }
Mike Stump11289f42009-09-09 15:08:12 +00004773 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004774 }
4775 }
4776
4777 // FIXME: This is not very efficient.
4778 S = "T";
4779
4780 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004781 // GCC has some special rules regarding encoding of properties which
4782 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004783 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004784 true /* outermost type */,
4785 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004786
4787 if (PD->isReadOnly()) {
4788 S += ",R";
4789 } else {
4790 switch (PD->getSetterKind()) {
4791 case ObjCPropertyDecl::Assign: break;
4792 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004793 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004794 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004795 }
4796 }
4797
4798 // It really isn't clear at all what this means, since properties
4799 // are "dynamic by default".
4800 if (Dynamic)
4801 S += ",D";
4802
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004803 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4804 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004805
Daniel Dunbar4932b362008-08-28 04:38:10 +00004806 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4807 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004808 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004809 }
4810
4811 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4812 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004813 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004814 }
4815
4816 if (SynthesizePID) {
4817 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4818 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004819 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004820 }
4821
4822 // FIXME: OBJCGC: weak & strong
4823}
4824
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004825/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004826/// Another legacy compatibility encoding: 32-bit longs are encoded as
4827/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004828/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4829///
4830void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004831 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004832 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004833 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004834 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004835 else
Jay Foad39c79802011-01-12 09:06:06 +00004836 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004837 PointeeTy = IntTy;
4838 }
4839 }
4840}
4841
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004842void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004843 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004844 // We follow the behavior of gcc, expanding structures which are
4845 // directly pointed to, and expanding embedded structures. Note that
4846 // these rules are sufficient to prevent recursive encoding of the
4847 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004848 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004849 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004850}
4851
John McCall393a78d2012-12-20 02:45:14 +00004852static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
4853 BuiltinType::Kind kind) {
4854 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004855 case BuiltinType::Void: return 'v';
4856 case BuiltinType::Bool: return 'B';
4857 case BuiltinType::Char_U:
4858 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00004859 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00004860 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00004861 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00004862 case BuiltinType::UInt: return 'I';
4863 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00004864 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004865 case BuiltinType::UInt128: return 'T';
4866 case BuiltinType::ULongLong: return 'Q';
4867 case BuiltinType::Char_S:
4868 case BuiltinType::SChar: return 'c';
4869 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004870 case BuiltinType::WChar_S:
4871 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004872 case BuiltinType::Int: return 'i';
4873 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00004874 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004875 case BuiltinType::LongLong: return 'q';
4876 case BuiltinType::Int128: return 't';
4877 case BuiltinType::Float: return 'f';
4878 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004879 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00004880 case BuiltinType::NullPtr: return '*'; // like char*
4881
4882 case BuiltinType::Half:
4883 // FIXME: potentially need @encodes for these!
4884 return ' ';
4885
4886 case BuiltinType::ObjCId:
4887 case BuiltinType::ObjCClass:
4888 case BuiltinType::ObjCSel:
4889 llvm_unreachable("@encoding ObjC primitive type");
4890
4891 // OpenCL and placeholder types don't need @encodings.
4892 case BuiltinType::OCLImage1d:
4893 case BuiltinType::OCLImage1dArray:
4894 case BuiltinType::OCLImage1dBuffer:
4895 case BuiltinType::OCLImage2d:
4896 case BuiltinType::OCLImage2dArray:
4897 case BuiltinType::OCLImage3d:
4898 case BuiltinType::Dependent:
4899#define BUILTIN_TYPE(KIND, ID)
4900#define PLACEHOLDER_TYPE(KIND, ID) \
4901 case BuiltinType::KIND:
4902#include "clang/AST/BuiltinTypes.def"
4903 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00004904 }
David Blaikie5a6a0202013-01-09 17:48:41 +00004905 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00004906}
4907
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004908static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4909 EnumDecl *Enum = ET->getDecl();
4910
4911 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4912 if (!Enum->isFixed())
4913 return 'i';
4914
4915 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00004916 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
4917 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004918}
4919
Jay Foad39c79802011-01-12 09:06:06 +00004920static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004921 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00004922 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004923 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004924 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4925 // The GNU runtime requires more information; bitfields are encoded as b,
4926 // then the offset (in bits) of the first element, then the type of the
4927 // bitfield, then the size in bits. For example, in this structure:
4928 //
4929 // struct
4930 // {
4931 // int integer;
4932 // int flags:2;
4933 // };
4934 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4935 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4936 // information is not especially sensible, but we're stuck with it for
4937 // compatibility with GCC, although providing it breaks anything that
4938 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00004939 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004940 const RecordDecl *RD = FD->getParent();
4941 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004942 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004943 if (const EnumType *ET = T->getAs<EnumType>())
4944 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00004945 else {
4946 const BuiltinType *BT = T->castAs<BuiltinType>();
4947 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
4948 }
David Chisnallb190a2c2010-06-04 01:10:52 +00004949 }
Richard Smithcaf33902011-10-10 18:28:20 +00004950 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004951}
4952
Daniel Dunbar07d07852009-10-18 21:17:35 +00004953// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004954void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4955 bool ExpandPointedToStructures,
4956 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004957 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004958 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004959 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004960 bool StructField,
4961 bool EncodeBlockParameters,
4962 bool EncodeClassNames) const {
John McCall393a78d2012-12-20 02:45:14 +00004963 CanQualType CT = getCanonicalType(T);
4964 switch (CT->getTypeClass()) {
4965 case Type::Builtin:
4966 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00004967 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004968 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00004969 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
4970 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
4971 else
4972 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00004973 return;
Mike Stump11289f42009-09-09 15:08:12 +00004974
John McCall393a78d2012-12-20 02:45:14 +00004975 case Type::Complex: {
4976 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00004977 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004978 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004979 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004980 return;
4981 }
John McCall393a78d2012-12-20 02:45:14 +00004982
4983 case Type::Atomic: {
4984 const AtomicType *AT = T->castAs<AtomicType>();
4985 S += 'A';
4986 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
4987 false, false);
4988 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004989 }
John McCall393a78d2012-12-20 02:45:14 +00004990
4991 // encoding for pointer or reference types.
4992 case Type::Pointer:
4993 case Type::LValueReference:
4994 case Type::RValueReference: {
4995 QualType PointeeTy;
4996 if (isa<PointerType>(CT)) {
4997 const PointerType *PT = T->castAs<PointerType>();
4998 if (PT->isObjCSelType()) {
4999 S += ':';
5000 return;
5001 }
5002 PointeeTy = PT->getPointeeType();
5003 } else {
5004 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5005 }
5006
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005007 bool isReadOnly = false;
5008 // For historical/compatibility reasons, the read-only qualifier of the
5009 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5010 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005011 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005012 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005013 if (OutermostType && T.isConstQualified()) {
5014 isReadOnly = true;
5015 S += 'r';
5016 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005017 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005018 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005019 while (P->getAs<PointerType>())
5020 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005021 if (P.isConstQualified()) {
5022 isReadOnly = true;
5023 S += 'r';
5024 }
5025 }
5026 if (isReadOnly) {
5027 // Another legacy compatibility encoding. Some ObjC qualifier and type
5028 // combinations need to be rearranged.
5029 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005030 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005031 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005032 }
Mike Stump11289f42009-09-09 15:08:12 +00005033
Anders Carlssond8499822007-10-29 05:01:08 +00005034 if (PointeeTy->isCharType()) {
5035 // char pointer types should be encoded as '*' unless it is a
5036 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005037 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005038 S += '*';
5039 return;
5040 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005041 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005042 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5043 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5044 S += '#';
5045 return;
5046 }
5047 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5048 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5049 S += '@';
5050 return;
5051 }
5052 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005053 }
Anders Carlssond8499822007-10-29 05:01:08 +00005054 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005055 getLegacyIntegralTypeEncoding(PointeeTy);
5056
Mike Stump11289f42009-09-09 15:08:12 +00005057 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005058 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005059 return;
5060 }
John McCall393a78d2012-12-20 02:45:14 +00005061
5062 case Type::ConstantArray:
5063 case Type::IncompleteArray:
5064 case Type::VariableArray: {
5065 const ArrayType *AT = cast<ArrayType>(CT);
5066
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005067 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005068 // Incomplete arrays are encoded as a pointer to the array element.
5069 S += '^';
5070
Mike Stump11289f42009-09-09 15:08:12 +00005071 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005072 false, ExpandStructures, FD);
5073 } else {
5074 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005075
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005076 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
5077 if (getTypeSize(CAT->getElementType()) == 0)
5078 S += '0';
5079 else
5080 S += llvm::utostr(CAT->getSize().getZExtValue());
5081 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005082 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005083 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5084 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005085 S += '0';
5086 }
Mike Stump11289f42009-09-09 15:08:12 +00005087
5088 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005089 false, ExpandStructures, FD);
5090 S += ']';
5091 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005092 return;
5093 }
Mike Stump11289f42009-09-09 15:08:12 +00005094
John McCall393a78d2012-12-20 02:45:14 +00005095 case Type::FunctionNoProto:
5096 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005097 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005098 return;
Mike Stump11289f42009-09-09 15:08:12 +00005099
John McCall393a78d2012-12-20 02:45:14 +00005100 case Type::Record: {
5101 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005102 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005103 // Anonymous structures print as '?'
5104 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5105 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005106 if (ClassTemplateSpecializationDecl *Spec
5107 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5108 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
5109 std::string TemplateArgsStr
5110 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005111 TemplateArgs.data(),
5112 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005113 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005114
5115 S += TemplateArgsStr;
5116 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005117 } else {
5118 S += '?';
5119 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005120 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005121 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005122 if (!RDecl->isUnion()) {
5123 getObjCEncodingForStructureImpl(RDecl, S, FD);
5124 } else {
5125 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5126 FieldEnd = RDecl->field_end();
5127 Field != FieldEnd; ++Field) {
5128 if (FD) {
5129 S += '"';
5130 S += Field->getNameAsString();
5131 S += '"';
5132 }
Mike Stump11289f42009-09-09 15:08:12 +00005133
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005134 // Special case bit-fields.
5135 if (Field->isBitField()) {
5136 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00005137 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005138 } else {
5139 QualType qt = Field->getType();
5140 getLegacyIntegralTypeEncoding(qt);
5141 getObjCEncodingForTypeImpl(qt, S, false, true,
5142 FD, /*OutermostType*/false,
5143 /*EncodingProperty*/false,
5144 /*StructField*/true);
5145 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005146 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005147 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005148 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005149 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005150 return;
5151 }
Mike Stump11289f42009-09-09 15:08:12 +00005152
John McCall393a78d2012-12-20 02:45:14 +00005153 case Type::BlockPointer: {
5154 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005155 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005156 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005157 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005158
5159 S += '<';
5160 // Block return type
5161 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5162 ExpandPointedToStructures, ExpandStructures,
5163 FD,
5164 false /* OutermostType */,
5165 EncodingProperty,
5166 false /* StructField */,
5167 EncodeBlockParameters,
5168 EncodeClassNames);
5169 // Block self
5170 S += "@?";
5171 // Block parameters
5172 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5173 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5174 E = FPT->arg_type_end(); I && (I != E); ++I) {
5175 getObjCEncodingForTypeImpl(*I, S,
5176 ExpandPointedToStructures,
5177 ExpandStructures,
5178 FD,
5179 false /* OutermostType */,
5180 EncodingProperty,
5181 false /* StructField */,
5182 EncodeBlockParameters,
5183 EncodeClassNames);
5184 }
5185 }
5186 S += '>';
5187 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005188 return;
5189 }
Mike Stump11289f42009-09-09 15:08:12 +00005190
John McCall393a78d2012-12-20 02:45:14 +00005191 case Type::ObjCObject:
5192 case Type::ObjCInterface: {
5193 // Ignore protocol qualifiers when mangling at this level.
5194 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCall8b07ec22010-05-15 11:32:37 +00005195
John McCall393a78d2012-12-20 02:45:14 +00005196 // The assumption seems to be that this assert will succeed
5197 // because nested levels will have filtered out 'id' and 'Class'.
5198 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005199 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005200 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005201 S += '{';
5202 const IdentifierInfo *II = OI->getIdentifier();
5203 S += II->getName();
5204 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005205 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005206 DeepCollectObjCIvars(OI, true, Ivars);
5207 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005208 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005209 if (Field->isBitField())
5210 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005211 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005212 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005213 }
5214 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005215 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005216 }
Mike Stump11289f42009-09-09 15:08:12 +00005217
John McCall393a78d2012-12-20 02:45:14 +00005218 case Type::ObjCObjectPointer: {
5219 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005220 if (OPT->isObjCIdType()) {
5221 S += '@';
5222 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005223 }
Mike Stump11289f42009-09-09 15:08:12 +00005224
Steve Narofff0c86112009-10-28 22:03:49 +00005225 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5226 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5227 // Since this is a binary compatibility issue, need to consult with runtime
5228 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005229 S += '#';
5230 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005231 }
Mike Stump11289f42009-09-09 15:08:12 +00005232
Chris Lattnere7cabb92009-07-13 00:10:46 +00005233 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005234 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005235 ExpandPointedToStructures,
5236 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005237 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005238 // Note that we do extended encoding of protocol qualifer list
5239 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005240 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00005241 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5242 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005243 S += '<';
5244 S += (*I)->getNameAsString();
5245 S += '>';
5246 }
5247 S += '"';
5248 }
5249 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005250 }
Mike Stump11289f42009-09-09 15:08:12 +00005251
Chris Lattnere7cabb92009-07-13 00:10:46 +00005252 QualType PointeeTy = OPT->getPointeeType();
5253 if (!EncodingProperty &&
5254 isa<TypedefType>(PointeeTy.getTypePtr())) {
5255 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005256 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005257 // {...};
5258 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00005259 getObjCEncodingForTypeImpl(PointeeTy, S,
5260 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00005261 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005262 return;
5263 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005264
5265 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005266 if (OPT->getInterfaceDecl() &&
5267 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005268 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005269 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00005270 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5271 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005272 S += '<';
5273 S += (*I)->getNameAsString();
5274 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005275 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005276 S += '"';
5277 }
5278 return;
5279 }
Mike Stump11289f42009-09-09 15:08:12 +00005280
John McCalla9e6e8d2010-05-17 23:56:34 +00005281 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005282 // FIXME: we shoul do better than that. 'M' is available.
5283 case Type::MemberPointer:
John McCalla9e6e8d2010-05-17 23:56:34 +00005284 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005285
John McCall393a78d2012-12-20 02:45:14 +00005286 case Type::Vector:
5287 case Type::ExtVector:
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005288 // This matches gcc's encoding, even though technically it is
5289 // insufficient.
5290 // FIXME. We should do a better job than gcc.
5291 return;
John McCall393a78d2012-12-20 02:45:14 +00005292
5293#define ABSTRACT_TYPE(KIND, BASE)
5294#define TYPE(KIND, BASE)
5295#define DEPENDENT_TYPE(KIND, BASE) \
5296 case Type::KIND:
5297#define NON_CANONICAL_TYPE(KIND, BASE) \
5298 case Type::KIND:
5299#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5300 case Type::KIND:
5301#include "clang/AST/TypeNodes.def"
5302 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005303 }
John McCall393a78d2012-12-20 02:45:14 +00005304 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005305}
5306
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005307void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5308 std::string &S,
5309 const FieldDecl *FD,
5310 bool includeVBases) const {
5311 assert(RDecl && "Expected non-null RecordDecl");
5312 assert(!RDecl->isUnion() && "Should not be called for unions");
5313 if (!RDecl->getDefinition())
5314 return;
5315
5316 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5317 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5318 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5319
5320 if (CXXRec) {
5321 for (CXXRecordDecl::base_class_iterator
5322 BI = CXXRec->bases_begin(),
5323 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5324 if (!BI->isVirtual()) {
5325 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005326 if (base->isEmpty())
5327 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005328 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005329 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5330 std::make_pair(offs, base));
5331 }
5332 }
5333 }
5334
5335 unsigned i = 0;
5336 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5337 FieldEnd = RDecl->field_end();
5338 Field != FieldEnd; ++Field, ++i) {
5339 uint64_t offs = layout.getFieldOffset(i);
5340 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00005341 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005342 }
5343
5344 if (CXXRec && includeVBases) {
5345 for (CXXRecordDecl::base_class_iterator
5346 BI = CXXRec->vbases_begin(),
5347 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5348 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005349 if (base->isEmpty())
5350 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005351 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005352 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5353 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5354 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005355 }
5356 }
5357
5358 CharUnits size;
5359 if (CXXRec) {
5360 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5361 } else {
5362 size = layout.getSize();
5363 }
5364
5365 uint64_t CurOffs = 0;
5366 std::multimap<uint64_t, NamedDecl *>::iterator
5367 CurLayObj = FieldOrBaseOffsets.begin();
5368
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005369 if (CXXRec && CXXRec->isDynamicClass() &&
5370 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005371 if (FD) {
5372 S += "\"_vptr$";
5373 std::string recname = CXXRec->getNameAsString();
5374 if (recname.empty()) recname = "?";
5375 S += recname;
5376 S += '"';
5377 }
5378 S += "^^?";
5379 CurOffs += getTypeSize(VoidPtrTy);
5380 }
5381
5382 if (!RDecl->hasFlexibleArrayMember()) {
5383 // Mark the end of the structure.
5384 uint64_t offs = toBits(size);
5385 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5386 std::make_pair(offs, (NamedDecl*)0));
5387 }
5388
5389 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5390 assert(CurOffs <= CurLayObj->first);
5391
5392 if (CurOffs < CurLayObj->first) {
5393 uint64_t padding = CurLayObj->first - CurOffs;
5394 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5395 // packing/alignment of members is different that normal, in which case
5396 // the encoding will be out-of-sync with the real layout.
5397 // If the runtime switches to just consider the size of types without
5398 // taking into account alignment, we could make padding explicit in the
5399 // encoding (e.g. using arrays of chars). The encoding strings would be
5400 // longer then though.
5401 CurOffs += padding;
5402 }
5403
5404 NamedDecl *dcl = CurLayObj->second;
5405 if (dcl == 0)
5406 break; // reached end of structure.
5407
5408 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5409 // We expand the bases without their virtual bases since those are going
5410 // in the initial structure. Note that this differs from gcc which
5411 // expands virtual bases each time one is encountered in the hierarchy,
5412 // making the encoding type bigger than it really is.
5413 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005414 assert(!base->isEmpty());
5415 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005416 } else {
5417 FieldDecl *field = cast<FieldDecl>(dcl);
5418 if (FD) {
5419 S += '"';
5420 S += field->getNameAsString();
5421 S += '"';
5422 }
5423
5424 if (field->isBitField()) {
5425 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00005426 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005427 } else {
5428 QualType qt = field->getType();
5429 getLegacyIntegralTypeEncoding(qt);
5430 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5431 /*OutermostType*/false,
5432 /*EncodingProperty*/false,
5433 /*StructField*/true);
5434 CurOffs += getTypeSize(field->getType());
5435 }
5436 }
5437 }
5438}
5439
Mike Stump11289f42009-09-09 15:08:12 +00005440void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005441 std::string& S) const {
5442 if (QT & Decl::OBJC_TQ_In)
5443 S += 'n';
5444 if (QT & Decl::OBJC_TQ_Inout)
5445 S += 'N';
5446 if (QT & Decl::OBJC_TQ_Out)
5447 S += 'o';
5448 if (QT & Decl::OBJC_TQ_Bycopy)
5449 S += 'O';
5450 if (QT & Decl::OBJC_TQ_Byref)
5451 S += 'R';
5452 if (QT & Decl::OBJC_TQ_Oneway)
5453 S += 'V';
5454}
5455
Douglas Gregor3ea72692011-08-12 05:46:01 +00005456TypedefDecl *ASTContext::getObjCIdDecl() const {
5457 if (!ObjCIdDecl) {
5458 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5459 T = getObjCObjectPointerType(T);
5460 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5461 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5462 getTranslationUnitDecl(),
5463 SourceLocation(), SourceLocation(),
5464 &Idents.get("id"), IdInfo);
5465 }
5466
5467 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005468}
5469
Douglas Gregor52e02802011-08-12 06:17:30 +00005470TypedefDecl *ASTContext::getObjCSelDecl() const {
5471 if (!ObjCSelDecl) {
5472 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5473 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5474 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5475 getTranslationUnitDecl(),
5476 SourceLocation(), SourceLocation(),
5477 &Idents.get("SEL"), SelInfo);
5478 }
5479 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005480}
5481
Douglas Gregor0a586182011-08-12 05:59:41 +00005482TypedefDecl *ASTContext::getObjCClassDecl() const {
5483 if (!ObjCClassDecl) {
5484 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5485 T = getObjCObjectPointerType(T);
5486 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5487 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5488 getTranslationUnitDecl(),
5489 SourceLocation(), SourceLocation(),
5490 &Idents.get("Class"), ClassInfo);
5491 }
5492
5493 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005494}
5495
Douglas Gregord53ae832012-01-17 18:09:05 +00005496ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5497 if (!ObjCProtocolClassDecl) {
5498 ObjCProtocolClassDecl
5499 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5500 SourceLocation(),
5501 &Idents.get("Protocol"),
5502 /*PrevDecl=*/0,
5503 SourceLocation(), true);
5504 }
5505
5506 return ObjCProtocolClassDecl;
5507}
5508
Meador Inge5d3fb222012-06-16 03:34:49 +00005509//===----------------------------------------------------------------------===//
5510// __builtin_va_list Construction Functions
5511//===----------------------------------------------------------------------===//
5512
5513static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5514 // typedef char* __builtin_va_list;
5515 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5516 TypeSourceInfo *TInfo
5517 = Context->getTrivialTypeSourceInfo(CharPtrType);
5518
5519 TypedefDecl *VaListTypeDecl
5520 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5521 Context->getTranslationUnitDecl(),
5522 SourceLocation(), SourceLocation(),
5523 &Context->Idents.get("__builtin_va_list"),
5524 TInfo);
5525 return VaListTypeDecl;
5526}
5527
5528static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5529 // typedef void* __builtin_va_list;
5530 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5531 TypeSourceInfo *TInfo
5532 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5533
5534 TypedefDecl *VaListTypeDecl
5535 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5536 Context->getTranslationUnitDecl(),
5537 SourceLocation(), SourceLocation(),
5538 &Context->Idents.get("__builtin_va_list"),
5539 TInfo);
5540 return VaListTypeDecl;
5541}
5542
5543static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5544 // typedef struct __va_list_tag {
5545 RecordDecl *VaListTagDecl;
5546
5547 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5548 Context->getTranslationUnitDecl(),
5549 &Context->Idents.get("__va_list_tag"));
5550 VaListTagDecl->startDefinition();
5551
5552 const size_t NumFields = 5;
5553 QualType FieldTypes[NumFields];
5554 const char *FieldNames[NumFields];
5555
5556 // unsigned char gpr;
5557 FieldTypes[0] = Context->UnsignedCharTy;
5558 FieldNames[0] = "gpr";
5559
5560 // unsigned char fpr;
5561 FieldTypes[1] = Context->UnsignedCharTy;
5562 FieldNames[1] = "fpr";
5563
5564 // unsigned short reserved;
5565 FieldTypes[2] = Context->UnsignedShortTy;
5566 FieldNames[2] = "reserved";
5567
5568 // void* overflow_arg_area;
5569 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5570 FieldNames[3] = "overflow_arg_area";
5571
5572 // void* reg_save_area;
5573 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5574 FieldNames[4] = "reg_save_area";
5575
5576 // Create fields
5577 for (unsigned i = 0; i < NumFields; ++i) {
5578 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5579 SourceLocation(),
5580 SourceLocation(),
5581 &Context->Idents.get(FieldNames[i]),
5582 FieldTypes[i], /*TInfo=*/0,
5583 /*BitWidth=*/0,
5584 /*Mutable=*/false,
5585 ICIS_NoInit);
5586 Field->setAccess(AS_public);
5587 VaListTagDecl->addDecl(Field);
5588 }
5589 VaListTagDecl->completeDefinition();
5590 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005591 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005592
5593 // } __va_list_tag;
5594 TypedefDecl *VaListTagTypedefDecl
5595 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5596 Context->getTranslationUnitDecl(),
5597 SourceLocation(), SourceLocation(),
5598 &Context->Idents.get("__va_list_tag"),
5599 Context->getTrivialTypeSourceInfo(VaListTagType));
5600 QualType VaListTagTypedefType =
5601 Context->getTypedefType(VaListTagTypedefDecl);
5602
5603 // typedef __va_list_tag __builtin_va_list[1];
5604 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5605 QualType VaListTagArrayType
5606 = Context->getConstantArrayType(VaListTagTypedefType,
5607 Size, ArrayType::Normal, 0);
5608 TypeSourceInfo *TInfo
5609 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5610 TypedefDecl *VaListTypedefDecl
5611 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5612 Context->getTranslationUnitDecl(),
5613 SourceLocation(), SourceLocation(),
5614 &Context->Idents.get("__builtin_va_list"),
5615 TInfo);
5616
5617 return VaListTypedefDecl;
5618}
5619
5620static TypedefDecl *
5621CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5622 // typedef struct __va_list_tag {
5623 RecordDecl *VaListTagDecl;
5624 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5625 Context->getTranslationUnitDecl(),
5626 &Context->Idents.get("__va_list_tag"));
5627 VaListTagDecl->startDefinition();
5628
5629 const size_t NumFields = 4;
5630 QualType FieldTypes[NumFields];
5631 const char *FieldNames[NumFields];
5632
5633 // unsigned gp_offset;
5634 FieldTypes[0] = Context->UnsignedIntTy;
5635 FieldNames[0] = "gp_offset";
5636
5637 // unsigned fp_offset;
5638 FieldTypes[1] = Context->UnsignedIntTy;
5639 FieldNames[1] = "fp_offset";
5640
5641 // void* overflow_arg_area;
5642 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5643 FieldNames[2] = "overflow_arg_area";
5644
5645 // void* reg_save_area;
5646 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5647 FieldNames[3] = "reg_save_area";
5648
5649 // Create fields
5650 for (unsigned i = 0; i < NumFields; ++i) {
5651 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5652 VaListTagDecl,
5653 SourceLocation(),
5654 SourceLocation(),
5655 &Context->Idents.get(FieldNames[i]),
5656 FieldTypes[i], /*TInfo=*/0,
5657 /*BitWidth=*/0,
5658 /*Mutable=*/false,
5659 ICIS_NoInit);
5660 Field->setAccess(AS_public);
5661 VaListTagDecl->addDecl(Field);
5662 }
5663 VaListTagDecl->completeDefinition();
5664 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005665 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005666
5667 // } __va_list_tag;
5668 TypedefDecl *VaListTagTypedefDecl
5669 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5670 Context->getTranslationUnitDecl(),
5671 SourceLocation(), SourceLocation(),
5672 &Context->Idents.get("__va_list_tag"),
5673 Context->getTrivialTypeSourceInfo(VaListTagType));
5674 QualType VaListTagTypedefType =
5675 Context->getTypedefType(VaListTagTypedefDecl);
5676
5677 // typedef __va_list_tag __builtin_va_list[1];
5678 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5679 QualType VaListTagArrayType
5680 = Context->getConstantArrayType(VaListTagTypedefType,
5681 Size, ArrayType::Normal,0);
5682 TypeSourceInfo *TInfo
5683 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5684 TypedefDecl *VaListTypedefDecl
5685 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5686 Context->getTranslationUnitDecl(),
5687 SourceLocation(), SourceLocation(),
5688 &Context->Idents.get("__builtin_va_list"),
5689 TInfo);
5690
5691 return VaListTypedefDecl;
5692}
5693
5694static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5695 // typedef int __builtin_va_list[4];
5696 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5697 QualType IntArrayType
5698 = Context->getConstantArrayType(Context->IntTy,
5699 Size, ArrayType::Normal, 0);
5700 TypedefDecl *VaListTypedefDecl
5701 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5702 Context->getTranslationUnitDecl(),
5703 SourceLocation(), SourceLocation(),
5704 &Context->Idents.get("__builtin_va_list"),
5705 Context->getTrivialTypeSourceInfo(IntArrayType));
5706
5707 return VaListTypedefDecl;
5708}
5709
Logan Chien57086ce2012-10-10 06:56:20 +00005710static TypedefDecl *
5711CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
5712 RecordDecl *VaListDecl;
5713 if (Context->getLangOpts().CPlusPlus) {
5714 // namespace std { struct __va_list {
5715 NamespaceDecl *NS;
5716 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5717 Context->getTranslationUnitDecl(),
5718 /*Inline*/false, SourceLocation(),
5719 SourceLocation(), &Context->Idents.get("std"),
5720 /*PrevDecl*/0);
5721
5722 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5723 Context->getTranslationUnitDecl(),
5724 SourceLocation(), SourceLocation(),
5725 &Context->Idents.get("__va_list"));
5726
5727 VaListDecl->setDeclContext(NS);
5728
5729 } else {
5730 // struct __va_list {
5731 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
5732 Context->getTranslationUnitDecl(),
5733 &Context->Idents.get("__va_list"));
5734 }
5735
5736 VaListDecl->startDefinition();
5737
5738 // void * __ap;
5739 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5740 VaListDecl,
5741 SourceLocation(),
5742 SourceLocation(),
5743 &Context->Idents.get("__ap"),
5744 Context->getPointerType(Context->VoidTy),
5745 /*TInfo=*/0,
5746 /*BitWidth=*/0,
5747 /*Mutable=*/false,
5748 ICIS_NoInit);
5749 Field->setAccess(AS_public);
5750 VaListDecl->addDecl(Field);
5751
5752 // };
5753 VaListDecl->completeDefinition();
5754
5755 // typedef struct __va_list __builtin_va_list;
5756 TypeSourceInfo *TInfo
5757 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
5758
5759 TypedefDecl *VaListTypeDecl
5760 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5761 Context->getTranslationUnitDecl(),
5762 SourceLocation(), SourceLocation(),
5763 &Context->Idents.get("__builtin_va_list"),
5764 TInfo);
5765
5766 return VaListTypeDecl;
5767}
5768
Meador Inge5d3fb222012-06-16 03:34:49 +00005769static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5770 TargetInfo::BuiltinVaListKind Kind) {
5771 switch (Kind) {
5772 case TargetInfo::CharPtrBuiltinVaList:
5773 return CreateCharPtrBuiltinVaListDecl(Context);
5774 case TargetInfo::VoidPtrBuiltinVaList:
5775 return CreateVoidPtrBuiltinVaListDecl(Context);
5776 case TargetInfo::PowerABIBuiltinVaList:
5777 return CreatePowerABIBuiltinVaListDecl(Context);
5778 case TargetInfo::X86_64ABIBuiltinVaList:
5779 return CreateX86_64ABIBuiltinVaListDecl(Context);
5780 case TargetInfo::PNaClABIBuiltinVaList:
5781 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00005782 case TargetInfo::AAPCSABIBuiltinVaList:
5783 return CreateAAPCSABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00005784 }
5785
5786 llvm_unreachable("Unhandled __builtin_va_list type kind");
5787}
5788
5789TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5790 if (!BuiltinVaListDecl)
5791 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5792
5793 return BuiltinVaListDecl;
5794}
5795
Meador Ingecfb60902012-07-01 15:57:25 +00005796QualType ASTContext::getVaListTagType() const {
5797 // Force the creation of VaListTagTy by building the __builtin_va_list
5798 // declaration.
5799 if (VaListTagTy.isNull())
5800 (void) getBuiltinVaListDecl();
5801
5802 return VaListTagTy;
5803}
5804
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005805void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00005806 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00005807 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00005808
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005809 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00005810}
5811
John McCalld28ae272009-12-02 08:04:21 +00005812/// \brief Retrieve the template name that corresponds to a non-empty
5813/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00005814TemplateName
5815ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5816 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00005817 unsigned size = End - Begin;
5818 assert(size > 1 && "set is not overloaded!");
5819
5820 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5821 size * sizeof(FunctionTemplateDecl*));
5822 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5823
5824 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00005825 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00005826 NamedDecl *D = *I;
5827 assert(isa<FunctionTemplateDecl>(D) ||
5828 (isa<UsingShadowDecl>(D) &&
5829 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5830 *Storage++ = D;
5831 }
5832
5833 return TemplateName(OT);
5834}
5835
Douglas Gregordc572a32009-03-30 22:58:21 +00005836/// \brief Retrieve the template name that represents a qualified
5837/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00005838TemplateName
5839ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5840 bool TemplateKeyword,
5841 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00005842 assert(NNS && "Missing nested-name-specifier in qualified template name");
5843
Douglas Gregorc42075a2010-02-04 18:10:26 +00005844 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00005845 llvm::FoldingSetNodeID ID;
5846 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5847
5848 void *InsertPos = 0;
5849 QualifiedTemplateName *QTN =
5850 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5851 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00005852 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
5853 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00005854 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5855 }
5856
5857 return TemplateName(QTN);
5858}
5859
5860/// \brief Retrieve the template name that represents a dependent
5861/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00005862TemplateName
5863ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5864 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00005865 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00005866 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00005867
5868 llvm::FoldingSetNodeID ID;
5869 DependentTemplateName::Profile(ID, NNS, Name);
5870
5871 void *InsertPos = 0;
5872 DependentTemplateName *QTN =
5873 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5874
5875 if (QTN)
5876 return TemplateName(QTN);
5877
5878 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5879 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00005880 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5881 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00005882 } else {
5883 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00005884 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5885 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005886 DependentTemplateName *CheckQTN =
5887 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5888 assert(!CheckQTN && "Dependent type name canonicalization broken");
5889 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00005890 }
5891
5892 DependentTemplateNames.InsertNode(QTN, InsertPos);
5893 return TemplateName(QTN);
5894}
5895
Douglas Gregor71395fa2009-11-04 00:56:37 +00005896/// \brief Retrieve the template name that represents a dependent
5897/// template name such as \c MetaFun::template operator+.
5898TemplateName
5899ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00005900 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00005901 assert((!NNS || NNS->isDependent()) &&
5902 "Nested name specifier must be dependent");
5903
5904 llvm::FoldingSetNodeID ID;
5905 DependentTemplateName::Profile(ID, NNS, Operator);
5906
5907 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00005908 DependentTemplateName *QTN
5909 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005910
5911 if (QTN)
5912 return TemplateName(QTN);
5913
5914 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5915 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00005916 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5917 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005918 } else {
5919 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00005920 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5921 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005922
5923 DependentTemplateName *CheckQTN
5924 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5925 assert(!CheckQTN && "Dependent template name canonicalization broken");
5926 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00005927 }
5928
5929 DependentTemplateNames.InsertNode(QTN, InsertPos);
5930 return TemplateName(QTN);
5931}
5932
Douglas Gregor5590be02011-01-15 06:45:20 +00005933TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00005934ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5935 TemplateName replacement) const {
5936 llvm::FoldingSetNodeID ID;
5937 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5938
5939 void *insertPos = 0;
5940 SubstTemplateTemplateParmStorage *subst
5941 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5942
5943 if (!subst) {
5944 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5945 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5946 }
5947
5948 return TemplateName(subst);
5949}
5950
5951TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00005952ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5953 const TemplateArgument &ArgPack) const {
5954 ASTContext &Self = const_cast<ASTContext &>(*this);
5955 llvm::FoldingSetNodeID ID;
5956 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5957
5958 void *InsertPos = 0;
5959 SubstTemplateTemplateParmPackStorage *Subst
5960 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5961
5962 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00005963 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00005964 ArgPack.pack_size(),
5965 ArgPack.pack_begin());
5966 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5967 }
5968
5969 return TemplateName(Subst);
5970}
5971
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005972/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00005973/// TargetInfo, produce the corresponding type. The unsigned @p Type
5974/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00005975CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005976 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00005977 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005978 case TargetInfo::SignedShort: return ShortTy;
5979 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5980 case TargetInfo::SignedInt: return IntTy;
5981 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5982 case TargetInfo::SignedLong: return LongTy;
5983 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5984 case TargetInfo::SignedLongLong: return LongLongTy;
5985 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5986 }
5987
David Blaikie83d382b2011-09-23 05:06:16 +00005988 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005989}
Ted Kremenek77c51b22008-07-24 23:58:27 +00005990
5991//===----------------------------------------------------------------------===//
5992// Type Predicates.
5993//===----------------------------------------------------------------------===//
5994
Fariborz Jahanian96207692009-02-18 21:49:28 +00005995/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5996/// garbage collection attribute.
5997///
John McCall553d45a2011-01-12 00:34:59 +00005998Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005999 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006000 return Qualifiers::GCNone;
6001
David Blaikiebbafb8a2012-03-11 07:00:24 +00006002 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006003 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6004
6005 // Default behaviour under objective-C's gc is for ObjC pointers
6006 // (or pointers to them) be treated as though they were declared
6007 // as __strong.
6008 if (GCAttrs == Qualifiers::GCNone) {
6009 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6010 return Qualifiers::Strong;
6011 else if (Ty->isPointerType())
6012 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6013 } else {
6014 // It's not valid to set GC attributes on anything that isn't a
6015 // pointer.
6016#ifndef NDEBUG
6017 QualType CT = Ty->getCanonicalTypeInternal();
6018 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6019 CT = AT->getElementType();
6020 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6021#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006022 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006023 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006024}
6025
Chris Lattner49af6a42008-04-07 06:51:04 +00006026//===----------------------------------------------------------------------===//
6027// Type Compatibility Testing
6028//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006029
Mike Stump11289f42009-09-09 15:08:12 +00006030/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006031/// compatible.
6032static bool areCompatVectorTypes(const VectorType *LHS,
6033 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006034 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006035 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006036 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006037}
6038
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006039bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6040 QualType SecondVec) {
6041 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6042 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6043
6044 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6045 return true;
6046
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006047 // Treat Neon vector types and most AltiVec vector types as if they are the
6048 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006049 const VectorType *First = FirstVec->getAs<VectorType>();
6050 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006051 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006052 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006053 First->getVectorKind() != VectorType::AltiVecPixel &&
6054 First->getVectorKind() != VectorType::AltiVecBool &&
6055 Second->getVectorKind() != VectorType::AltiVecPixel &&
6056 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006057 return true;
6058
6059 return false;
6060}
6061
Steve Naroff8e6aee52009-07-23 01:01:38 +00006062//===----------------------------------------------------------------------===//
6063// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6064//===----------------------------------------------------------------------===//
6065
6066/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6067/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006068bool
6069ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6070 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006071 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006072 return true;
6073 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6074 E = rProto->protocol_end(); PI != E; ++PI)
6075 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6076 return true;
6077 return false;
6078}
6079
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006080/// QualifiedIdConformsQualifiedId - compare id<pr,...> with id<pr1,...>
Steve Naroff8e6aee52009-07-23 01:01:38 +00006081/// return true if lhs's protocols conform to rhs's protocol; false
6082/// otherwise.
6083bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
6084 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
6085 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
6086 return false;
6087}
6088
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006089/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6090/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006091bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6092 QualType rhs) {
6093 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6094 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6095 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6096
6097 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6098 E = lhsQID->qual_end(); I != E; ++I) {
6099 bool match = false;
6100 ObjCProtocolDecl *lhsProto = *I;
6101 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6102 E = rhsOPT->qual_end(); J != E; ++J) {
6103 ObjCProtocolDecl *rhsProto = *J;
6104 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6105 match = true;
6106 break;
6107 }
6108 }
6109 if (!match)
6110 return false;
6111 }
6112 return true;
6113}
6114
Steve Naroff8e6aee52009-07-23 01:01:38 +00006115/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6116/// ObjCQualifiedIDType.
6117bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6118 bool compare) {
6119 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006120 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006121 lhs->isObjCIdType() || lhs->isObjCClassType())
6122 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006123 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006124 rhs->isObjCIdType() || rhs->isObjCClassType())
6125 return true;
6126
6127 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006128 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006129
Steve Naroff8e6aee52009-07-23 01:01:38 +00006130 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006131
Steve Naroff8e6aee52009-07-23 01:01:38 +00006132 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006133 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006134 // make sure we check the class hierarchy.
6135 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6136 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6137 E = lhsQID->qual_end(); I != E; ++I) {
6138 // when comparing an id<P> on lhs with a static type on rhs,
6139 // see if static class implements all of id's protocols, directly or
6140 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006141 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006142 return false;
6143 }
6144 }
6145 // If there are no qualifiers and no interface, we have an 'id'.
6146 return true;
6147 }
Mike Stump11289f42009-09-09 15:08:12 +00006148 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006149 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6150 E = lhsQID->qual_end(); I != E; ++I) {
6151 ObjCProtocolDecl *lhsProto = *I;
6152 bool match = false;
6153
6154 // when comparing an id<P> on lhs with a static type on rhs,
6155 // see if static class implements all of id's protocols, directly or
6156 // through its super class and categories.
6157 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6158 E = rhsOPT->qual_end(); J != E; ++J) {
6159 ObjCProtocolDecl *rhsProto = *J;
6160 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6161 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6162 match = true;
6163 break;
6164 }
6165 }
Mike Stump11289f42009-09-09 15:08:12 +00006166 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006167 // make sure we check the class hierarchy.
6168 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6169 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6170 E = lhsQID->qual_end(); I != E; ++I) {
6171 // when comparing an id<P> on lhs with a static type on rhs,
6172 // see if static class implements all of id's protocols, directly or
6173 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006174 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006175 match = true;
6176 break;
6177 }
6178 }
6179 }
6180 if (!match)
6181 return false;
6182 }
Mike Stump11289f42009-09-09 15:08:12 +00006183
Steve Naroff8e6aee52009-07-23 01:01:38 +00006184 return true;
6185 }
Mike Stump11289f42009-09-09 15:08:12 +00006186
Steve Naroff8e6aee52009-07-23 01:01:38 +00006187 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6188 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6189
Mike Stump11289f42009-09-09 15:08:12 +00006190 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006191 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006192 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006193 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6194 E = lhsOPT->qual_end(); I != E; ++I) {
6195 ObjCProtocolDecl *lhsProto = *I;
6196 bool match = false;
6197
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006198 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006199 // see if static class implements all of id's protocols, directly or
6200 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006201 // First, lhs protocols in the qualifier list must be found, direct
6202 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006203 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6204 E = rhsQID->qual_end(); J != E; ++J) {
6205 ObjCProtocolDecl *rhsProto = *J;
6206 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6207 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6208 match = true;
6209 break;
6210 }
6211 }
6212 if (!match)
6213 return false;
6214 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006215
6216 // Static class's protocols, or its super class or category protocols
6217 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6218 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6219 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6220 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6221 // This is rather dubious but matches gcc's behavior. If lhs has
6222 // no type qualifier and its class has no static protocol(s)
6223 // assume that it is mismatch.
6224 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6225 return false;
6226 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6227 LHSInheritedProtocols.begin(),
6228 E = LHSInheritedProtocols.end(); I != E; ++I) {
6229 bool match = false;
6230 ObjCProtocolDecl *lhsProto = (*I);
6231 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6232 E = rhsQID->qual_end(); J != E; ++J) {
6233 ObjCProtocolDecl *rhsProto = *J;
6234 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6235 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6236 match = true;
6237 break;
6238 }
6239 }
6240 if (!match)
6241 return false;
6242 }
6243 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006244 return true;
6245 }
6246 return false;
6247}
6248
Eli Friedman47f77112008-08-22 00:56:42 +00006249/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006250/// compatible for assignment from RHS to LHS. This handles validation of any
6251/// protocol qualifiers on the LHS or RHS.
6252///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006253bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6254 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006255 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6256 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6257
Steve Naroff1329fa02009-07-15 18:40:39 +00006258 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006259 if (LHS->isObjCUnqualifiedIdOrClass() ||
6260 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006261 return true;
6262
John McCall8b07ec22010-05-15 11:32:37 +00006263 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006264 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6265 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006266 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006267
6268 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6269 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6270 QualType(RHSOPT,0));
6271
John McCall8b07ec22010-05-15 11:32:37 +00006272 // If we have 2 user-defined types, fall into that path.
6273 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006274 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006275
Steve Naroff8e6aee52009-07-23 01:01:38 +00006276 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006277}
6278
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006279/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006280/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006281/// arguments in block literals. When passed as arguments, passing 'A*' where
6282/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6283/// not OK. For the return type, the opposite is not OK.
6284bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6285 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006286 const ObjCObjectPointerType *RHSOPT,
6287 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006288 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006289 return true;
6290
6291 if (LHSOPT->isObjCBuiltinType()) {
6292 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6293 }
6294
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006295 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006296 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6297 QualType(RHSOPT,0),
6298 false);
6299
6300 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6301 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6302 if (LHS && RHS) { // We have 2 user-defined types.
6303 if (LHS != RHS) {
6304 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006305 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006306 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006307 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006308 }
6309 else
6310 return true;
6311 }
6312 return false;
6313}
6314
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006315/// getIntersectionOfProtocols - This routine finds the intersection of set
6316/// of protocols inherited from two distinct objective-c pointer objects.
6317/// It is used to build composite qualifier list of the composite type of
6318/// the conditional expression involving two objective-c pointer objects.
6319static
6320void getIntersectionOfProtocols(ASTContext &Context,
6321 const ObjCObjectPointerType *LHSOPT,
6322 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006323 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006324
John McCall8b07ec22010-05-15 11:32:37 +00006325 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6326 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6327 assert(LHS->getInterface() && "LHS must have an interface base");
6328 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006329
6330 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6331 unsigned LHSNumProtocols = LHS->getNumProtocols();
6332 if (LHSNumProtocols > 0)
6333 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6334 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006335 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006336 Context.CollectInheritedProtocols(LHS->getInterface(),
6337 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006338 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6339 LHSInheritedProtocols.end());
6340 }
6341
6342 unsigned RHSNumProtocols = RHS->getNumProtocols();
6343 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006344 ObjCProtocolDecl **RHSProtocols =
6345 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006346 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6347 if (InheritedProtocolSet.count(RHSProtocols[i]))
6348 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006349 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006350 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006351 Context.CollectInheritedProtocols(RHS->getInterface(),
6352 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006353 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6354 RHSInheritedProtocols.begin(),
6355 E = RHSInheritedProtocols.end(); I != E; ++I)
6356 if (InheritedProtocolSet.count((*I)))
6357 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006358 }
6359}
6360
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006361/// areCommonBaseCompatible - Returns common base class of the two classes if
6362/// one found. Note that this is O'2 algorithm. But it will be called as the
6363/// last type comparison in a ?-exp of ObjC pointer types before a
6364/// warning is issued. So, its invokation is extremely rare.
6365QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006366 const ObjCObjectPointerType *Lptr,
6367 const ObjCObjectPointerType *Rptr) {
6368 const ObjCObjectType *LHS = Lptr->getObjectType();
6369 const ObjCObjectType *RHS = Rptr->getObjectType();
6370 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6371 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006372 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006373 return QualType();
6374
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006375 do {
John McCall8b07ec22010-05-15 11:32:37 +00006376 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006377 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006378 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006379 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6380
6381 QualType Result = QualType(LHS, 0);
6382 if (!Protocols.empty())
6383 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6384 Result = getObjCObjectPointerType(Result);
6385 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006386 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006387 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006388
6389 return QualType();
6390}
6391
John McCall8b07ec22010-05-15 11:32:37 +00006392bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6393 const ObjCObjectType *RHS) {
6394 assert(LHS->getInterface() && "LHS is not an interface type");
6395 assert(RHS->getInterface() && "RHS is not an interface type");
6396
Chris Lattner49af6a42008-04-07 06:51:04 +00006397 // Verify that the base decls are compatible: the RHS must be a subclass of
6398 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006399 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006400 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006401
Chris Lattner49af6a42008-04-07 06:51:04 +00006402 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6403 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006404 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006405 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006406
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006407 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6408 // more detailed analysis is required.
6409 if (RHS->getNumProtocols() == 0) {
6410 // OK, if LHS is a superclass of RHS *and*
6411 // this superclass is assignment compatible with LHS.
6412 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006413 bool IsSuperClass =
6414 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6415 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006416 // OK if conversion of LHS to SuperClass results in narrowing of types
6417 // ; i.e., SuperClass may implement at least one of the protocols
6418 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6419 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6420 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006421 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006422 // If super class has no protocols, it is not a match.
6423 if (SuperClassInheritedProtocols.empty())
6424 return false;
6425
6426 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6427 LHSPE = LHS->qual_end();
6428 LHSPI != LHSPE; LHSPI++) {
6429 bool SuperImplementsProtocol = false;
6430 ObjCProtocolDecl *LHSProto = (*LHSPI);
6431
6432 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6433 SuperClassInheritedProtocols.begin(),
6434 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6435 ObjCProtocolDecl *SuperClassProto = (*I);
6436 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6437 SuperImplementsProtocol = true;
6438 break;
6439 }
6440 }
6441 if (!SuperImplementsProtocol)
6442 return false;
6443 }
6444 return true;
6445 }
6446 return false;
6447 }
Mike Stump11289f42009-09-09 15:08:12 +00006448
John McCall8b07ec22010-05-15 11:32:37 +00006449 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6450 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00006451 LHSPI != LHSPE; LHSPI++) {
6452 bool RHSImplementsProtocol = false;
6453
6454 // If the RHS doesn't implement the protocol on the left, the types
6455 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00006456 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6457 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00006458 RHSPI != RHSPE; RHSPI++) {
6459 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006460 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00006461 break;
6462 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006463 }
6464 // FIXME: For better diagnostics, consider passing back the protocol name.
6465 if (!RHSImplementsProtocol)
6466 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006467 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006468 // The RHS implements all protocols listed on the LHS.
6469 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006470}
6471
Steve Naroffb7605152009-02-12 17:52:19 +00006472bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6473 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006474 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6475 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006476
Steve Naroff7cae42b2009-07-10 23:34:53 +00006477 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006478 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006479
6480 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6481 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006482}
6483
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006484bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6485 return canAssignObjCInterfaces(
6486 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6487 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6488}
6489
Mike Stump11289f42009-09-09 15:08:12 +00006490/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006491/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006492/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006493/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006494bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6495 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006496 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006497 return hasSameType(LHS, RHS);
6498
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006499 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006500}
6501
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006502bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006503 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006504}
6505
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006506bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6507 return !mergeTypes(LHS, RHS, true).isNull();
6508}
6509
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006510/// mergeTransparentUnionType - if T is a transparent union type and a member
6511/// of T is compatible with SubType, return the merged type, else return
6512/// QualType()
6513QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6514 bool OfBlockPointer,
6515 bool Unqualified) {
6516 if (const RecordType *UT = T->getAsUnionType()) {
6517 RecordDecl *UD = UT->getDecl();
6518 if (UD->hasAttr<TransparentUnionAttr>()) {
6519 for (RecordDecl::field_iterator it = UD->field_begin(),
6520 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00006521 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006522 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6523 if (!MT.isNull())
6524 return MT;
6525 }
6526 }
6527 }
6528
6529 return QualType();
6530}
6531
6532/// mergeFunctionArgumentTypes - merge two types which appear as function
6533/// argument types
6534QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6535 bool OfBlockPointer,
6536 bool Unqualified) {
6537 // GNU extension: two types are compatible if they appear as a function
6538 // argument, one of the types is a transparent union type and the other
6539 // type is compatible with a union member
6540 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6541 Unqualified);
6542 if (!lmerge.isNull())
6543 return lmerge;
6544
6545 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6546 Unqualified);
6547 if (!rmerge.isNull())
6548 return rmerge;
6549
6550 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6551}
6552
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006553QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006554 bool OfBlockPointer,
6555 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006556 const FunctionType *lbase = lhs->getAs<FunctionType>();
6557 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006558 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6559 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006560 bool allLTypes = true;
6561 bool allRTypes = true;
6562
6563 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006564 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006565 if (OfBlockPointer) {
6566 QualType RHS = rbase->getResultType();
6567 QualType LHS = lbase->getResultType();
6568 bool UnqualifiedResult = Unqualified;
6569 if (!UnqualifiedResult)
6570 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006571 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006572 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006573 else
John McCall8c6b56f2010-12-15 01:06:38 +00006574 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6575 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006576 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006577
6578 if (Unqualified)
6579 retType = retType.getUnqualifiedType();
6580
6581 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6582 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6583 if (Unqualified) {
6584 LRetType = LRetType.getUnqualifiedType();
6585 RRetType = RRetType.getUnqualifiedType();
6586 }
6587
6588 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006589 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006590 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006591 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006592
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006593 // FIXME: double check this
6594 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6595 // rbase->getRegParmAttr() != 0 &&
6596 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006597 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6598 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006599
Douglas Gregor8c940862010-01-18 17:14:39 +00006600 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00006601 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00006602 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006603
John McCall8c6b56f2010-12-15 01:06:38 +00006604 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006605 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6606 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006607 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6608 return QualType();
6609
John McCall31168b02011-06-15 23:02:42 +00006610 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6611 return QualType();
6612
John McCall8c6b56f2010-12-15 01:06:38 +00006613 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6614 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006615
Rafael Espindola8778c282012-11-29 16:09:03 +00006616 if (lbaseInfo.getNoReturn() != NoReturn)
6617 allLTypes = false;
6618 if (rbaseInfo.getNoReturn() != NoReturn)
6619 allRTypes = false;
6620
John McCall31168b02011-06-15 23:02:42 +00006621 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006622
Eli Friedman47f77112008-08-22 00:56:42 +00006623 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006624 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6625 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006626 unsigned lproto_nargs = lproto->getNumArgs();
6627 unsigned rproto_nargs = rproto->getNumArgs();
6628
6629 // Compatible functions must have the same number of arguments
6630 if (lproto_nargs != rproto_nargs)
6631 return QualType();
6632
6633 // Variadic and non-variadic functions aren't compatible
6634 if (lproto->isVariadic() != rproto->isVariadic())
6635 return QualType();
6636
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006637 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6638 return QualType();
6639
Fariborz Jahanian97676972011-09-28 21:52:05 +00006640 if (LangOpts.ObjCAutoRefCount &&
6641 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6642 return QualType();
6643
Eli Friedman47f77112008-08-22 00:56:42 +00006644 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006645 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00006646 for (unsigned i = 0; i < lproto_nargs; i++) {
6647 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6648 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006649 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6650 OfBlockPointer,
6651 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006652 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006653
6654 if (Unqualified)
6655 argtype = argtype.getUnqualifiedType();
6656
Eli Friedman47f77112008-08-22 00:56:42 +00006657 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006658 if (Unqualified) {
6659 largtype = largtype.getUnqualifiedType();
6660 rargtype = rargtype.getUnqualifiedType();
6661 }
6662
Chris Lattner465fa322008-10-05 17:34:18 +00006663 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6664 allLTypes = false;
6665 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6666 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006667 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006668
Eli Friedman47f77112008-08-22 00:56:42 +00006669 if (allLTypes) return lhs;
6670 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006671
6672 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6673 EPI.ExtInfo = einfo;
6674 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006675 }
6676
6677 if (lproto) allRTypes = false;
6678 if (rproto) allLTypes = false;
6679
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006680 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006681 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006682 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006683 if (proto->isVariadic()) return QualType();
6684 // Check that the types are compatible with the types that
6685 // would result from default argument promotions (C99 6.7.5.3p15).
6686 // The only types actually affected are promotable integer
6687 // types and floats, which would be passed as a different
6688 // type depending on whether the prototype is visible.
6689 unsigned proto_nargs = proto->getNumArgs();
6690 for (unsigned i = 0; i < proto_nargs; ++i) {
6691 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00006692
Eli Friedman448ce402012-08-30 00:44:15 +00006693 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00006694 // to pass enum values.
Eli Friedman448ce402012-08-30 00:44:15 +00006695 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
6696 argTy = Enum->getDecl()->getIntegerType();
6697 if (argTy.isNull())
6698 return QualType();
6699 }
Douglas Gregor2973d402010-02-03 19:27:29 +00006700
Eli Friedman47f77112008-08-22 00:56:42 +00006701 if (argTy->isPromotableIntegerType() ||
6702 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6703 return QualType();
6704 }
6705
6706 if (allLTypes) return lhs;
6707 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006708
6709 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6710 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00006711 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006712 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006713 }
6714
6715 if (allLTypes) return lhs;
6716 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00006717 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00006718}
6719
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006720QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006721 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006722 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00006723 // C++ [expr]: If an expression initially has the type "reference to T", the
6724 // type is adjusted to "T" prior to any further analysis, the expression
6725 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006726 // expression is an lvalue unless the reference is an rvalue reference and
6727 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00006728 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6729 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006730
6731 if (Unqualified) {
6732 LHS = LHS.getUnqualifiedType();
6733 RHS = RHS.getUnqualifiedType();
6734 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00006735
Eli Friedman47f77112008-08-22 00:56:42 +00006736 QualType LHSCan = getCanonicalType(LHS),
6737 RHSCan = getCanonicalType(RHS);
6738
6739 // If two types are identical, they are compatible.
6740 if (LHSCan == RHSCan)
6741 return LHS;
6742
John McCall8ccfcb52009-09-24 19:53:00 +00006743 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006744 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6745 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00006746 if (LQuals != RQuals) {
6747 // If any of these qualifiers are different, we have a type
6748 // mismatch.
6749 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00006750 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6751 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00006752 return QualType();
6753
6754 // Exactly one GC qualifier difference is allowed: __strong is
6755 // okay if the other type has no GC qualifier but is an Objective
6756 // C object pointer (i.e. implicitly strong by default). We fix
6757 // this by pretending that the unqualified type was actually
6758 // qualified __strong.
6759 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6760 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6761 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6762
6763 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6764 return QualType();
6765
6766 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6767 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6768 }
6769 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6770 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6771 }
Eli Friedman47f77112008-08-22 00:56:42 +00006772 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00006773 }
6774
6775 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00006776
Eli Friedmandcca6332009-06-01 01:22:52 +00006777 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6778 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00006779
Chris Lattnerfd652912008-01-14 05:45:46 +00006780 // We want to consider the two function types to be the same for these
6781 // comparisons, just force one to the other.
6782 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6783 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00006784
6785 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00006786 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6787 LHSClass = Type::ConstantArray;
6788 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6789 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00006790
John McCall8b07ec22010-05-15 11:32:37 +00006791 // ObjCInterfaces are just specialized ObjCObjects.
6792 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6793 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6794
Nate Begemance4d7fc2008-04-18 23:10:10 +00006795 // Canonicalize ExtVector -> Vector.
6796 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6797 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00006798
Chris Lattner95554662008-04-07 05:43:21 +00006799 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006800 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00006801 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00006802 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00006803 // Compatibility is based on the underlying type, not the promotion
6804 // type.
John McCall9dd450b2009-09-21 23:43:11 +00006805 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006806 QualType TINT = ETy->getDecl()->getIntegerType();
6807 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006808 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006809 }
John McCall9dd450b2009-09-21 23:43:11 +00006810 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006811 QualType TINT = ETy->getDecl()->getIntegerType();
6812 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006813 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006814 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006815 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00006816 if (OfBlockPointer && !BlockReturnType) {
6817 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6818 return LHS;
6819 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6820 return RHS;
6821 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006822
Eli Friedman47f77112008-08-22 00:56:42 +00006823 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00006824 }
Eli Friedman47f77112008-08-22 00:56:42 +00006825
Steve Naroffc6edcbd2008-01-09 22:43:08 +00006826 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006827 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006828#define TYPE(Class, Base)
6829#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00006830#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006831#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6832#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6833#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00006834 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006835
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006836 case Type::LValueReference:
6837 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006838 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00006839 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006840
John McCall8b07ec22010-05-15 11:32:37 +00006841 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006842 case Type::IncompleteArray:
6843 case Type::VariableArray:
6844 case Type::FunctionProto:
6845 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00006846 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006847
Chris Lattnerfd652912008-01-14 05:45:46 +00006848 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00006849 {
6850 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006851 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6852 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006853 if (Unqualified) {
6854 LHSPointee = LHSPointee.getUnqualifiedType();
6855 RHSPointee = RHSPointee.getUnqualifiedType();
6856 }
6857 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6858 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006859 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00006860 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006861 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00006862 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006863 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006864 return getPointerType(ResultType);
6865 }
Steve Naroff68e167d2008-12-10 17:49:55 +00006866 case Type::BlockPointer:
6867 {
6868 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006869 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6870 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006871 if (Unqualified) {
6872 LHSPointee = LHSPointee.getUnqualifiedType();
6873 RHSPointee = RHSPointee.getUnqualifiedType();
6874 }
6875 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6876 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00006877 if (ResultType.isNull()) return QualType();
6878 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6879 return LHS;
6880 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6881 return RHS;
6882 return getBlockPointerType(ResultType);
6883 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00006884 case Type::Atomic:
6885 {
6886 // Merge two pointer types, while trying to preserve typedef info
6887 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6888 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6889 if (Unqualified) {
6890 LHSValue = LHSValue.getUnqualifiedType();
6891 RHSValue = RHSValue.getUnqualifiedType();
6892 }
6893 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6894 Unqualified);
6895 if (ResultType.isNull()) return QualType();
6896 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6897 return LHS;
6898 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6899 return RHS;
6900 return getAtomicType(ResultType);
6901 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006902 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00006903 {
6904 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6905 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6906 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6907 return QualType();
6908
6909 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6910 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006911 if (Unqualified) {
6912 LHSElem = LHSElem.getUnqualifiedType();
6913 RHSElem = RHSElem.getUnqualifiedType();
6914 }
6915
6916 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006917 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00006918 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6919 return LHS;
6920 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6921 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00006922 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6923 ArrayType::ArraySizeModifier(), 0);
6924 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6925 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006926 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6927 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00006928 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6929 return LHS;
6930 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6931 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006932 if (LVAT) {
6933 // FIXME: This isn't correct! But tricky to implement because
6934 // the array's size has to be the size of LHS, but the type
6935 // has to be different.
6936 return LHS;
6937 }
6938 if (RVAT) {
6939 // FIXME: This isn't correct! But tricky to implement because
6940 // the array's size has to be the size of RHS, but the type
6941 // has to be different.
6942 return RHS;
6943 }
Eli Friedman3e62c212008-08-22 01:48:21 +00006944 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6945 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00006946 return getIncompleteArrayType(ResultType,
6947 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006948 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006949 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006950 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006951 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006952 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00006953 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00006954 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006955 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00006956 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00006957 case Type::Complex:
6958 // Distinct complex types are incompatible.
6959 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006960 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00006961 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00006962 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6963 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00006964 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00006965 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00006966 case Type::ObjCObject: {
6967 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00006968 // FIXME: This should be type compatibility, e.g. whether
6969 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00006970 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6971 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6972 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00006973 return LHS;
6974
Eli Friedman47f77112008-08-22 00:56:42 +00006975 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00006976 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006977 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006978 if (OfBlockPointer) {
6979 if (canAssignObjCInterfacesInBlockPointer(
6980 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006981 RHS->getAs<ObjCObjectPointerType>(),
6982 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00006983 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006984 return QualType();
6985 }
John McCall9dd450b2009-09-21 23:43:11 +00006986 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6987 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006988 return LHS;
6989
Steve Naroffc68cfcf2008-12-10 22:14:21 +00006990 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00006991 }
Steve Naroff32e44c02007-10-15 20:41:53 +00006992 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006993
David Blaikie8a40f702012-01-17 06:56:22 +00006994 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00006995}
Ted Kremenekfc581a92007-10-31 17:10:13 +00006996
Fariborz Jahanian97676972011-09-28 21:52:05 +00006997bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6998 const FunctionProtoType *FromFunctionType,
6999 const FunctionProtoType *ToFunctionType) {
7000 if (FromFunctionType->hasAnyConsumedArgs() !=
7001 ToFunctionType->hasAnyConsumedArgs())
7002 return false;
7003 FunctionProtoType::ExtProtoInfo FromEPI =
7004 FromFunctionType->getExtProtoInfo();
7005 FunctionProtoType::ExtProtoInfo ToEPI =
7006 ToFunctionType->getExtProtoInfo();
7007 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
7008 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
7009 ArgIdx != NumArgs; ++ArgIdx) {
7010 if (FromEPI.ConsumedArguments[ArgIdx] !=
7011 ToEPI.ConsumedArguments[ArgIdx])
7012 return false;
7013 }
7014 return true;
7015}
7016
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007017/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7018/// 'RHS' attributes and returns the merged version; including for function
7019/// return types.
7020QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7021 QualType LHSCan = getCanonicalType(LHS),
7022 RHSCan = getCanonicalType(RHS);
7023 // If two types are identical, they are compatible.
7024 if (LHSCan == RHSCan)
7025 return LHS;
7026 if (RHSCan->isFunctionType()) {
7027 if (!LHSCan->isFunctionType())
7028 return QualType();
7029 QualType OldReturnType =
7030 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
7031 QualType NewReturnType =
7032 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
7033 QualType ResReturnType =
7034 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7035 if (ResReturnType.isNull())
7036 return QualType();
7037 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7038 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7039 // In either case, use OldReturnType to build the new function type.
7040 const FunctionType *F = LHS->getAs<FunctionType>();
7041 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007042 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7043 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007044 QualType ResultType
7045 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00007046 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007047 return ResultType;
7048 }
7049 }
7050 return QualType();
7051 }
7052
7053 // If the qualifiers are different, the types can still be merged.
7054 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7055 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7056 if (LQuals != RQuals) {
7057 // If any of these qualifiers are different, we have a type mismatch.
7058 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7059 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7060 return QualType();
7061
7062 // Exactly one GC qualifier difference is allowed: __strong is
7063 // okay if the other type has no GC qualifier but is an Objective
7064 // C object pointer (i.e. implicitly strong by default). We fix
7065 // this by pretending that the unqualified type was actually
7066 // qualified __strong.
7067 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7068 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7069 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7070
7071 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7072 return QualType();
7073
7074 if (GC_L == Qualifiers::Strong)
7075 return LHS;
7076 if (GC_R == Qualifiers::Strong)
7077 return RHS;
7078 return QualType();
7079 }
7080
7081 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7082 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7083 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7084 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7085 if (ResQT == LHSBaseQT)
7086 return LHS;
7087 if (ResQT == RHSBaseQT)
7088 return RHS;
7089 }
7090 return QualType();
7091}
7092
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007093//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007094// Integer Predicates
7095//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007096
Jay Foad39c79802011-01-12 09:06:06 +00007097unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00007098 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00007099 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007100 if (T->isBooleanType())
7101 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007102 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007103 return (unsigned)getTypeSize(T);
7104}
7105
Abramo Bagnara13640492012-09-09 10:21:24 +00007106QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007107 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007108
7109 // Turn <4 x signed int> -> <4 x unsigned int>
7110 if (const VectorType *VTy = T->getAs<VectorType>())
7111 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007112 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007113
7114 // For enums, we return the unsigned version of the base type.
7115 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007116 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007117
7118 const BuiltinType *BTy = T->getAs<BuiltinType>();
7119 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007120 switch (BTy->getKind()) {
7121 case BuiltinType::Char_S:
7122 case BuiltinType::SChar:
7123 return UnsignedCharTy;
7124 case BuiltinType::Short:
7125 return UnsignedShortTy;
7126 case BuiltinType::Int:
7127 return UnsignedIntTy;
7128 case BuiltinType::Long:
7129 return UnsignedLongTy;
7130 case BuiltinType::LongLong:
7131 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007132 case BuiltinType::Int128:
7133 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007134 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007135 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007136 }
7137}
7138
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007139ASTMutationListener::~ASTMutationListener() { }
7140
Chris Lattnerecd79c62009-06-14 00:45:47 +00007141
7142//===----------------------------------------------------------------------===//
7143// Builtin Type Computation
7144//===----------------------------------------------------------------------===//
7145
7146/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007147/// pointer over the consumed characters. This returns the resultant type. If
7148/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7149/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7150/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007151///
7152/// RequiresICE is filled in on return to indicate whether the value is required
7153/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007154static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007155 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007156 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007157 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007158 // Modifiers.
7159 int HowLong = 0;
7160 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007161 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007162
Chris Lattnerdc226c22010-10-01 22:42:38 +00007163 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007164 bool Done = false;
7165 while (!Done) {
7166 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007167 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007168 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007169 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007170 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007171 case 'S':
7172 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7173 assert(!Signed && "Can't use 'S' modifier multiple times!");
7174 Signed = true;
7175 break;
7176 case 'U':
7177 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7178 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7179 Unsigned = true;
7180 break;
7181 case 'L':
7182 assert(HowLong <= 2 && "Can't have LLLL modifier");
7183 ++HowLong;
7184 break;
7185 }
7186 }
7187
7188 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007189
Chris Lattnerecd79c62009-06-14 00:45:47 +00007190 // Read the base type.
7191 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007192 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007193 case 'v':
7194 assert(HowLong == 0 && !Signed && !Unsigned &&
7195 "Bad modifiers used with 'v'!");
7196 Type = Context.VoidTy;
7197 break;
7198 case 'f':
7199 assert(HowLong == 0 && !Signed && !Unsigned &&
7200 "Bad modifiers used with 'f'!");
7201 Type = Context.FloatTy;
7202 break;
7203 case 'd':
7204 assert(HowLong < 2 && !Signed && !Unsigned &&
7205 "Bad modifiers used with 'd'!");
7206 if (HowLong)
7207 Type = Context.LongDoubleTy;
7208 else
7209 Type = Context.DoubleTy;
7210 break;
7211 case 's':
7212 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7213 if (Unsigned)
7214 Type = Context.UnsignedShortTy;
7215 else
7216 Type = Context.ShortTy;
7217 break;
7218 case 'i':
7219 if (HowLong == 3)
7220 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7221 else if (HowLong == 2)
7222 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7223 else if (HowLong == 1)
7224 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7225 else
7226 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7227 break;
7228 case 'c':
7229 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7230 if (Signed)
7231 Type = Context.SignedCharTy;
7232 else if (Unsigned)
7233 Type = Context.UnsignedCharTy;
7234 else
7235 Type = Context.CharTy;
7236 break;
7237 case 'b': // boolean
7238 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7239 Type = Context.BoolTy;
7240 break;
7241 case 'z': // size_t.
7242 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7243 Type = Context.getSizeType();
7244 break;
7245 case 'F':
7246 Type = Context.getCFConstantStringType();
7247 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007248 case 'G':
7249 Type = Context.getObjCIdType();
7250 break;
7251 case 'H':
7252 Type = Context.getObjCSelType();
7253 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00007254 case 'M':
7255 Type = Context.getObjCSuperType();
7256 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007257 case 'a':
7258 Type = Context.getBuiltinVaListType();
7259 assert(!Type.isNull() && "builtin va list type not initialized!");
7260 break;
7261 case 'A':
7262 // This is a "reference" to a va_list; however, what exactly
7263 // this means depends on how va_list is defined. There are two
7264 // different kinds of va_list: ones passed by value, and ones
7265 // passed by reference. An example of a by-value va_list is
7266 // x86, where va_list is a char*. An example of by-ref va_list
7267 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7268 // we want this argument to be a char*&; for x86-64, we want
7269 // it to be a __va_list_tag*.
7270 Type = Context.getBuiltinVaListType();
7271 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007272 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007273 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007274 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007275 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007276 break;
7277 case 'V': {
7278 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007279 unsigned NumElements = strtoul(Str, &End, 10);
7280 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007281 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007282
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007283 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7284 RequiresICE, false);
7285 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007286
7287 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007288 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007289 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007290 break;
7291 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007292 case 'E': {
7293 char *End;
7294
7295 unsigned NumElements = strtoul(Str, &End, 10);
7296 assert(End != Str && "Missing vector size");
7297
7298 Str = End;
7299
7300 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7301 false);
7302 Type = Context.getExtVectorType(ElementType, NumElements);
7303 break;
7304 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007305 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007306 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7307 false);
7308 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007309 Type = Context.getComplexType(ElementType);
7310 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007311 }
7312 case 'Y' : {
7313 Type = Context.getPointerDiffType();
7314 break;
7315 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007316 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007317 Type = Context.getFILEType();
7318 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007319 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007320 return QualType();
7321 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007322 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007323 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007324 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007325 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007326 else
7327 Type = Context.getjmp_bufType();
7328
Mike Stump2adb4da2009-07-28 23:47:15 +00007329 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007330 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007331 return QualType();
7332 }
7333 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007334 case 'K':
7335 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7336 Type = Context.getucontext_tType();
7337
7338 if (Type.isNull()) {
7339 Error = ASTContext::GE_Missing_ucontext;
7340 return QualType();
7341 }
7342 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00007343 case 'p':
7344 Type = Context.getProcessIDType();
7345 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007346 }
Mike Stump11289f42009-09-09 15:08:12 +00007347
Chris Lattnerdc226c22010-10-01 22:42:38 +00007348 // If there are modifiers and if we're allowed to parse them, go for it.
7349 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007350 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007351 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007352 default: Done = true; --Str; break;
7353 case '*':
7354 case '&': {
7355 // Both pointers and references can have their pointee types
7356 // qualified with an address space.
7357 char *End;
7358 unsigned AddrSpace = strtoul(Str, &End, 10);
7359 if (End != Str && AddrSpace != 0) {
7360 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7361 Str = End;
7362 }
7363 if (c == '*')
7364 Type = Context.getPointerType(Type);
7365 else
7366 Type = Context.getLValueReferenceType(Type);
7367 break;
7368 }
7369 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7370 case 'C':
7371 Type = Type.withConst();
7372 break;
7373 case 'D':
7374 Type = Context.getVolatileType(Type);
7375 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007376 case 'R':
7377 Type = Type.withRestrict();
7378 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007379 }
7380 }
Chris Lattner84733392010-10-01 07:13:18 +00007381
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007382 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007383 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007384
Chris Lattnerecd79c62009-06-14 00:45:47 +00007385 return Type;
7386}
7387
7388/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007389QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007390 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007391 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007392 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007393
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007394 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007395
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007396 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007397 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007398 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7399 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007400 if (Error != GE_None)
7401 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007402
7403 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7404
Chris Lattnerecd79c62009-06-14 00:45:47 +00007405 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007406 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007407 if (Error != GE_None)
7408 return QualType();
7409
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007410 // If this argument is required to be an IntegerConstantExpression and the
7411 // caller cares, fill in the bitmask we return.
7412 if (RequiresICE && IntegerConstantArgs)
7413 *IntegerConstantArgs |= 1 << ArgTypes.size();
7414
Chris Lattnerecd79c62009-06-14 00:45:47 +00007415 // Do array -> pointer decay. The builtin should use the decayed type.
7416 if (Ty->isArrayType())
7417 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007418
Chris Lattnerecd79c62009-06-14 00:45:47 +00007419 ArgTypes.push_back(Ty);
7420 }
7421
7422 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7423 "'.' should only occur at end of builtin type list!");
7424
John McCall991eb4b2010-12-21 00:44:39 +00007425 FunctionType::ExtInfo EI;
7426 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7427
7428 bool Variadic = (TypeStr[0] == '.');
7429
7430 // We really shouldn't be making a no-proto type here, especially in C++.
7431 if (ArgTypes.empty() && Variadic)
7432 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007433
John McCalldb40c7f2010-12-14 08:05:40 +00007434 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007435 EPI.ExtInfo = EI;
7436 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007437
7438 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007439}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007440
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007441GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
7442 GVALinkage External = GVA_StrongExternal;
7443
7444 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007445 switch (L) {
7446 case NoLinkage:
7447 case InternalLinkage:
7448 case UniqueExternalLinkage:
7449 return GVA_Internal;
7450
7451 case ExternalLinkage:
7452 switch (FD->getTemplateSpecializationKind()) {
7453 case TSK_Undeclared:
7454 case TSK_ExplicitSpecialization:
7455 External = GVA_StrongExternal;
7456 break;
7457
7458 case TSK_ExplicitInstantiationDefinition:
7459 return GVA_ExplicitTemplateInstantiation;
7460
7461 case TSK_ExplicitInstantiationDeclaration:
7462 case TSK_ImplicitInstantiation:
7463 External = GVA_TemplateInstantiation;
7464 break;
7465 }
7466 }
7467
7468 if (!FD->isInlined())
7469 return External;
7470
David Blaikiebbafb8a2012-03-11 07:00:24 +00007471 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007472 // GNU or C99 inline semantics. Determine whether this symbol should be
7473 // externally visible.
7474 if (FD->isInlineDefinitionExternallyVisible())
7475 return External;
7476
7477 // C99 inline semantics, where the symbol is not externally visible.
7478 return GVA_C99Inline;
7479 }
7480
7481 // C++0x [temp.explicit]p9:
7482 // [ Note: The intent is that an inline function that is the subject of
7483 // an explicit instantiation declaration will still be implicitly
7484 // instantiated when used so that the body can be considered for
7485 // inlining, but that no out-of-line copy of the inline function would be
7486 // generated in the translation unit. -- end note ]
7487 if (FD->getTemplateSpecializationKind()
7488 == TSK_ExplicitInstantiationDeclaration)
7489 return GVA_C99Inline;
7490
7491 return GVA_CXXInline;
7492}
7493
7494GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7495 // If this is a static data member, compute the kind of template
7496 // specialization. Otherwise, this variable is not part of a
7497 // template.
7498 TemplateSpecializationKind TSK = TSK_Undeclared;
7499 if (VD->isStaticDataMember())
7500 TSK = VD->getTemplateSpecializationKind();
7501
7502 Linkage L = VD->getLinkage();
Rafael Espindola6525f962013-01-02 04:19:07 +00007503 assert (!(L == ExternalLinkage && getLangOpts().CPlusPlus &&
7504 VD->getType()->getLinkage() == UniqueExternalLinkage));
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007505
7506 switch (L) {
7507 case NoLinkage:
7508 case InternalLinkage:
7509 case UniqueExternalLinkage:
7510 return GVA_Internal;
7511
7512 case ExternalLinkage:
7513 switch (TSK) {
7514 case TSK_Undeclared:
7515 case TSK_ExplicitSpecialization:
7516 return GVA_StrongExternal;
7517
7518 case TSK_ExplicitInstantiationDeclaration:
7519 llvm_unreachable("Variable should not be instantiated");
7520 // Fall through to treat this like any other instantiation.
7521
7522 case TSK_ExplicitInstantiationDefinition:
7523 return GVA_ExplicitTemplateInstantiation;
7524
7525 case TSK_ImplicitInstantiation:
7526 return GVA_TemplateInstantiation;
7527 }
7528 }
7529
David Blaikie8a40f702012-01-17 06:56:22 +00007530 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007531}
7532
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007533bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007534 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7535 if (!VD->isFileVarDecl())
7536 return false;
Argyrios Kyrtzidisa98e8612011-09-13 21:35:00 +00007537 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007538 return false;
7539
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007540 // Weak references don't produce any output by themselves.
7541 if (D->hasAttr<WeakRefAttr>())
7542 return false;
7543
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007544 // Aliases and used decls are required.
7545 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7546 return true;
7547
7548 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7549 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007550 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007551 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007552
7553 // Constructors and destructors are required.
7554 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7555 return true;
7556
7557 // The key function for a class is required.
7558 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7559 const CXXRecordDecl *RD = MD->getParent();
7560 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7561 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
7562 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7563 return true;
7564 }
7565 }
7566
7567 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7568
7569 // static, static inline, always_inline, and extern inline functions can
7570 // always be deferred. Normal inline functions can be deferred in C99/C++.
7571 // Implicit template instantiations can also be deferred in C++.
7572 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007573 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007574 return false;
7575 return true;
7576 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007577
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007578 const VarDecl *VD = cast<VarDecl>(D);
7579 assert(VD->isFileVarDecl() && "Expected file scoped var");
7580
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007581 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7582 return false;
7583
Richard Smitha0e5e542012-11-12 21:38:00 +00007584 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007585 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smitha0e5e542012-11-12 21:38:00 +00007586 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7587 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007588
Richard Smitha0e5e542012-11-12 21:38:00 +00007589 // Variables that have destruction with side-effects are required.
7590 if (VD->getType().isDestructedType())
7591 return true;
7592
7593 // Variables that have initialization with side-effects are required.
7594 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7595 return true;
7596
7597 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007598}
Charles Davis53c59df2010-08-16 03:33:14 +00007599
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007600CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davis99202b32010-11-09 18:04:24 +00007601 // Pass through to the C++ ABI object
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007602 return ABI->getDefaultMethodCallConv(isVariadic);
7603}
7604
7605CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
7606 if (CC == CC_C && !LangOpts.MRTD && getTargetInfo().getCXXABI() != CXXABI_Microsoft)
7607 return CC_Default;
7608 return CC;
Charles Davis99202b32010-11-09 18:04:24 +00007609}
7610
Jay Foad39c79802011-01-12 09:06:06 +00007611bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007612 // Pass through to the C++ ABI object
7613 return ABI->isNearlyEmpty(RD);
7614}
7615
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007616MangleContext *ASTContext::createMangleContext() {
Douglas Gregore8bbc122011-09-02 00:18:52 +00007617 switch (Target->getCXXABI()) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007618 case CXXABI_ARM:
7619 case CXXABI_Itanium:
7620 return createItaniumMangleContext(*this, getDiagnostics());
7621 case CXXABI_Microsoft:
7622 return createMicrosoftMangleContext(*this, getDiagnostics());
7623 }
David Blaikie83d382b2011-09-23 05:06:16 +00007624 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007625}
7626
Charles Davis53c59df2010-08-16 03:33:14 +00007627CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007628
7629size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00007630 return ASTRecordLayouts.getMemorySize()
7631 + llvm::capacity_in_bytes(ObjCLayouts)
7632 + llvm::capacity_in_bytes(KeyFunctions)
7633 + llvm::capacity_in_bytes(ObjCImpls)
7634 + llvm::capacity_in_bytes(BlockVarCopyInits)
7635 + llvm::capacity_in_bytes(DeclAttrs)
7636 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7637 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7638 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7639 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7640 + llvm::capacity_in_bytes(OverriddenMethods)
7641 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007642 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00007643 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007644}
Ted Kremenek540017e2011-10-06 05:00:56 +00007645
David Blaikie095deba2012-11-14 01:52:05 +00007646void ASTContext::addUnnamedTag(const TagDecl *Tag) {
7647 // FIXME: This mangling should be applied to function local classes too
7648 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl() ||
7649 !isa<CXXRecordDecl>(Tag->getParent()) || Tag->getLinkage() != ExternalLinkage)
7650 return;
7651
7652 std::pair<llvm::DenseMap<const DeclContext *, unsigned>::iterator, bool> P =
7653 UnnamedMangleContexts.insert(std::make_pair(Tag->getParent(), 0));
7654 UnnamedMangleNumbers.insert(std::make_pair(Tag, P.first->second++));
7655}
7656
7657int ASTContext::getUnnamedTagManglingNumber(const TagDecl *Tag) const {
7658 llvm::DenseMap<const TagDecl *, unsigned>::const_iterator I =
7659 UnnamedMangleNumbers.find(Tag);
7660 return I != UnnamedMangleNumbers.end() ? I->second : -1;
7661}
7662
Douglas Gregor63798542012-02-20 19:44:39 +00007663unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7664 CXXRecordDecl *Lambda = CallOperator->getParent();
7665 return LambdaMangleContexts[Lambda->getDeclContext()]
7666 .getManglingNumber(CallOperator);
7667}
7668
7669
Ted Kremenek540017e2011-10-06 05:00:56 +00007670void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7671 ParamIndices[D] = index;
7672}
7673
7674unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7675 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7676 assert(I != ParamIndices.end() &&
7677 "ParmIndices lacks entry set by ParmVarDecl");
7678 return I->second;
7679}