blob: b04b830c8521c6731919301651956b6ab01702eb [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.
368 for (const ObjCCategoryDecl *ClsExtDecl = ID->getFirstClassExtension();
369 ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension()) {
370 if (ObjCMethodDecl *RedeclaredMethod =
371 ClsExtDecl->getMethod(ObjCMethod->getSelector(),
372 ObjCMethod->isInstanceMethod()))
373 Redeclared.push_back(RedeclaredMethod);
374 }
375 }
376}
377
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000378comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
379 const Decl *D) const {
380 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
381 ThisDeclInfo->CommentDecl = D;
382 ThisDeclInfo->IsFilled = false;
383 ThisDeclInfo->fill();
384 ThisDeclInfo->CommentDecl = FC->getDecl();
385 comments::FullComment *CFC =
386 new (*this) comments::FullComment(FC->getBlocks(),
387 ThisDeclInfo);
388 return CFC;
389
390}
391
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000392comments::FullComment *ASTContext::getCommentForDecl(
393 const Decl *D,
394 const Preprocessor *PP) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000395 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000396
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000397 const Decl *Canonical = D->getCanonicalDecl();
398 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
399 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000400
401 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000402 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000403 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000404 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000405 return CFC;
406 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000407 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000408 }
409
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000410 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000411
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000412 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000413 if (!RC) {
414 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000415 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000416 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D))
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000417 addRedeclaredMethods(OMD, Overridden);
418 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
419 for (unsigned i = 0, e = Overridden.size(); i < e; i++) {
420 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP)) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000421 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000422 return CFC;
423 }
424 }
425 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000426 return NULL;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000427 }
428
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000429 // If the RawComment was attached to other redeclaration of this Decl, we
430 // should parse the comment in context of that other Decl. This is important
431 // because comments can contain references to parameter names which can be
432 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000433 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000434 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000435
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000436 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000437 ParsedComments[Canonical] = FC;
438 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000439}
440
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000441void
442ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
443 TemplateTemplateParmDecl *Parm) {
444 ID.AddInteger(Parm->getDepth());
445 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000446 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000447
448 TemplateParameterList *Params = Parm->getTemplateParameters();
449 ID.AddInteger(Params->size());
450 for (TemplateParameterList::const_iterator P = Params->begin(),
451 PEnd = Params->end();
452 P != PEnd; ++P) {
453 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
454 ID.AddInteger(0);
455 ID.AddBoolean(TTP->isParameterPack());
456 continue;
457 }
458
459 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
460 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000461 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000462 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000463 if (NTTP->isExpandedParameterPack()) {
464 ID.AddBoolean(true);
465 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000466 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
467 QualType T = NTTP->getExpansionType(I);
468 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
469 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000470 } else
471 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000472 continue;
473 }
474
475 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
476 ID.AddInteger(2);
477 Profile(ID, TTP);
478 }
479}
480
481TemplateTemplateParmDecl *
482ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000483 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000484 // Check if we already have a canonical template template parameter.
485 llvm::FoldingSetNodeID ID;
486 CanonicalTemplateTemplateParm::Profile(ID, TTP);
487 void *InsertPos = 0;
488 CanonicalTemplateTemplateParm *Canonical
489 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
490 if (Canonical)
491 return Canonical->getParam();
492
493 // Build a canonical template parameter list.
494 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000495 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000496 CanonParams.reserve(Params->size());
497 for (TemplateParameterList::const_iterator P = Params->begin(),
498 PEnd = Params->end();
499 P != PEnd; ++P) {
500 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
501 CanonParams.push_back(
502 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000503 SourceLocation(),
504 SourceLocation(),
505 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000506 TTP->getIndex(), 0, false,
507 TTP->isParameterPack()));
508 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000509 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
510 QualType T = getCanonicalType(NTTP->getType());
511 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
512 NonTypeTemplateParmDecl *Param;
513 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000514 SmallVector<QualType, 2> ExpandedTypes;
515 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000516 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
517 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
518 ExpandedTInfos.push_back(
519 getTrivialTypeSourceInfo(ExpandedTypes.back()));
520 }
521
522 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000523 SourceLocation(),
524 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000525 NTTP->getDepth(),
526 NTTP->getPosition(), 0,
527 T,
528 TInfo,
529 ExpandedTypes.data(),
530 ExpandedTypes.size(),
531 ExpandedTInfos.data());
532 } else {
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 NTTP->isParameterPack(),
540 TInfo);
541 }
542 CanonParams.push_back(Param);
543
544 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000545 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
546 cast<TemplateTemplateParmDecl>(*P)));
547 }
548
549 TemplateTemplateParmDecl *CanonTTP
550 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
551 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000552 TTP->getPosition(),
553 TTP->isParameterPack(),
554 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000555 TemplateParameterList::Create(*this, SourceLocation(),
556 SourceLocation(),
557 CanonParams.data(),
558 CanonParams.size(),
559 SourceLocation()));
560
561 // Get the new insert position for the node we care about.
562 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
563 assert(Canonical == 0 && "Shouldn't be in the map!");
564 (void)Canonical;
565
566 // Create the canonical template template parameter entry.
567 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
568 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
569 return CanonTTP;
570}
571
Charles Davis53c59df2010-08-16 03:33:14 +0000572CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000573 if (!LangOpts.CPlusPlus) return 0;
574
Charles Davis6bcb07a2010-08-19 02:18:14 +0000575 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000576 case CXXABI_ARM:
577 return CreateARMCXXABI(*this);
578 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000579 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000580 case CXXABI_Microsoft:
581 return CreateMicrosoftCXXABI(*this);
582 }
David Blaikie8a40f702012-01-17 06:56:22 +0000583 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000584}
585
Douglas Gregore8bbc122011-09-02 00:18:52 +0000586static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000587 const LangOptions &LOpts) {
588 if (LOpts.FakeAddressSpaceMap) {
589 // The fake address space map must have a distinct entry for each
590 // language-specific address space.
591 static const unsigned FakeAddrSpaceMap[] = {
592 1, // opencl_global
593 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000594 3, // opencl_constant
595 4, // cuda_device
596 5, // cuda_constant
597 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000598 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000599 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000600 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000601 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000602 }
603}
604
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000605ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000606 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000607 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000608 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000609 unsigned size_reserve,
610 bool DelayInitialization)
611 : FunctionProtoTypes(this_()),
612 TemplateSpecializationTypes(this_()),
613 DependentTemplateSpecializationTypes(this_()),
614 SubstTemplateTemplateParmPacks(this_()),
615 GlobalNestedNameSpecifier(0),
616 Int128Decl(0), UInt128Decl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000617 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000618 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanianf2578572012-08-30 18:49:41 +0000619 BOOLDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000620 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000621 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000622 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
623 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
624 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000625 NullTypeSourceInfo(QualType()),
626 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000627 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000628 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000629 Idents(idents), Selectors(sels),
630 BuiltinInfo(builtins),
631 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000632 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000633 Comments(SM), CommentsLoaded(false),
Dmitri Gribenko7acbf002012-09-10 20:32:42 +0000634 CommentCommandTraits(BumpAlloc),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000635 LastSDM(0, 0),
636 UniqueBlockByRefTypeID(0)
637{
Mike Stump11289f42009-09-09 15:08:12 +0000638 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000639 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000640
641 if (!DelayInitialization) {
642 assert(t && "No target supplied for ASTContext initialization");
643 InitBuiltinTypes(*t);
644 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000645}
646
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000647ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000648 // Release the DenseMaps associated with DeclContext objects.
649 // FIXME: Is this the ideal solution?
650 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000651
Douglas Gregor5b11d492010-07-25 17:53:33 +0000652 // Call all of the deallocation functions.
653 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
654 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000655
Ted Kremenek076baeb2010-06-08 23:00:58 +0000656 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000657 // because they can contain DenseMaps.
658 for (llvm::DenseMap<const ObjCContainerDecl*,
659 const ASTRecordLayout*>::iterator
660 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
661 // Increment in loop to prevent using deallocated memory.
662 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
663 R->Destroy(*this);
664
Ted Kremenek076baeb2010-06-08 23:00:58 +0000665 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
666 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
667 // Increment in loop to prevent using deallocated memory.
668 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
669 R->Destroy(*this);
670 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000671
672 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
673 AEnd = DeclAttrs.end();
674 A != AEnd; ++A)
675 A->second->~AttrVec();
676}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000677
Douglas Gregor1a809332010-05-23 18:26:36 +0000678void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
679 Deallocations.push_back(std::make_pair(Callback, Data));
680}
681
Mike Stump11289f42009-09-09 15:08:12 +0000682void
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000683ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000684 ExternalSource.reset(Source.take());
685}
686
Chris Lattner4eb445d2007-01-26 01:27:23 +0000687void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000688 llvm::errs() << "\n*** AST Context Stats:\n";
689 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000690
Douglas Gregora30d0462009-05-26 14:40:08 +0000691 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000692#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000693#define ABSTRACT_TYPE(Name, Parent)
694#include "clang/AST/TypeNodes.def"
695 0 // Extra
696 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000697
Chris Lattner4eb445d2007-01-26 01:27:23 +0000698 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
699 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000700 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000701 }
702
Douglas Gregora30d0462009-05-26 14:40:08 +0000703 unsigned Idx = 0;
704 unsigned TotalBytes = 0;
705#define TYPE(Name, Parent) \
706 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000707 llvm::errs() << " " << counts[Idx] << " " << #Name \
708 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000709 TotalBytes += counts[Idx] * sizeof(Name##Type); \
710 ++Idx;
711#define ABSTRACT_TYPE(Name, Parent)
712#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000713
Chandler Carruth3c147a72011-07-04 05:32:14 +0000714 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
715
Douglas Gregor7454c562010-07-02 20:37:36 +0000716 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000717 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
718 << NumImplicitDefaultConstructors
719 << " implicit default constructors created\n";
720 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
721 << NumImplicitCopyConstructors
722 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000723 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000724 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
725 << NumImplicitMoveConstructors
726 << " implicit move constructors created\n";
727 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
728 << NumImplicitCopyAssignmentOperators
729 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000730 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000731 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
732 << NumImplicitMoveAssignmentOperators
733 << " implicit move assignment operators created\n";
734 llvm::errs() << NumImplicitDestructorsDeclared << "/"
735 << NumImplicitDestructors
736 << " implicit destructors created\n";
737
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000738 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000739 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000740 ExternalSource->PrintStats();
741 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000742
Douglas Gregor5b11d492010-07-25 17:53:33 +0000743 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000744}
745
Douglas Gregor801c99d2011-08-12 06:49:56 +0000746TypedefDecl *ASTContext::getInt128Decl() const {
747 if (!Int128Decl) {
748 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
749 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
750 getTranslationUnitDecl(),
751 SourceLocation(),
752 SourceLocation(),
753 &Idents.get("__int128_t"),
754 TInfo);
755 }
756
757 return Int128Decl;
758}
759
760TypedefDecl *ASTContext::getUInt128Decl() const {
761 if (!UInt128Decl) {
762 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
763 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
764 getTranslationUnitDecl(),
765 SourceLocation(),
766 SourceLocation(),
767 &Idents.get("__uint128_t"),
768 TInfo);
769 }
770
771 return UInt128Decl;
772}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000773
John McCall48f2d582009-10-23 23:03:21 +0000774void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000775 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000776 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000777 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000778}
779
Douglas Gregore8bbc122011-09-02 00:18:52 +0000780void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
781 assert((!this->Target || this->Target == &Target) &&
782 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000783 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000784
Douglas Gregore8bbc122011-09-02 00:18:52 +0000785 this->Target = &Target;
786
787 ABI.reset(createCXXABI(Target));
788 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
789
Chris Lattner970e54e2006-11-12 00:37:36 +0000790 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000791 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000792
Chris Lattner970e54e2006-11-12 00:37:36 +0000793 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000794 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000795 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000796 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000797 InitBuiltinType(CharTy, BuiltinType::Char_S);
798 else
799 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000800 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000801 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
802 InitBuiltinType(ShortTy, BuiltinType::Short);
803 InitBuiltinType(IntTy, BuiltinType::Int);
804 InitBuiltinType(LongTy, BuiltinType::Long);
805 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000806
Chris Lattner970e54e2006-11-12 00:37:36 +0000807 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000808 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
809 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
810 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
811 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
812 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000813
Chris Lattner970e54e2006-11-12 00:37:36 +0000814 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000815 InitBuiltinType(FloatTy, BuiltinType::Float);
816 InitBuiltinType(DoubleTy, BuiltinType::Double);
817 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000818
Chris Lattnerf122cef2009-04-30 02:43:43 +0000819 // GNU extension, 128-bit integers.
820 InitBuiltinType(Int128Ty, BuiltinType::Int128);
821 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
822
Abramo Bagnara06782942012-09-09 10:13:32 +0000823 if (LangOpts.CPlusPlus && LangOpts.WChar) { // C++ 3.9.1p5
Eli Friedman786d0872011-04-30 19:24:24 +0000824 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000825 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
826 else // -fshort-wchar makes wchar_t be unsigned.
827 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
Abramo Bagnara06782942012-09-09 10:13:32 +0000828 } else // C99 (or C++ using -fno-wchar)
Chris Lattner007cb022009-02-26 23:43:47 +0000829 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000830
James Molloy36365542012-05-04 10:55:22 +0000831 WIntTy = getFromTargetType(Target.getWIntType());
832
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000833 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
834 InitBuiltinType(Char16Ty, BuiltinType::Char16);
835 else // C99
836 Char16Ty = getFromTargetType(Target.getChar16Type());
837
838 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
839 InitBuiltinType(Char32Ty, BuiltinType::Char32);
840 else // C99
841 Char32Ty = getFromTargetType(Target.getChar32Type());
842
Douglas Gregor4619e432008-12-05 23:32:09 +0000843 // Placeholder type for type-dependent expressions whose type is
844 // completely unknown. No code should ever check a type against
845 // DependentTy and users should never see it; however, it is here to
846 // help diagnose failures to properly check for type-dependent
847 // expressions.
848 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000849
John McCall36e7fe32010-10-12 00:20:44 +0000850 // Placeholder type for functions.
851 InitBuiltinType(OverloadTy, BuiltinType::Overload);
852
John McCall0009fcc2011-04-26 20:42:42 +0000853 // Placeholder type for bound members.
854 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
855
John McCall526ab472011-10-25 17:37:35 +0000856 // Placeholder type for pseudo-objects.
857 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
858
John McCall31996342011-04-07 08:22:57 +0000859 // "any" type; useful for debugger-like clients.
860 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
861
John McCall8a6b59a2011-10-17 18:09:15 +0000862 // Placeholder type for unbridged ARC casts.
863 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
864
Eli Friedman34866c72012-08-31 00:14:07 +0000865 // Placeholder type for builtin functions.
866 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
867
Chris Lattner970e54e2006-11-12 00:37:36 +0000868 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000869 FloatComplexTy = getComplexType(FloatTy);
870 DoubleComplexTy = getComplexType(DoubleTy);
871 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000872
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000873 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000874 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
875 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000876 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000877
878 if (LangOpts.OpenCL) {
879 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
880 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
881 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
882 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
883 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
884 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
885 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000886
887 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +0000888 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
889 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000890
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000891 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000892
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000893 // void * type
894 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000895
896 // nullptr type (C++0x 2.14.7)
897 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000898
899 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
900 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +0000901
902 // Builtin type used to help define __builtin_va_list.
903 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +0000904}
905
David Blaikie9c902b52011-09-25 23:23:43 +0000906DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000907 return SourceMgr.getDiagnostics();
908}
909
Douglas Gregor561eceb2010-08-30 16:49:28 +0000910AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
911 AttrVec *&Result = DeclAttrs[D];
912 if (!Result) {
913 void *Mem = Allocate(sizeof(AttrVec));
914 Result = new (Mem) AttrVec;
915 }
916
917 return *Result;
918}
919
920/// \brief Erase the attributes corresponding to the given declaration.
921void ASTContext::eraseDeclAttrs(const Decl *D) {
922 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
923 if (Pos != DeclAttrs.end()) {
924 Pos->second->~AttrVec();
925 DeclAttrs.erase(Pos);
926 }
927}
928
Douglas Gregor86d142a2009-10-08 07:24:58 +0000929MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000930ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000931 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000932 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000933 = InstantiatedFromStaticDataMember.find(Var);
934 if (Pos == InstantiatedFromStaticDataMember.end())
935 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000936
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000937 return Pos->second;
938}
939
Mike Stump11289f42009-09-09 15:08:12 +0000940void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000941ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000942 TemplateSpecializationKind TSK,
943 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000944 assert(Inst->isStaticDataMember() && "Not a static data member");
945 assert(Tmpl->isStaticDataMember() && "Not a static data member");
946 assert(!InstantiatedFromStaticDataMember[Inst] &&
947 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000948 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000949 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000950}
951
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000952FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
953 const FunctionDecl *FD){
954 assert(FD && "Specialization is 0");
955 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +0000956 = ClassScopeSpecializationPattern.find(FD);
957 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000958 return 0;
959
960 return Pos->second;
961}
962
963void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
964 FunctionDecl *Pattern) {
965 assert(FD && "Specialization is 0");
966 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +0000967 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000968}
969
John McCalle61f2ba2009-11-18 02:36:19 +0000970NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000971ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000972 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000973 = InstantiatedFromUsingDecl.find(UUD);
974 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000975 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000976
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000977 return Pos->second;
978}
979
980void
John McCallb96ec562009-12-04 22:46:56 +0000981ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
982 assert((isa<UsingDecl>(Pattern) ||
983 isa<UnresolvedUsingValueDecl>(Pattern) ||
984 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
985 "pattern decl is not a using decl");
986 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
987 InstantiatedFromUsingDecl[Inst] = Pattern;
988}
989
990UsingShadowDecl *
991ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
992 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
993 = InstantiatedFromUsingShadowDecl.find(Inst);
994 if (Pos == InstantiatedFromUsingShadowDecl.end())
995 return 0;
996
997 return Pos->second;
998}
999
1000void
1001ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1002 UsingShadowDecl *Pattern) {
1003 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1004 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001005}
1006
Anders Carlsson5da84842009-09-01 04:26:58 +00001007FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1008 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1009 = InstantiatedFromUnnamedFieldDecl.find(Field);
1010 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1011 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001012
Anders Carlsson5da84842009-09-01 04:26:58 +00001013 return Pos->second;
1014}
1015
1016void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1017 FieldDecl *Tmpl) {
1018 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1019 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1020 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1021 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001022
Anders Carlsson5da84842009-09-01 04:26:58 +00001023 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1024}
1025
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +00001026bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
1027 const FieldDecl *LastFD) const {
1028 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001029 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +00001030}
1031
Fariborz Jahanianeb397412011-05-02 17:20:56 +00001032bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
1033 const FieldDecl *LastFD) const {
1034 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001035 FD->getBitWidthValue(*this) == 0 &&
1036 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +00001037}
1038
Fariborz Jahanian84335f72011-05-04 18:51:37 +00001039bool ASTContext::BitfieldFollowsBitfield(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) &&
1043 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +00001044}
1045
Chad Rosierf01a7dd2011-08-04 23:34:15 +00001046bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001047 const FieldDecl *LastFD) const {
1048 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001049 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001050}
1051
Chad Rosierf01a7dd2011-08-04 23:34:15 +00001052bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001053 const FieldDecl *LastFD) const {
1054 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001055 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001056}
1057
Douglas Gregor832940b2010-03-02 23:58:15 +00001058ASTContext::overridden_cxx_method_iterator
1059ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1060 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001061 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001062 if (Pos == OverriddenMethods.end())
1063 return 0;
1064
1065 return Pos->second.begin();
1066}
1067
1068ASTContext::overridden_cxx_method_iterator
1069ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1070 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001071 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001072 if (Pos == OverriddenMethods.end())
1073 return 0;
1074
1075 return Pos->second.end();
1076}
1077
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001078unsigned
1079ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1080 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001081 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001082 if (Pos == OverriddenMethods.end())
1083 return 0;
1084
1085 return Pos->second.size();
1086}
1087
Douglas Gregor832940b2010-03-02 23:58:15 +00001088void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1089 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001090 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001091 OverriddenMethods[Method].push_back(Overridden);
1092}
1093
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001094void ASTContext::getOverriddenMethods(
1095 const NamedDecl *D,
1096 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001097 assert(D);
1098
1099 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001100 Overridden.append(CXXMethod->begin_overridden_methods(),
1101 CXXMethod->end_overridden_methods());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001102 return;
1103 }
1104
1105 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1106 if (!Method)
1107 return;
1108
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001109 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1110 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001111 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001112}
1113
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001114void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1115 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1116 assert(!Import->isFromASTFile() && "Non-local import declaration");
1117 if (!FirstLocalImport) {
1118 FirstLocalImport = Import;
1119 LastLocalImport = Import;
1120 return;
1121 }
1122
1123 LastLocalImport->NextLocalImport = Import;
1124 LastLocalImport = Import;
1125}
1126
Chris Lattner53cfe802007-07-18 17:52:12 +00001127//===----------------------------------------------------------------------===//
1128// Type Sizing and Analysis
1129//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001130
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001131/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1132/// scalar floating point type.
1133const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001134 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001135 assert(BT && "Not a floating point type!");
1136 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001137 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001138 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001139 case BuiltinType::Float: return Target->getFloatFormat();
1140 case BuiltinType::Double: return Target->getDoubleFormat();
1141 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001142 }
1143}
1144
Ken Dyck160146e2010-01-27 17:10:57 +00001145/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +00001146/// specified decl. Note that bitfields do not have a valid alignment, so
1147/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001148/// If @p RefAsPointee, references are treated like their underlying type
1149/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +00001150CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001151 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001152
John McCall94268702010-10-08 18:24:19 +00001153 bool UseAlignAttrOnly = false;
1154 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1155 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001156
John McCall94268702010-10-08 18:24:19 +00001157 // __attribute__((aligned)) can increase or decrease alignment
1158 // *except* on a struct or struct member, where it only increases
1159 // alignment unless 'packed' is also specified.
1160 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001161 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001162 // ignore that possibility; Sema should diagnose it.
1163 if (isa<FieldDecl>(D)) {
1164 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1165 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1166 } else {
1167 UseAlignAttrOnly = true;
1168 }
1169 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001170 else if (isa<FieldDecl>(D))
1171 UseAlignAttrOnly =
1172 D->hasAttr<PackedAttr>() ||
1173 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001174
John McCall4e819612011-01-20 07:57:12 +00001175 // If we're using the align attribute only, just ignore everything
1176 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001177 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001178 // do nothing
1179
John McCall94268702010-10-08 18:24:19 +00001180 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001181 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001182 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001183 if (RefAsPointee)
1184 T = RT->getPointeeType();
1185 else
1186 T = getPointerType(RT->getPointeeType());
1187 }
1188 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001189 // Adjust alignments of declarations with array type by the
1190 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +00001191 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +00001192 const ArrayType *arrayType;
1193 if (MinWidth && (arrayType = getAsArrayType(T))) {
1194 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001195 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +00001196 else if (isa<ConstantArrayType>(arrayType) &&
1197 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001198 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +00001199
John McCall33ddac02011-01-19 10:06:00 +00001200 // Walk through any array types while we're at it.
1201 T = getBaseElementType(arrayType);
1202 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001203 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +00001204 }
John McCall4e819612011-01-20 07:57:12 +00001205
1206 // Fields can be subject to extra alignment constraints, like if
1207 // the field is packed, the struct is packed, or the struct has a
1208 // a max-field-alignment constraint (#pragma pack). So calculate
1209 // the actual alignment of the field within the struct, and then
1210 // (as we're expected to) constrain that by the alignment of the type.
1211 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
1212 // So calculate the alignment of the field.
1213 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
1214
1215 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +00001216 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001217
1218 // Use the GCD of that and the offset within the record.
1219 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
1220 if (offset > 0) {
1221 // Alignment is always a power of 2, so the GCD will be a power of 2,
1222 // which means we get to do this crazy thing instead of Euclid's.
1223 uint64_t lowBitOfOffset = offset & (~offset + 1);
1224 if (lowBitOfOffset < fieldAlign)
1225 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
1226 }
1227
1228 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +00001229 }
Chris Lattner68061312009-01-24 21:53:27 +00001230 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001231
Ken Dyckcc56c542011-01-15 18:38:59 +00001232 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001233}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001234
John McCallf1249922012-08-21 04:10:00 +00001235// getTypeInfoDataSizeInChars - Return the size of a type, in
1236// chars. If the type is a record, its data size is returned. This is
1237// the size of the memcpy that's performed when assigning this type
1238// using a trivial copy/move assignment operator.
1239std::pair<CharUnits, CharUnits>
1240ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1241 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1242
1243 // In C++, objects can sometimes be allocated into the tail padding
1244 // of a base-class subobject. We decide whether that's possible
1245 // during class layout, so here we can just trust the layout results.
1246 if (getLangOpts().CPlusPlus) {
1247 if (const RecordType *RT = T->getAs<RecordType>()) {
1248 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1249 sizeAndAlign.first = layout.getDataSize();
1250 }
1251 }
1252
1253 return sizeAndAlign;
1254}
1255
John McCall87fe5d52010-05-20 01:18:31 +00001256std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001257ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001258 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +00001259 return std::make_pair(toCharUnitsFromBits(Info.first),
1260 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +00001261}
1262
1263std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001264ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001265 return getTypeInfoInChars(T.getTypePtr());
1266}
1267
Daniel Dunbarc6475872012-03-09 04:12:54 +00001268std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1269 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1270 if (it != MemoizedTypeInfo.end())
1271 return it->second;
1272
1273 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1274 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1275 return Info;
1276}
1277
1278/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1279/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001280///
1281/// FIXME: Pointers into different addr spaces could have different sizes and
1282/// alignment requirements: getPointerInfo should take an AddrSpace, this
1283/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +00001284std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +00001285ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +00001286 uint64_t Width=0;
1287 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001288 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001289#define TYPE(Class, Base)
1290#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001291#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001292#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1293#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001294 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001295
Chris Lattner355332d2007-07-13 22:27:08 +00001296 case Type::FunctionNoProto:
1297 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001298 // GCC extension: alignof(function) = 32 bits
1299 Width = 0;
1300 Align = 32;
1301 break;
1302
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001303 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001304 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001305 Width = 0;
1306 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1307 break;
1308
Steve Naroff5c131802007-08-30 01:06:46 +00001309 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001310 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001311
Chris Lattner37e05872008-03-05 18:54:05 +00001312 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001313 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +00001314 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1315 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001316 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001317 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +00001318 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001319 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001320 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001321 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001322 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001323 const VectorType *VT = cast<VectorType>(T);
1324 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1325 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001326 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001327 // If the alignment is not a power of 2, round up to the next power of 2.
1328 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001329 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001330 Align = llvm::NextPowerOf2(Align);
1331 Width = llvm::RoundUpToAlignment(Width, Align);
1332 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001333 // Adjust the alignment based on the target max.
1334 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1335 if (TargetVectorAlign && TargetVectorAlign < Align)
1336 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001337 break;
1338 }
Chris Lattner647fb222007-07-18 18:26:58 +00001339
Chris Lattner7570e9c2008-03-08 08:52:55 +00001340 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001341 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001342 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001343 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001344 // GCC extension: alignof(void) = 8 bits.
1345 Width = 0;
1346 Align = 8;
1347 break;
1348
Chris Lattner6a4f7452007-12-19 19:23:28 +00001349 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001350 Width = Target->getBoolWidth();
1351 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001352 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001353 case BuiltinType::Char_S:
1354 case BuiltinType::Char_U:
1355 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001356 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001357 Width = Target->getCharWidth();
1358 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001359 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001360 case BuiltinType::WChar_S:
1361 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001362 Width = Target->getWCharWidth();
1363 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001364 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001365 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001366 Width = Target->getChar16Width();
1367 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001368 break;
1369 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001370 Width = Target->getChar32Width();
1371 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001372 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001373 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001374 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001375 Width = Target->getShortWidth();
1376 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001377 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001378 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001379 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001380 Width = Target->getIntWidth();
1381 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001382 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001383 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001384 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001385 Width = Target->getLongWidth();
1386 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001387 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001388 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001389 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001390 Width = Target->getLongLongWidth();
1391 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001392 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001393 case BuiltinType::Int128:
1394 case BuiltinType::UInt128:
1395 Width = 128;
1396 Align = 128; // int128_t is 128-bit aligned on all targets.
1397 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001398 case BuiltinType::Half:
1399 Width = Target->getHalfWidth();
1400 Align = Target->getHalfAlign();
1401 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001402 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001403 Width = Target->getFloatWidth();
1404 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001405 break;
1406 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001407 Width = Target->getDoubleWidth();
1408 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001409 break;
1410 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001411 Width = Target->getLongDoubleWidth();
1412 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001413 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001414 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001415 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1416 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001417 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001418 case BuiltinType::ObjCId:
1419 case BuiltinType::ObjCClass:
1420 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001421 Width = Target->getPointerWidth(0);
1422 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001423 break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001424 case BuiltinType::OCLImage1d:
1425 case BuiltinType::OCLImage1dArray:
1426 case BuiltinType::OCLImage1dBuffer:
1427 case BuiltinType::OCLImage2d:
1428 case BuiltinType::OCLImage2dArray:
1429 case BuiltinType::OCLImage3d:
1430 // Currently these types are pointers to opaque types.
1431 Width = Target->getPointerWidth(0);
1432 Align = Target->getPointerAlign(0);
1433 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001434 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001435 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001436 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001437 Width = Target->getPointerWidth(0);
1438 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001439 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001440 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001441 unsigned AS = getTargetAddressSpace(
1442 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001443 Width = Target->getPointerWidth(AS);
1444 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001445 break;
1446 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001447 case Type::LValueReference:
1448 case Type::RValueReference: {
1449 // alignof and sizeof should never enter this code path here, so we go
1450 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001451 unsigned AS = getTargetAddressSpace(
1452 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001453 Width = Target->getPointerWidth(AS);
1454 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001455 break;
1456 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001457 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001458 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001459 Width = Target->getPointerWidth(AS);
1460 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001461 break;
1462 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001463 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001464 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001465 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +00001466 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +00001467 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001468 Align = PtrDiffInfo.second;
1469 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001470 }
Chris Lattner647fb222007-07-18 18:26:58 +00001471 case Type::Complex: {
1472 // Complex types have the same alignment as their elements, but twice the
1473 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001474 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001475 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001476 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001477 Align = EltInfo.second;
1478 break;
1479 }
John McCall8b07ec22010-05-15 11:32:37 +00001480 case Type::ObjCObject:
1481 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001482 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001483 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001484 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001485 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001486 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001487 break;
1488 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001489 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001490 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001491 const TagType *TT = cast<TagType>(T);
1492
1493 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001494 Width = 8;
1495 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001496 break;
1497 }
Mike Stump11289f42009-09-09 15:08:12 +00001498
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001499 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001500 return getTypeInfo(ET->getDecl()->getIntegerType());
1501
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001502 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001503 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001504 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001505 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001506 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001507 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001508
Chris Lattner63d2b362009-10-22 05:17:15 +00001509 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001510 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1511 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001512
Richard Smith30482bc2011-02-20 03:19:35 +00001513 case Type::Auto: {
1514 const AutoType *A = cast<AutoType>(T);
1515 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001516 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001517 }
1518
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001519 case Type::Paren:
1520 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1521
Douglas Gregoref462e62009-04-30 17:32:17 +00001522 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001523 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001524 std::pair<uint64_t, unsigned> Info
1525 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001526 // If the typedef has an aligned attribute on it, it overrides any computed
1527 // alignment we have. This violates the GCC documentation (which says that
1528 // attribute(aligned) can only round up) but matches its implementation.
1529 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1530 Align = AttrAlign;
1531 else
1532 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001533 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001534 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001535 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001536
1537 case Type::TypeOfExpr:
1538 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1539 .getTypePtr());
1540
1541 case Type::TypeOf:
1542 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1543
Anders Carlsson81df7b82009-06-24 19:06:50 +00001544 case Type::Decltype:
1545 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1546 .getTypePtr());
1547
Alexis Hunte852b102011-05-24 22:41:36 +00001548 case Type::UnaryTransform:
1549 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1550
Abramo Bagnara6150c882010-05-11 21:36:43 +00001551 case Type::Elaborated:
1552 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001553
John McCall81904512011-01-06 01:58:22 +00001554 case Type::Attributed:
1555 return getTypeInfo(
1556 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1557
Richard Smith3f1b5d02011-05-05 21:57:07 +00001558 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001559 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001560 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001561 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1562 // A type alias template specialization may refer to a typedef with the
1563 // aligned attribute on it.
1564 if (TST->isTypeAlias())
1565 return getTypeInfo(TST->getAliasedType().getTypePtr());
1566 else
1567 return getTypeInfo(getCanonicalType(T));
1568 }
1569
Eli Friedman0dfb8892011-10-06 23:00:33 +00001570 case Type::Atomic: {
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001571 std::pair<uint64_t, unsigned> Info
1572 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1573 Width = Info.first;
1574 Align = Info.second;
1575 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1576 llvm::isPowerOf2_64(Width)) {
1577 // We can potentially perform lock-free atomic operations for this
1578 // type; promote the alignment appropriately.
1579 // FIXME: We could potentially promote the width here as well...
1580 // is that worthwhile? (Non-struct atomic types generally have
1581 // power-of-two size anyway, but structs might not. Requires a bit
1582 // of implementation work to make sure we zero out the extra bits.)
1583 Align = static_cast<unsigned>(Width);
1584 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001585 }
1586
Douglas Gregoref462e62009-04-30 17:32:17 +00001587 }
Mike Stump11289f42009-09-09 15:08:12 +00001588
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001589 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001590 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001591}
1592
Ken Dyckcc56c542011-01-15 18:38:59 +00001593/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1594CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1595 return CharUnits::fromQuantity(BitSize / getCharWidth());
1596}
1597
Ken Dyckb0fcc592011-02-11 01:54:29 +00001598/// toBits - Convert a size in characters to a size in characters.
1599int64_t ASTContext::toBits(CharUnits CharSize) const {
1600 return CharSize.getQuantity() * getCharWidth();
1601}
1602
Ken Dyck8c89d592009-12-22 14:23:30 +00001603/// getTypeSizeInChars - Return the size of the specified type, in characters.
1604/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001605CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001606 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001607}
Jay Foad39c79802011-01-12 09:06:06 +00001608CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001609 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001610}
1611
Ken Dycka6046ab2010-01-26 17:25:18 +00001612/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001613/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001614CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001615 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001616}
Jay Foad39c79802011-01-12 09:06:06 +00001617CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001618 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001619}
1620
Chris Lattnera3402cd2009-01-27 18:08:34 +00001621/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1622/// type for the current target in bits. This can be different than the ABI
1623/// alignment in cases where it is beneficial for performance to overalign
1624/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001625unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001626 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001627
1628 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001629 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001630 T = CT->getElementType().getTypePtr();
1631 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001632 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1633 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001634 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1635
Chris Lattnera3402cd2009-01-27 18:08:34 +00001636 return ABIAlign;
1637}
1638
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001639/// DeepCollectObjCIvars -
1640/// This routine first collects all declared, but not synthesized, ivars in
1641/// super class and then collects all ivars, including those synthesized for
1642/// current class. This routine is used for implementation of current class
1643/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001644///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001645void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1646 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001647 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001648 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1649 DeepCollectObjCIvars(SuperClass, false, Ivars);
1650 if (!leafClass) {
1651 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1652 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001653 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001654 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001655 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001656 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001657 Iv= Iv->getNextIvar())
1658 Ivars.push_back(Iv);
1659 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001660}
1661
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001662/// CollectInheritedProtocols - Collect all protocols in current class and
1663/// those inherited by it.
1664void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001665 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001666 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001667 // We can use protocol_iterator here instead of
1668 // all_referenced_protocol_iterator since we are walking all categories.
1669 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1670 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001671 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001672 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001673 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001674 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001675 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001676 CollectInheritedProtocols(*P, Protocols);
1677 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001678 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001679
1680 // Categories of this Interface.
1681 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1682 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1683 CollectInheritedProtocols(CDeclChain, Protocols);
1684 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1685 while (SD) {
1686 CollectInheritedProtocols(SD, Protocols);
1687 SD = SD->getSuperClass();
1688 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001689 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001690 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001691 PE = OC->protocol_end(); P != PE; ++P) {
1692 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001693 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001694 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1695 PE = Proto->protocol_end(); P != PE; ++P)
1696 CollectInheritedProtocols(*P, Protocols);
1697 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001698 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001699 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1700 PE = OP->protocol_end(); P != PE; ++P) {
1701 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001702 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001703 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1704 PE = Proto->protocol_end(); P != PE; ++P)
1705 CollectInheritedProtocols(*P, Protocols);
1706 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001707 }
1708}
1709
Jay Foad39c79802011-01-12 09:06:06 +00001710unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001711 unsigned count = 0;
1712 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001713 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1714 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001715 count += CDecl->ivar_size();
1716
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001717 // Count ivar defined in this class's implementation. This
1718 // includes synthesized ivars.
1719 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001720 count += ImplDecl->ivar_size();
1721
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001722 return count;
1723}
1724
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001725bool ASTContext::isSentinelNullExpr(const Expr *E) {
1726 if (!E)
1727 return false;
1728
1729 // nullptr_t is always treated as null.
1730 if (E->getType()->isNullPtrType()) return true;
1731
1732 if (E->getType()->isAnyPointerType() &&
1733 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1734 Expr::NPC_ValueDependentIsNull))
1735 return true;
1736
1737 // Unfortunately, __null has type 'int'.
1738 if (isa<GNUNullExpr>(E)) return true;
1739
1740 return false;
1741}
1742
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001743/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1744ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1745 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1746 I = ObjCImpls.find(D);
1747 if (I != ObjCImpls.end())
1748 return cast<ObjCImplementationDecl>(I->second);
1749 return 0;
1750}
1751/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1752ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1753 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1754 I = ObjCImpls.find(D);
1755 if (I != ObjCImpls.end())
1756 return cast<ObjCCategoryImplDecl>(I->second);
1757 return 0;
1758}
1759
1760/// \brief Set the implementation of ObjCInterfaceDecl.
1761void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1762 ObjCImplementationDecl *ImplD) {
1763 assert(IFaceD && ImplD && "Passed null params");
1764 ObjCImpls[IFaceD] = ImplD;
1765}
1766/// \brief Set the implementation of ObjCCategoryDecl.
1767void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1768 ObjCCategoryImplDecl *ImplD) {
1769 assert(CatD && ImplD && "Passed null params");
1770 ObjCImpls[CatD] = ImplD;
1771}
1772
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001773ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1774 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1775 return ID;
1776 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1777 return CD->getClassInterface();
1778 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1779 return IMD->getClassInterface();
1780
1781 return 0;
1782}
1783
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001784/// \brief Get the copy initialization expression of VarDecl,or NULL if
1785/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001786Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001787 assert(VD && "Passed null params");
1788 assert(VD->hasAttr<BlocksAttr>() &&
1789 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001790 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001791 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001792 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1793}
1794
1795/// \brief Set the copy inialization expression of a block var decl.
1796void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1797 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001798 assert(VD->hasAttr<BlocksAttr>() &&
1799 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001800 BlockVarCopyInits[VD] = Init;
1801}
1802
John McCallbcd03502009-12-07 02:54:59 +00001803TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001804 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001805 if (!DataSize)
1806 DataSize = TypeLoc::getFullDataSizeForType(T);
1807 else
1808 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001809 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001810
John McCallbcd03502009-12-07 02:54:59 +00001811 TypeSourceInfo *TInfo =
1812 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1813 new (TInfo) TypeSourceInfo(T);
1814 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001815}
1816
John McCallbcd03502009-12-07 02:54:59 +00001817TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001818 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001819 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001820 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001821 return DI;
1822}
1823
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001824const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001825ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001826 return getObjCLayout(D, 0);
1827}
1828
1829const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001830ASTContext::getASTObjCImplementationLayout(
1831 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001832 return getObjCLayout(D->getClassInterface(), D);
1833}
1834
Chris Lattner983a8bb2007-07-13 22:13:22 +00001835//===----------------------------------------------------------------------===//
1836// Type creation/memoization methods
1837//===----------------------------------------------------------------------===//
1838
Jay Foad39c79802011-01-12 09:06:06 +00001839QualType
John McCall33ddac02011-01-19 10:06:00 +00001840ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1841 unsigned fastQuals = quals.getFastQualifiers();
1842 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001843
1844 // Check if we've already instantiated this type.
1845 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001846 ExtQuals::Profile(ID, baseType, quals);
1847 void *insertPos = 0;
1848 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1849 assert(eq->getQualifiers() == quals);
1850 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001851 }
1852
John McCall33ddac02011-01-19 10:06:00 +00001853 // If the base type is not canonical, make the appropriate canonical type.
1854 QualType canon;
1855 if (!baseType->isCanonicalUnqualified()) {
1856 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00001857 canonSplit.Quals.addConsistentQualifiers(quals);
1858 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001859
1860 // Re-find the insert position.
1861 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1862 }
1863
1864 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1865 ExtQualNodes.InsertNode(eq, insertPos);
1866 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001867}
1868
Jay Foad39c79802011-01-12 09:06:06 +00001869QualType
1870ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001871 QualType CanT = getCanonicalType(T);
1872 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001873 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001874
John McCall8ccfcb52009-09-24 19:53:00 +00001875 // If we are composing extended qualifiers together, merge together
1876 // into one ExtQuals node.
1877 QualifierCollector Quals;
1878 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001879
John McCall8ccfcb52009-09-24 19:53:00 +00001880 // If this type already has an address space specified, it cannot get
1881 // another one.
1882 assert(!Quals.hasAddressSpace() &&
1883 "Type cannot be in multiple addr spaces!");
1884 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001885
John McCall8ccfcb52009-09-24 19:53:00 +00001886 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001887}
1888
Chris Lattnerd60183d2009-02-18 22:53:11 +00001889QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001890 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001891 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001892 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001893 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001894
John McCall53fa7142010-12-24 02:08:15 +00001895 if (const PointerType *ptr = T->getAs<PointerType>()) {
1896 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001897 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001898 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1899 return getPointerType(ResultType);
1900 }
1901 }
Mike Stump11289f42009-09-09 15:08:12 +00001902
John McCall8ccfcb52009-09-24 19:53:00 +00001903 // If we are composing extended qualifiers together, merge together
1904 // into one ExtQuals node.
1905 QualifierCollector Quals;
1906 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001907
John McCall8ccfcb52009-09-24 19:53:00 +00001908 // If this type already has an ObjCGC specified, it cannot get
1909 // another one.
1910 assert(!Quals.hasObjCGCAttr() &&
1911 "Type cannot have multiple ObjCGCs!");
1912 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001913
John McCall8ccfcb52009-09-24 19:53:00 +00001914 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001915}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001916
John McCall4f5019e2010-12-19 02:44:49 +00001917const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1918 FunctionType::ExtInfo Info) {
1919 if (T->getExtInfo() == Info)
1920 return T;
1921
1922 QualType Result;
1923 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1924 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1925 } else {
1926 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1927 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1928 EPI.ExtInfo = Info;
1929 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1930 FPT->getNumArgs(), EPI);
1931 }
1932
1933 return cast<FunctionType>(Result.getTypePtr());
1934}
1935
Chris Lattnerc6395932007-06-22 20:56:16 +00001936/// getComplexType - Return the uniqued reference to the type for a complex
1937/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001938QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001939 // Unique pointers, to guarantee there is only one pointer of a particular
1940 // structure.
1941 llvm::FoldingSetNodeID ID;
1942 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001943
Chris Lattnerc6395932007-06-22 20:56:16 +00001944 void *InsertPos = 0;
1945 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1946 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001947
Chris Lattnerc6395932007-06-22 20:56:16 +00001948 // If the pointee type isn't canonical, this won't be a canonical type either,
1949 // so fill in the canonical type field.
1950 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001951 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001952 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001953
Chris Lattnerc6395932007-06-22 20:56:16 +00001954 // Get the new insert position for the node we care about.
1955 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001956 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001957 }
John McCall90d1c2d2009-09-24 23:30:46 +00001958 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001959 Types.push_back(New);
1960 ComplexTypes.InsertNode(New, InsertPos);
1961 return QualType(New, 0);
1962}
1963
Chris Lattner970e54e2006-11-12 00:37:36 +00001964/// getPointerType - Return the uniqued reference to the type for a pointer to
1965/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001966QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001967 // Unique pointers, to guarantee there is only one pointer of a particular
1968 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001969 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001970 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001971
Chris Lattner67521df2007-01-27 01:29:36 +00001972 void *InsertPos = 0;
1973 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001974 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001975
Chris Lattner7ccecb92006-11-12 08:50:50 +00001976 // If the pointee type isn't canonical, this won't be a canonical type either,
1977 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001978 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001979 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001980 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001981
Chris Lattner67521df2007-01-27 01:29:36 +00001982 // Get the new insert position for the node we care about.
1983 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001984 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001985 }
John McCall90d1c2d2009-09-24 23:30:46 +00001986 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001987 Types.push_back(New);
1988 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001989 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001990}
1991
Mike Stump11289f42009-09-09 15:08:12 +00001992/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001993/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001994QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001995 assert(T->isFunctionType() && "block of function types only");
1996 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001997 // structure.
1998 llvm::FoldingSetNodeID ID;
1999 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002000
Steve Naroffec33ed92008-08-27 16:04:49 +00002001 void *InsertPos = 0;
2002 if (BlockPointerType *PT =
2003 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2004 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002005
2006 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002007 // type either so fill in the canonical type field.
2008 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002009 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002010 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002011
Steve Naroffec33ed92008-08-27 16:04:49 +00002012 // Get the new insert position for the node we care about.
2013 BlockPointerType *NewIP =
2014 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002015 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002016 }
John McCall90d1c2d2009-09-24 23:30:46 +00002017 BlockPointerType *New
2018 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002019 Types.push_back(New);
2020 BlockPointerTypes.InsertNode(New, InsertPos);
2021 return QualType(New, 0);
2022}
2023
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002024/// getLValueReferenceType - Return the uniqued reference to the type for an
2025/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002026QualType
2027ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002028 assert(getCanonicalType(T) != OverloadTy &&
2029 "Unresolved overloaded function type");
2030
Bill Wendling3708c182007-05-27 10:15:43 +00002031 // Unique pointers, to guarantee there is only one pointer of a particular
2032 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002033 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002034 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002035
2036 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002037 if (LValueReferenceType *RT =
2038 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002039 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002040
John McCallfc93cf92009-10-22 22:37:11 +00002041 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2042
Bill Wendling3708c182007-05-27 10:15:43 +00002043 // If the referencee type isn't canonical, this won't be a canonical type
2044 // either, so fill in the canonical type field.
2045 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002046 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2047 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2048 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002049
Bill Wendling3708c182007-05-27 10:15:43 +00002050 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002051 LValueReferenceType *NewIP =
2052 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002053 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002054 }
2055
John McCall90d1c2d2009-09-24 23:30:46 +00002056 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002057 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2058 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002059 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002060 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002061
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002062 return QualType(New, 0);
2063}
2064
2065/// getRValueReferenceType - Return the uniqued reference to the type for an
2066/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002067QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002068 // Unique pointers, to guarantee there is only one pointer of a particular
2069 // structure.
2070 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002071 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002072
2073 void *InsertPos = 0;
2074 if (RValueReferenceType *RT =
2075 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2076 return QualType(RT, 0);
2077
John McCallfc93cf92009-10-22 22:37:11 +00002078 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2079
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002080 // If the referencee type isn't canonical, this won't be a canonical type
2081 // either, so fill in the canonical type field.
2082 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002083 if (InnerRef || !T.isCanonical()) {
2084 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2085 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002086
2087 // Get the new insert position for the node we care about.
2088 RValueReferenceType *NewIP =
2089 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002090 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002091 }
2092
John McCall90d1c2d2009-09-24 23:30:46 +00002093 RValueReferenceType *New
2094 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002095 Types.push_back(New);
2096 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002097 return QualType(New, 0);
2098}
2099
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002100/// getMemberPointerType - Return the uniqued reference to the type for a
2101/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002102QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002103 // Unique pointers, to guarantee there is only one pointer of a particular
2104 // structure.
2105 llvm::FoldingSetNodeID ID;
2106 MemberPointerType::Profile(ID, T, Cls);
2107
2108 void *InsertPos = 0;
2109 if (MemberPointerType *PT =
2110 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2111 return QualType(PT, 0);
2112
2113 // If the pointee or class type isn't canonical, this won't be a canonical
2114 // type either, so fill in the canonical type field.
2115 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002116 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002117 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2118
2119 // Get the new insert position for the node we care about.
2120 MemberPointerType *NewIP =
2121 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002122 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002123 }
John McCall90d1c2d2009-09-24 23:30:46 +00002124 MemberPointerType *New
2125 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002126 Types.push_back(New);
2127 MemberPointerTypes.InsertNode(New, InsertPos);
2128 return QualType(New, 0);
2129}
2130
Mike Stump11289f42009-09-09 15:08:12 +00002131/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002132/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002133QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002134 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002135 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002136 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002137 assert((EltTy->isDependentType() ||
2138 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002139 "Constant array of VLAs is illegal!");
2140
Chris Lattnere2df3f92009-05-13 04:12:56 +00002141 // Convert the array size into a canonical width matching the pointer size for
2142 // the target.
2143 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002144 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002145 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002146
Chris Lattner23b7eb62007-06-15 23:05:46 +00002147 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002148 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002149
Chris Lattner36f8e652007-01-27 08:31:04 +00002150 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002151 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002152 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002153 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002154
John McCall33ddac02011-01-19 10:06:00 +00002155 // If the element type isn't canonical or has qualifiers, this won't
2156 // be a canonical type either, so fill in the canonical type field.
2157 QualType Canon;
2158 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2159 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002160 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002161 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002162 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002163
Chris Lattner36f8e652007-01-27 08:31:04 +00002164 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002165 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002166 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002167 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002168 }
Mike Stump11289f42009-09-09 15:08:12 +00002169
John McCall90d1c2d2009-09-24 23:30:46 +00002170 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002171 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002172 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002173 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002174 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002175}
2176
John McCall06549462011-01-18 08:40:38 +00002177/// getVariableArrayDecayedType - Turns the given type, which may be
2178/// variably-modified, into the corresponding type with all the known
2179/// sizes replaced with [*].
2180QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2181 // Vastly most common case.
2182 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002183
John McCall06549462011-01-18 08:40:38 +00002184 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002185
John McCall06549462011-01-18 08:40:38 +00002186 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002187 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002188 switch (ty->getTypeClass()) {
2189#define TYPE(Class, Base)
2190#define ABSTRACT_TYPE(Class, Base)
2191#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2192#include "clang/AST/TypeNodes.def"
2193 llvm_unreachable("didn't desugar past all non-canonical types?");
2194
2195 // These types should never be variably-modified.
2196 case Type::Builtin:
2197 case Type::Complex:
2198 case Type::Vector:
2199 case Type::ExtVector:
2200 case Type::DependentSizedExtVector:
2201 case Type::ObjCObject:
2202 case Type::ObjCInterface:
2203 case Type::ObjCObjectPointer:
2204 case Type::Record:
2205 case Type::Enum:
2206 case Type::UnresolvedUsing:
2207 case Type::TypeOfExpr:
2208 case Type::TypeOf:
2209 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002210 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002211 case Type::DependentName:
2212 case Type::InjectedClassName:
2213 case Type::TemplateSpecialization:
2214 case Type::DependentTemplateSpecialization:
2215 case Type::TemplateTypeParm:
2216 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002217 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002218 case Type::PackExpansion:
2219 llvm_unreachable("type should never be variably-modified");
2220
2221 // These types can be variably-modified but should never need to
2222 // further decay.
2223 case Type::FunctionNoProto:
2224 case Type::FunctionProto:
2225 case Type::BlockPointer:
2226 case Type::MemberPointer:
2227 return type;
2228
2229 // These types can be variably-modified. All these modifications
2230 // preserve structure except as noted by comments.
2231 // TODO: if we ever care about optimizing VLAs, there are no-op
2232 // optimizations available here.
2233 case Type::Pointer:
2234 result = getPointerType(getVariableArrayDecayedType(
2235 cast<PointerType>(ty)->getPointeeType()));
2236 break;
2237
2238 case Type::LValueReference: {
2239 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2240 result = getLValueReferenceType(
2241 getVariableArrayDecayedType(lv->getPointeeType()),
2242 lv->isSpelledAsLValue());
2243 break;
2244 }
2245
2246 case Type::RValueReference: {
2247 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2248 result = getRValueReferenceType(
2249 getVariableArrayDecayedType(lv->getPointeeType()));
2250 break;
2251 }
2252
Eli Friedman0dfb8892011-10-06 23:00:33 +00002253 case Type::Atomic: {
2254 const AtomicType *at = cast<AtomicType>(ty);
2255 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2256 break;
2257 }
2258
John McCall06549462011-01-18 08:40:38 +00002259 case Type::ConstantArray: {
2260 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2261 result = getConstantArrayType(
2262 getVariableArrayDecayedType(cat->getElementType()),
2263 cat->getSize(),
2264 cat->getSizeModifier(),
2265 cat->getIndexTypeCVRQualifiers());
2266 break;
2267 }
2268
2269 case Type::DependentSizedArray: {
2270 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2271 result = getDependentSizedArrayType(
2272 getVariableArrayDecayedType(dat->getElementType()),
2273 dat->getSizeExpr(),
2274 dat->getSizeModifier(),
2275 dat->getIndexTypeCVRQualifiers(),
2276 dat->getBracketsRange());
2277 break;
2278 }
2279
2280 // Turn incomplete types into [*] types.
2281 case Type::IncompleteArray: {
2282 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2283 result = getVariableArrayType(
2284 getVariableArrayDecayedType(iat->getElementType()),
2285 /*size*/ 0,
2286 ArrayType::Normal,
2287 iat->getIndexTypeCVRQualifiers(),
2288 SourceRange());
2289 break;
2290 }
2291
2292 // Turn VLA types into [*] types.
2293 case Type::VariableArray: {
2294 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2295 result = getVariableArrayType(
2296 getVariableArrayDecayedType(vat->getElementType()),
2297 /*size*/ 0,
2298 ArrayType::Star,
2299 vat->getIndexTypeCVRQualifiers(),
2300 vat->getBracketsRange());
2301 break;
2302 }
2303 }
2304
2305 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002306 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002307}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002308
Steve Naroffcadebd02007-08-30 18:14:25 +00002309/// getVariableArrayType - Returns a non-unique reference to the type for a
2310/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002311QualType ASTContext::getVariableArrayType(QualType EltTy,
2312 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002313 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002314 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002315 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002316 // Since we don't unique expressions, it isn't possible to unique VLA's
2317 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002318 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002319
John McCall33ddac02011-01-19 10:06:00 +00002320 // Be sure to pull qualifiers off the element type.
2321 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2322 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002323 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002324 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002325 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002326 }
2327
John McCall90d1c2d2009-09-24 23:30:46 +00002328 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002329 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002330
2331 VariableArrayTypes.push_back(New);
2332 Types.push_back(New);
2333 return QualType(New, 0);
2334}
2335
Douglas Gregor4619e432008-12-05 23:32:09 +00002336/// getDependentSizedArrayType - Returns a non-unique reference to
2337/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002338/// type.
John McCall33ddac02011-01-19 10:06:00 +00002339QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2340 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002341 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002342 unsigned elementTypeQuals,
2343 SourceRange brackets) const {
2344 assert((!numElements || numElements->isTypeDependent() ||
2345 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002346 "Size must be type- or value-dependent!");
2347
John McCall33ddac02011-01-19 10:06:00 +00002348 // Dependently-sized array types that do not have a specified number
2349 // of elements will have their sizes deduced from a dependent
2350 // initializer. We do no canonicalization here at all, which is okay
2351 // because they can't be used in most locations.
2352 if (!numElements) {
2353 DependentSizedArrayType *newType
2354 = new (*this, TypeAlignment)
2355 DependentSizedArrayType(*this, elementType, QualType(),
2356 numElements, ASM, elementTypeQuals,
2357 brackets);
2358 Types.push_back(newType);
2359 return QualType(newType, 0);
2360 }
2361
2362 // Otherwise, we actually build a new type every time, but we
2363 // also build a canonical type.
2364
2365 SplitQualType canonElementType = getCanonicalType(elementType).split();
2366
2367 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002368 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002369 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002370 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002371 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002372
John McCall33ddac02011-01-19 10:06:00 +00002373 // Look for an existing type with these properties.
2374 DependentSizedArrayType *canonTy =
2375 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002376
John McCall33ddac02011-01-19 10:06:00 +00002377 // If we don't have one, build one.
2378 if (!canonTy) {
2379 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002380 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002381 QualType(), numElements, ASM, elementTypeQuals,
2382 brackets);
2383 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2384 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002385 }
2386
John McCall33ddac02011-01-19 10:06:00 +00002387 // Apply qualifiers from the element type to the array.
2388 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002389 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002390
John McCall33ddac02011-01-19 10:06:00 +00002391 // If we didn't need extra canonicalization for the element type,
2392 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002393 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002394 return canon;
2395
2396 // Otherwise, we need to build a type which follows the spelling
2397 // of the element type.
2398 DependentSizedArrayType *sugaredType
2399 = new (*this, TypeAlignment)
2400 DependentSizedArrayType(*this, elementType, canon, numElements,
2401 ASM, elementTypeQuals, brackets);
2402 Types.push_back(sugaredType);
2403 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002404}
2405
John McCall33ddac02011-01-19 10:06:00 +00002406QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002407 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002408 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002409 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002410 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002411
John McCall33ddac02011-01-19 10:06:00 +00002412 void *insertPos = 0;
2413 if (IncompleteArrayType *iat =
2414 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2415 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002416
2417 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002418 // either, so fill in the canonical type field. We also have to pull
2419 // qualifiers off the element type.
2420 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002421
John McCall33ddac02011-01-19 10:06:00 +00002422 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2423 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002424 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002425 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002426 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002427
2428 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002429 IncompleteArrayType *existing =
2430 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2431 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002432 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002433
John McCall33ddac02011-01-19 10:06:00 +00002434 IncompleteArrayType *newType = new (*this, TypeAlignment)
2435 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002436
John McCall33ddac02011-01-19 10:06:00 +00002437 IncompleteArrayTypes.InsertNode(newType, insertPos);
2438 Types.push_back(newType);
2439 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002440}
2441
Steve Naroff91fcddb2007-07-18 18:00:27 +00002442/// getVectorType - Return the unique reference to a vector type of
2443/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002444QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002445 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002446 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002447
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002448 // Check if we've already instantiated a vector of this type.
2449 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002450 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002451
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002452 void *InsertPos = 0;
2453 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2454 return QualType(VTP, 0);
2455
2456 // If the element type isn't canonical, this won't be a canonical type either,
2457 // so fill in the canonical type field.
2458 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002459 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002460 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002461
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002462 // Get the new insert position for the node we care about.
2463 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002464 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002465 }
John McCall90d1c2d2009-09-24 23:30:46 +00002466 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002467 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002468 VectorTypes.InsertNode(New, InsertPos);
2469 Types.push_back(New);
2470 return QualType(New, 0);
2471}
2472
Nate Begemance4d7fc2008-04-18 23:10:10 +00002473/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002474/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002475QualType
2476ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002477 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002478
Steve Naroff91fcddb2007-07-18 18:00:27 +00002479 // Check if we've already instantiated a vector of this type.
2480 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002481 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002482 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002483 void *InsertPos = 0;
2484 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2485 return QualType(VTP, 0);
2486
2487 // If the element type isn't canonical, this won't be a canonical type either,
2488 // so fill in the canonical type field.
2489 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002490 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002491 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002492
Steve Naroff91fcddb2007-07-18 18:00:27 +00002493 // Get the new insert position for the node we care about.
2494 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002495 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002496 }
John McCall90d1c2d2009-09-24 23:30:46 +00002497 ExtVectorType *New = new (*this, TypeAlignment)
2498 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002499 VectorTypes.InsertNode(New, InsertPos);
2500 Types.push_back(New);
2501 return QualType(New, 0);
2502}
2503
Jay Foad39c79802011-01-12 09:06:06 +00002504QualType
2505ASTContext::getDependentSizedExtVectorType(QualType vecType,
2506 Expr *SizeExpr,
2507 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002508 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002509 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002510 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002511
Douglas Gregor352169a2009-07-31 03:54:25 +00002512 void *InsertPos = 0;
2513 DependentSizedExtVectorType *Canon
2514 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2515 DependentSizedExtVectorType *New;
2516 if (Canon) {
2517 // We already have a canonical version of this array type; use it as
2518 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002519 New = new (*this, TypeAlignment)
2520 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2521 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002522 } else {
2523 QualType CanonVecTy = getCanonicalType(vecType);
2524 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002525 New = new (*this, TypeAlignment)
2526 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2527 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002528
2529 DependentSizedExtVectorType *CanonCheck
2530 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2531 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2532 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002533 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2534 } else {
2535 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2536 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002537 New = new (*this, TypeAlignment)
2538 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002539 }
2540 }
Mike Stump11289f42009-09-09 15:08:12 +00002541
Douglas Gregor758a8692009-06-17 21:51:59 +00002542 Types.push_back(New);
2543 return QualType(New, 0);
2544}
2545
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002546/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002547///
Jay Foad39c79802011-01-12 09:06:06 +00002548QualType
2549ASTContext::getFunctionNoProtoType(QualType ResultTy,
2550 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002551 const CallingConv DefaultCC = Info.getCC();
2552 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2553 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002554 // Unique functions, to guarantee there is only one function of a particular
2555 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002556 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002557 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002558
Chris Lattner47955de2007-01-27 08:37:20 +00002559 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002560 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002561 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002562 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002563
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002564 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002565 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002566 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002567 Canonical =
2568 getFunctionNoProtoType(getCanonicalType(ResultTy),
2569 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002570
Chris Lattner47955de2007-01-27 08:37:20 +00002571 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002572 FunctionNoProtoType *NewIP =
2573 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002574 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002575 }
Mike Stump11289f42009-09-09 15:08:12 +00002576
Roman Divacky65b88cd2011-03-01 17:40:53 +00002577 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002578 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002579 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002580 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002581 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002582 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002583}
2584
2585/// getFunctionType - Return a normal function type with a typed argument
2586/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002587QualType
2588ASTContext::getFunctionType(QualType ResultTy,
2589 const QualType *ArgArray, unsigned NumArgs,
2590 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002591 // Unique functions, to guarantee there is only one function of a particular
2592 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002593 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002594 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002595
2596 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002597 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002598 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002599 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002600
2601 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002602 bool isCanonical =
2603 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2604 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002605 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002606 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002607 isCanonical = false;
2608
Roman Divacky65b88cd2011-03-01 17:40:53 +00002609 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2610 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2611 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002612
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002613 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002614 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002615 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002616 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002617 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002618 CanonicalArgs.reserve(NumArgs);
2619 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002620 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002621
John McCalldb40c7f2010-12-14 08:05:40 +00002622 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002623 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002624 CanonicalEPI.ExceptionSpecType = EST_None;
2625 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002626 CanonicalEPI.ExtInfo
2627 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2628
Chris Lattner76a00cf2008-04-06 22:59:24 +00002629 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002630 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002631 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002632
Chris Lattnerfd4de792007-01-27 01:15:32 +00002633 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002634 FunctionProtoType *NewIP =
2635 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002636 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002637 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002638
John McCall31168b02011-06-15 23:02:42 +00002639 // FunctionProtoType objects are allocated with extra bytes after
2640 // them for three variable size arrays at the end:
2641 // - parameter types
2642 // - exception types
2643 // - consumed-arguments flags
2644 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002645 // expression, or information used to resolve the exception
2646 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002647 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002648 NumArgs * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002649 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002650 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002651 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002652 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002653 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002654 Size += 2 * sizeof(FunctionDecl*);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002655 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2656 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002657 }
John McCall31168b02011-06-15 23:02:42 +00002658 if (EPI.ConsumedArguments)
2659 Size += NumArgs * sizeof(bool);
2660
John McCalldb40c7f2010-12-14 08:05:40 +00002661 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002662 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2663 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002664 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002665 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002666 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002667 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002668}
Chris Lattneref51c202006-11-10 07:17:23 +00002669
John McCalle78aac42010-03-10 03:28:59 +00002670#ifndef NDEBUG
2671static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2672 if (!isa<CXXRecordDecl>(D)) return false;
2673 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2674 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2675 return true;
2676 if (RD->getDescribedClassTemplate() &&
2677 !isa<ClassTemplateSpecializationDecl>(RD))
2678 return true;
2679 return false;
2680}
2681#endif
2682
2683/// getInjectedClassNameType - Return the unique reference to the
2684/// injected class name type for the specified templated declaration.
2685QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002686 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002687 assert(NeedsInjectedClassNameType(Decl));
2688 if (Decl->TypeForDecl) {
2689 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002690 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002691 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2692 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2693 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2694 } else {
John McCall424cec92011-01-19 06:33:43 +00002695 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002696 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002697 Decl->TypeForDecl = newType;
2698 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002699 }
2700 return QualType(Decl->TypeForDecl, 0);
2701}
2702
Douglas Gregor83a586e2008-04-13 21:07:44 +00002703/// getTypeDeclType - Return the unique reference to the type for the
2704/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002705QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002706 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002707 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002708
Richard Smithdda56e42011-04-15 14:24:37 +00002709 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002710 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002711
John McCall96f0b5f2010-03-10 06:48:02 +00002712 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2713 "Template type parameter types are always available.");
2714
John McCall81e38502010-02-16 03:57:14 +00002715 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002716 assert(!Record->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002717 "struct/union has previous declaration");
2718 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002719 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002720 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002721 assert(!Enum->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002722 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002723 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002724 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002725 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002726 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2727 Decl->TypeForDecl = newType;
2728 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002729 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002730 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002731
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002732 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002733}
2734
Chris Lattner32d920b2007-01-26 02:01:53 +00002735/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002736/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002737QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002738ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2739 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002740 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002741
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002742 if (Canonical.isNull())
2743 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002744 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002745 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002746 Decl->TypeForDecl = newType;
2747 Types.push_back(newType);
2748 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002749}
2750
Jay Foad39c79802011-01-12 09:06:06 +00002751QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002752 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2753
Douglas Gregorec9fd132012-01-14 16:38:05 +00002754 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002755 if (PrevDecl->TypeForDecl)
2756 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2757
John McCall424cec92011-01-19 06:33:43 +00002758 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2759 Decl->TypeForDecl = newType;
2760 Types.push_back(newType);
2761 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002762}
2763
Jay Foad39c79802011-01-12 09:06:06 +00002764QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002765 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2766
Douglas Gregorec9fd132012-01-14 16:38:05 +00002767 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002768 if (PrevDecl->TypeForDecl)
2769 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2770
John McCall424cec92011-01-19 06:33:43 +00002771 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2772 Decl->TypeForDecl = newType;
2773 Types.push_back(newType);
2774 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002775}
2776
John McCall81904512011-01-06 01:58:22 +00002777QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2778 QualType modifiedType,
2779 QualType equivalentType) {
2780 llvm::FoldingSetNodeID id;
2781 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2782
2783 void *insertPos = 0;
2784 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2785 if (type) return QualType(type, 0);
2786
2787 QualType canon = getCanonicalType(equivalentType);
2788 type = new (*this, TypeAlignment)
2789 AttributedType(canon, attrKind, modifiedType, equivalentType);
2790
2791 Types.push_back(type);
2792 AttributedTypes.InsertNode(type, insertPos);
2793
2794 return QualType(type, 0);
2795}
2796
2797
John McCallcebee162009-10-18 09:09:24 +00002798/// \brief Retrieve a substitution-result type.
2799QualType
2800ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002801 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002802 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002803 && "replacement types must always be canonical");
2804
2805 llvm::FoldingSetNodeID ID;
2806 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2807 void *InsertPos = 0;
2808 SubstTemplateTypeParmType *SubstParm
2809 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2810
2811 if (!SubstParm) {
2812 SubstParm = new (*this, TypeAlignment)
2813 SubstTemplateTypeParmType(Parm, Replacement);
2814 Types.push_back(SubstParm);
2815 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2816 }
2817
2818 return QualType(SubstParm, 0);
2819}
2820
Douglas Gregorada4b792011-01-14 02:55:32 +00002821/// \brief Retrieve a
2822QualType ASTContext::getSubstTemplateTypeParmPackType(
2823 const TemplateTypeParmType *Parm,
2824 const TemplateArgument &ArgPack) {
2825#ifndef NDEBUG
2826 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2827 PEnd = ArgPack.pack_end();
2828 P != PEnd; ++P) {
2829 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2830 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2831 }
2832#endif
2833
2834 llvm::FoldingSetNodeID ID;
2835 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2836 void *InsertPos = 0;
2837 if (SubstTemplateTypeParmPackType *SubstParm
2838 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2839 return QualType(SubstParm, 0);
2840
2841 QualType Canon;
2842 if (!Parm->isCanonicalUnqualified()) {
2843 Canon = getCanonicalType(QualType(Parm, 0));
2844 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2845 ArgPack);
2846 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2847 }
2848
2849 SubstTemplateTypeParmPackType *SubstParm
2850 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2851 ArgPack);
2852 Types.push_back(SubstParm);
2853 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2854 return QualType(SubstParm, 0);
2855}
2856
Douglas Gregoreff93e02009-02-05 23:33:38 +00002857/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002858/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002859/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002860QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002861 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002862 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002863 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002864 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002865 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002866 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002867 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2868
2869 if (TypeParm)
2870 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002871
Chandler Carruth08836322011-05-01 00:51:33 +00002872 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002873 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002874 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002875
2876 TemplateTypeParmType *TypeCheck
2877 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2878 assert(!TypeCheck && "Template type parameter canonical type broken");
2879 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002880 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002881 TypeParm = new (*this, TypeAlignment)
2882 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002883
2884 Types.push_back(TypeParm);
2885 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2886
2887 return QualType(TypeParm, 0);
2888}
2889
John McCalle78aac42010-03-10 03:28:59 +00002890TypeSourceInfo *
2891ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2892 SourceLocation NameLoc,
2893 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002894 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002895 assert(!Name.getAsDependentTemplateName() &&
2896 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002897 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002898
2899 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2900 TemplateSpecializationTypeLoc TL
2901 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002902 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00002903 TL.setTemplateNameLoc(NameLoc);
2904 TL.setLAngleLoc(Args.getLAngleLoc());
2905 TL.setRAngleLoc(Args.getRAngleLoc());
2906 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2907 TL.setArgLocInfo(i, Args[i].getLocInfo());
2908 return DI;
2909}
2910
Mike Stump11289f42009-09-09 15:08:12 +00002911QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002912ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002913 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002914 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002915 assert(!Template.getAsDependentTemplateName() &&
2916 "No dependent template names here!");
2917
John McCall6b51f282009-11-23 01:53:49 +00002918 unsigned NumArgs = Args.size();
2919
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002920 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002921 ArgVec.reserve(NumArgs);
2922 for (unsigned i = 0; i != NumArgs; ++i)
2923 ArgVec.push_back(Args[i].getArgument());
2924
John McCall2408e322010-04-27 00:57:59 +00002925 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002926 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002927}
2928
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002929#ifndef NDEBUG
2930static bool hasAnyPackExpansions(const TemplateArgument *Args,
2931 unsigned NumArgs) {
2932 for (unsigned I = 0; I != NumArgs; ++I)
2933 if (Args[I].isPackExpansion())
2934 return true;
2935
2936 return true;
2937}
2938#endif
2939
John McCall0ad16662009-10-29 08:12:44 +00002940QualType
2941ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002942 const TemplateArgument *Args,
2943 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002944 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002945 assert(!Template.getAsDependentTemplateName() &&
2946 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002947 // Look through qualified template names.
2948 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2949 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002950
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002951 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00002952 Template.getAsTemplateDecl() &&
2953 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00002954 QualType CanonType;
2955 if (!Underlying.isNull())
2956 CanonType = getCanonicalType(Underlying);
2957 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002958 // We can get here with an alias template when the specialization contains
2959 // a pack expansion that does not match up with a parameter pack.
2960 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2961 "Caller must compute aliased type");
2962 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00002963 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2964 NumArgs);
2965 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002966
Douglas Gregora8e02e72009-07-28 23:00:59 +00002967 // Allocate the (non-canonical) template specialization type, but don't
2968 // try to unique it: these types typically have location information that
2969 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002970 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2971 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002972 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002973 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002974 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002975 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2976 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002977
Douglas Gregor8bf42052009-02-09 18:46:07 +00002978 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002979 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002980}
2981
Mike Stump11289f42009-09-09 15:08:12 +00002982QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002983ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2984 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002985 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002986 assert(!Template.getAsDependentTemplateName() &&
2987 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002988
Douglas Gregore29139c2011-03-03 17:04:51 +00002989 // Look through qualified template names.
2990 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2991 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002992
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002993 // Build the canonical template specialization type.
2994 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002995 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002996 CanonArgs.reserve(NumArgs);
2997 for (unsigned I = 0; I != NumArgs; ++I)
2998 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2999
3000 // Determine whether this canonical template specialization type already
3001 // exists.
3002 llvm::FoldingSetNodeID ID;
3003 TemplateSpecializationType::Profile(ID, CanonTemplate,
3004 CanonArgs.data(), NumArgs, *this);
3005
3006 void *InsertPos = 0;
3007 TemplateSpecializationType *Spec
3008 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3009
3010 if (!Spec) {
3011 // Allocate a new canonical template specialization type.
3012 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3013 sizeof(TemplateArgument) * NumArgs),
3014 TypeAlignment);
3015 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3016 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003017 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003018 Types.push_back(Spec);
3019 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3020 }
3021
3022 assert(Spec->isDependentType() &&
3023 "Non-dependent template-id type must have a canonical type");
3024 return QualType(Spec, 0);
3025}
3026
3027QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003028ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3029 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003030 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003031 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003032 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003033
3034 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003035 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003036 if (T)
3037 return QualType(T, 0);
3038
Douglas Gregorc42075a2010-02-04 18:10:26 +00003039 QualType Canon = NamedType;
3040 if (!Canon.isCanonical()) {
3041 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003042 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3043 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003044 (void)CheckT;
3045 }
3046
Abramo Bagnara6150c882010-05-11 21:36:43 +00003047 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003048 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003049 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003050 return QualType(T, 0);
3051}
3052
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003053QualType
Jay Foad39c79802011-01-12 09:06:06 +00003054ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003055 llvm::FoldingSetNodeID ID;
3056 ParenType::Profile(ID, InnerType);
3057
3058 void *InsertPos = 0;
3059 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3060 if (T)
3061 return QualType(T, 0);
3062
3063 QualType Canon = InnerType;
3064 if (!Canon.isCanonical()) {
3065 Canon = getCanonicalType(InnerType);
3066 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3067 assert(!CheckT && "Paren canonical type broken");
3068 (void)CheckT;
3069 }
3070
3071 T = new (*this) ParenType(InnerType, Canon);
3072 Types.push_back(T);
3073 ParenTypes.InsertNode(T, InsertPos);
3074 return QualType(T, 0);
3075}
3076
Douglas Gregor02085352010-03-31 20:19:30 +00003077QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3078 NestedNameSpecifier *NNS,
3079 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003080 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003081 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3082
3083 if (Canon.isNull()) {
3084 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003085 ElaboratedTypeKeyword CanonKeyword = Keyword;
3086 if (Keyword == ETK_None)
3087 CanonKeyword = ETK_Typename;
3088
3089 if (CanonNNS != NNS || CanonKeyword != Keyword)
3090 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003091 }
3092
3093 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003094 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003095
3096 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003097 DependentNameType *T
3098 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003099 if (T)
3100 return QualType(T, 0);
3101
Douglas Gregor02085352010-03-31 20:19:30 +00003102 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003103 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003104 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003105 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003106}
3107
Mike Stump11289f42009-09-09 15:08:12 +00003108QualType
John McCallc392f372010-06-11 00:33:02 +00003109ASTContext::getDependentTemplateSpecializationType(
3110 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003111 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003112 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003113 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003114 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003115 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003116 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3117 ArgCopy.push_back(Args[I].getArgument());
3118 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3119 ArgCopy.size(),
3120 ArgCopy.data());
3121}
3122
3123QualType
3124ASTContext::getDependentTemplateSpecializationType(
3125 ElaboratedTypeKeyword Keyword,
3126 NestedNameSpecifier *NNS,
3127 const IdentifierInfo *Name,
3128 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003129 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003130 assert((!NNS || NNS->isDependent()) &&
3131 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003132
Douglas Gregorc42075a2010-02-04 18:10:26 +00003133 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003134 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3135 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003136
3137 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00003138 DependentTemplateSpecializationType *T
3139 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003140 if (T)
3141 return QualType(T, 0);
3142
John McCallc392f372010-06-11 00:33:02 +00003143 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003144
John McCallc392f372010-06-11 00:33:02 +00003145 ElaboratedTypeKeyword CanonKeyword = Keyword;
3146 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3147
3148 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003149 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003150 for (unsigned I = 0; I != NumArgs; ++I) {
3151 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3152 if (!CanonArgs[I].structurallyEquals(Args[I]))
3153 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003154 }
3155
John McCallc392f372010-06-11 00:33:02 +00003156 QualType Canon;
3157 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3158 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3159 Name, NumArgs,
3160 CanonArgs.data());
3161
3162 // Find the insert position again.
3163 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3164 }
3165
3166 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3167 sizeof(TemplateArgument) * NumArgs),
3168 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003169 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003170 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003171 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003172 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003173 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003174}
3175
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003176QualType ASTContext::getPackExpansionType(QualType Pattern,
3177 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003178 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003179 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003180
3181 assert(Pattern->containsUnexpandedParameterPack() &&
3182 "Pack expansions must expand one or more parameter packs");
3183 void *InsertPos = 0;
3184 PackExpansionType *T
3185 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3186 if (T)
3187 return QualType(T, 0);
3188
3189 QualType Canon;
3190 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003191 Canon = getCanonicalType(Pattern);
3192 // The canonical type might not contain an unexpanded parameter pack, if it
3193 // contains an alias template specialization which ignores one of its
3194 // parameters.
3195 if (Canon->containsUnexpandedParameterPack()) {
3196 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003197
Richard Smith68eea502012-07-16 00:20:35 +00003198 // Find the insert position again, in case we inserted an element into
3199 // PackExpansionTypes and invalidated our insert position.
3200 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3201 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003202 }
3203
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003204 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003205 Types.push_back(T);
3206 PackExpansionTypes.InsertNode(T, InsertPos);
3207 return QualType(T, 0);
3208}
3209
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003210/// CmpProtocolNames - Comparison predicate for sorting protocols
3211/// alphabetically.
3212static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3213 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003214 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003215}
3216
John McCall8b07ec22010-05-15 11:32:37 +00003217static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003218 unsigned NumProtocols) {
3219 if (NumProtocols == 0) return true;
3220
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003221 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3222 return false;
3223
John McCallfc93cf92009-10-22 22:37:11 +00003224 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003225 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3226 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003227 return false;
3228 return true;
3229}
3230
3231static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003232 unsigned &NumProtocols) {
3233 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003234
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003235 // Sort protocols, keyed by name.
3236 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3237
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003238 // Canonicalize.
3239 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3240 Protocols[I] = Protocols[I]->getCanonicalDecl();
3241
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003242 // Remove duplicates.
3243 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3244 NumProtocols = ProtocolsEnd-Protocols;
3245}
3246
John McCall8b07ec22010-05-15 11:32:37 +00003247QualType ASTContext::getObjCObjectType(QualType BaseType,
3248 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003249 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003250 // If the base type is an interface and there aren't any protocols
3251 // to add, then the interface type will do just fine.
3252 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3253 return BaseType;
3254
3255 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003256 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003257 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00003258 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00003259 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3260 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003261
John McCall8b07ec22010-05-15 11:32:37 +00003262 // Build the canonical type, which has the canonical base type and
3263 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003264 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003265 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3266 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3267 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003268 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003269 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003270 unsigned UniqueCount = NumProtocols;
3271
John McCallfc93cf92009-10-22 22:37:11 +00003272 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003273 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3274 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003275 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003276 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3277 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003278 }
3279
3280 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003281 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3282 }
3283
3284 unsigned Size = sizeof(ObjCObjectTypeImpl);
3285 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3286 void *Mem = Allocate(Size, TypeAlignment);
3287 ObjCObjectTypeImpl *T =
3288 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3289
3290 Types.push_back(T);
3291 ObjCObjectTypes.InsertNode(T, InsertPos);
3292 return QualType(T, 0);
3293}
3294
3295/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3296/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003297QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003298 llvm::FoldingSetNodeID ID;
3299 ObjCObjectPointerType::Profile(ID, ObjectT);
3300
3301 void *InsertPos = 0;
3302 if (ObjCObjectPointerType *QT =
3303 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3304 return QualType(QT, 0);
3305
3306 // Find the canonical object type.
3307 QualType Canonical;
3308 if (!ObjectT.isCanonical()) {
3309 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3310
3311 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003312 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3313 }
3314
Douglas Gregorf85bee62010-02-08 22:59:26 +00003315 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003316 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3317 ObjCObjectPointerType *QType =
3318 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003319
Steve Narofffb4330f2009-06-17 22:40:22 +00003320 Types.push_back(QType);
3321 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003322 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003323}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003324
Douglas Gregor1c283312010-08-11 12:19:30 +00003325/// getObjCInterfaceType - Return the unique reference to the type for the
3326/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003327QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3328 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003329 if (Decl->TypeForDecl)
3330 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003331
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003332 if (PrevDecl) {
3333 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3334 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3335 return QualType(PrevDecl->TypeForDecl, 0);
3336 }
3337
Douglas Gregor7671e532011-12-16 16:34:57 +00003338 // Prefer the definition, if there is one.
3339 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3340 Decl = Def;
3341
Douglas Gregor1c283312010-08-11 12:19:30 +00003342 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3343 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3344 Decl->TypeForDecl = T;
3345 Types.push_back(T);
3346 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003347}
3348
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003349/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3350/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003351/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003352/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003353/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003354QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003355 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003356 if (tofExpr->isTypeDependent()) {
3357 llvm::FoldingSetNodeID ID;
3358 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003359
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003360 void *InsertPos = 0;
3361 DependentTypeOfExprType *Canon
3362 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3363 if (Canon) {
3364 // We already have a "canonical" version of an identical, dependent
3365 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003366 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003367 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003368 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003369 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003370 Canon
3371 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003372 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3373 toe = Canon;
3374 }
3375 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003376 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003377 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003378 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003379 Types.push_back(toe);
3380 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003381}
3382
Steve Naroffa773cd52007-08-01 18:02:17 +00003383/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3384/// TypeOfType AST's. The only motivation to unique these nodes would be
3385/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003386/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003387/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003388QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003389 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003390 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003391 Types.push_back(tot);
3392 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003393}
3394
Anders Carlssonad6bd352009-06-24 21:24:56 +00003395
Anders Carlsson81df7b82009-06-24 19:06:50 +00003396/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3397/// DecltypeType AST's. The only motivation to unique these nodes would be
3398/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003399/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003400/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003401QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003402 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003403
3404 // C++0x [temp.type]p2:
3405 // If an expression e involves a template parameter, decltype(e) denotes a
3406 // unique dependent type. Two such decltype-specifiers refer to the same
3407 // type only if their expressions are equivalent (14.5.6.1).
3408 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003409 llvm::FoldingSetNodeID ID;
3410 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003411
Douglas Gregora21f6c32009-07-30 23:36:40 +00003412 void *InsertPos = 0;
3413 DependentDecltypeType *Canon
3414 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3415 if (Canon) {
3416 // We already have a "canonical" version of an equivalent, dependent
3417 // decltype type. Use that as our canonical type.
Richard Smithef8bf432012-08-13 20:08:14 +00003418 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003419 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003420 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003421 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003422 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003423 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3424 dt = Canon;
3425 }
3426 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003427 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3428 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003429 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003430 Types.push_back(dt);
3431 return QualType(dt, 0);
3432}
3433
Alexis Hunte852b102011-05-24 22:41:36 +00003434/// getUnaryTransformationType - We don't unique these, since the memory
3435/// savings are minimal and these are rare.
3436QualType ASTContext::getUnaryTransformType(QualType BaseType,
3437 QualType UnderlyingType,
3438 UnaryTransformType::UTTKind Kind)
3439 const {
3440 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003441 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3442 Kind,
3443 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003444 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003445 Types.push_back(Ty);
3446 return QualType(Ty, 0);
3447}
3448
Richard Smithb2bc2e62011-02-21 20:05:19 +00003449/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003450QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00003451 void *InsertPos = 0;
3452 if (!DeducedType.isNull()) {
3453 // Look in the folding set for an existing type.
3454 llvm::FoldingSetNodeID ID;
3455 AutoType::Profile(ID, DeducedType);
3456 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3457 return QualType(AT, 0);
3458 }
3459
3460 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3461 Types.push_back(AT);
3462 if (InsertPos)
3463 AutoTypes.InsertNode(AT, InsertPos);
3464 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003465}
3466
Eli Friedman0dfb8892011-10-06 23:00:33 +00003467/// getAtomicType - Return the uniqued reference to the atomic type for
3468/// the given value type.
3469QualType ASTContext::getAtomicType(QualType T) const {
3470 // Unique pointers, to guarantee there is only one pointer of a particular
3471 // structure.
3472 llvm::FoldingSetNodeID ID;
3473 AtomicType::Profile(ID, T);
3474
3475 void *InsertPos = 0;
3476 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3477 return QualType(AT, 0);
3478
3479 // If the atomic value type isn't canonical, this won't be a canonical type
3480 // either, so fill in the canonical type field.
3481 QualType Canonical;
3482 if (!T.isCanonical()) {
3483 Canonical = getAtomicType(getCanonicalType(T));
3484
3485 // Get the new insert position for the node we care about.
3486 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3487 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3488 }
3489 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3490 Types.push_back(New);
3491 AtomicTypes.InsertNode(New, InsertPos);
3492 return QualType(New, 0);
3493}
3494
Richard Smith02e85f32011-04-14 22:09:26 +00003495/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3496QualType ASTContext::getAutoDeductType() const {
3497 if (AutoDeductTy.isNull())
3498 AutoDeductTy = getAutoType(QualType());
3499 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3500 return AutoDeductTy;
3501}
3502
3503/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3504QualType ASTContext::getAutoRRefDeductType() const {
3505 if (AutoRRefDeductTy.isNull())
3506 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3507 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3508 return AutoRRefDeductTy;
3509}
3510
Chris Lattnerfb072462007-01-23 05:45:31 +00003511/// getTagDeclType - Return the unique reference to the type for the
3512/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003513QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003514 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003515 // FIXME: What is the design on getTagDeclType when it requires casting
3516 // away const? mutable?
3517 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003518}
3519
Mike Stump11289f42009-09-09 15:08:12 +00003520/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3521/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3522/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003523CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003524 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003525}
Chris Lattnerfb072462007-01-23 05:45:31 +00003526
Hans Wennborg27541db2011-10-27 08:29:09 +00003527/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3528CanQualType ASTContext::getIntMaxType() const {
3529 return getFromTargetType(Target->getIntMaxType());
3530}
3531
3532/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3533CanQualType ASTContext::getUIntMaxType() const {
3534 return getFromTargetType(Target->getUIntMaxType());
3535}
3536
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003537/// getSignedWCharType - Return the type of "signed wchar_t".
3538/// Used when in C++, as a GCC extension.
3539QualType ASTContext::getSignedWCharType() const {
3540 // FIXME: derive from "Target" ?
3541 return WCharTy;
3542}
3543
3544/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3545/// Used when in C++, as a GCC extension.
3546QualType ASTContext::getUnsignedWCharType() const {
3547 // FIXME: derive from "Target" ?
3548 return UnsignedIntTy;
3549}
3550
Hans Wennborg27541db2011-10-27 08:29:09 +00003551/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003552/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3553QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003554 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003555}
3556
Eli Friedman4e91899e2012-11-27 02:58:24 +00003557/// \brief Return the unique type for "pid_t" defined in
3558/// <sys/types.h>. We need this to compute the correct type for vfork().
3559QualType ASTContext::getProcessIDType() const {
3560 return getFromTargetType(Target->getProcessIDType());
3561}
3562
Chris Lattnera21ad802008-04-02 05:18:44 +00003563//===----------------------------------------------------------------------===//
3564// Type Operators
3565//===----------------------------------------------------------------------===//
3566
Jay Foad39c79802011-01-12 09:06:06 +00003567CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003568 // Push qualifiers into arrays, and then discard any remaining
3569 // qualifiers.
3570 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003571 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003572 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003573 QualType Result;
3574 if (isa<ArrayType>(Ty)) {
3575 Result = getArrayDecayedType(QualType(Ty,0));
3576 } else if (isa<FunctionType>(Ty)) {
3577 Result = getPointerType(QualType(Ty, 0));
3578 } else {
3579 Result = QualType(Ty, 0);
3580 }
3581
3582 return CanQualType::CreateUnsafe(Result);
3583}
3584
John McCall6c9dd522011-01-18 07:41:22 +00003585QualType ASTContext::getUnqualifiedArrayType(QualType type,
3586 Qualifiers &quals) {
3587 SplitQualType splitType = type.getSplitUnqualifiedType();
3588
3589 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3590 // the unqualified desugared type and then drops it on the floor.
3591 // We then have to strip that sugar back off with
3592 // getUnqualifiedDesugaredType(), which is silly.
3593 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003594 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003595
3596 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003597 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003598 quals = splitType.Quals;
3599 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003600 }
3601
John McCall6c9dd522011-01-18 07:41:22 +00003602 // Otherwise, recurse on the array's element type.
3603 QualType elementType = AT->getElementType();
3604 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3605
3606 // If that didn't change the element type, AT has no qualifiers, so we
3607 // can just use the results in splitType.
3608 if (elementType == unqualElementType) {
3609 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003610 quals = splitType.Quals;
3611 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003612 }
3613
3614 // Otherwise, add in the qualifiers from the outermost type, then
3615 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003616 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003617
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003618 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003619 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003620 CAT->getSizeModifier(), 0);
3621 }
3622
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003623 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003624 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003625 }
3626
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003627 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003628 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003629 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003630 VAT->getSizeModifier(),
3631 VAT->getIndexTypeCVRQualifiers(),
3632 VAT->getBracketsRange());
3633 }
3634
3635 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003636 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003637 DSAT->getSizeModifier(), 0,
3638 SourceRange());
3639}
3640
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003641/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3642/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3643/// they point to and return true. If T1 and T2 aren't pointer types
3644/// or pointer-to-member types, or if they are not similar at this
3645/// level, returns false and leaves T1 and T2 unchanged. Top-level
3646/// qualifiers on T1 and T2 are ignored. This function will typically
3647/// be called in a loop that successively "unwraps" pointer and
3648/// pointer-to-member types to compare them at each level.
3649bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3650 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3651 *T2PtrType = T2->getAs<PointerType>();
3652 if (T1PtrType && T2PtrType) {
3653 T1 = T1PtrType->getPointeeType();
3654 T2 = T2PtrType->getPointeeType();
3655 return true;
3656 }
3657
3658 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3659 *T2MPType = T2->getAs<MemberPointerType>();
3660 if (T1MPType && T2MPType &&
3661 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3662 QualType(T2MPType->getClass(), 0))) {
3663 T1 = T1MPType->getPointeeType();
3664 T2 = T2MPType->getPointeeType();
3665 return true;
3666 }
3667
David Blaikiebbafb8a2012-03-11 07:00:24 +00003668 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003669 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3670 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3671 if (T1OPType && T2OPType) {
3672 T1 = T1OPType->getPointeeType();
3673 T2 = T2OPType->getPointeeType();
3674 return true;
3675 }
3676 }
3677
3678 // FIXME: Block pointers, too?
3679
3680 return false;
3681}
3682
Jay Foad39c79802011-01-12 09:06:06 +00003683DeclarationNameInfo
3684ASTContext::getNameForTemplate(TemplateName Name,
3685 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003686 switch (Name.getKind()) {
3687 case TemplateName::QualifiedTemplate:
3688 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003689 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003690 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3691 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003692
John McCalld9dfe3a2011-06-30 08:33:18 +00003693 case TemplateName::OverloadedTemplate: {
3694 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3695 // DNInfo work in progress: CHECKME: what about DNLoc?
3696 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3697 }
3698
3699 case TemplateName::DependentTemplate: {
3700 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003701 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003702 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003703 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3704 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003705 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003706 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3707 // DNInfo work in progress: FIXME: source locations?
3708 DeclarationNameLoc DNLoc;
3709 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3710 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3711 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003712 }
3713 }
3714
John McCalld9dfe3a2011-06-30 08:33:18 +00003715 case TemplateName::SubstTemplateTemplateParm: {
3716 SubstTemplateTemplateParmStorage *subst
3717 = Name.getAsSubstTemplateTemplateParm();
3718 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3719 NameLoc);
3720 }
3721
3722 case TemplateName::SubstTemplateTemplateParmPack: {
3723 SubstTemplateTemplateParmPackStorage *subst
3724 = Name.getAsSubstTemplateTemplateParmPack();
3725 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3726 NameLoc);
3727 }
3728 }
3729
3730 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003731}
3732
Jay Foad39c79802011-01-12 09:06:06 +00003733TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003734 switch (Name.getKind()) {
3735 case TemplateName::QualifiedTemplate:
3736 case TemplateName::Template: {
3737 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003738 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003739 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003740 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3741
3742 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003743 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003744 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003745
John McCalld9dfe3a2011-06-30 08:33:18 +00003746 case TemplateName::OverloadedTemplate:
3747 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003748
John McCalld9dfe3a2011-06-30 08:33:18 +00003749 case TemplateName::DependentTemplate: {
3750 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3751 assert(DTN && "Non-dependent template names must refer to template decls.");
3752 return DTN->CanonicalTemplateName;
3753 }
3754
3755 case TemplateName::SubstTemplateTemplateParm: {
3756 SubstTemplateTemplateParmStorage *subst
3757 = Name.getAsSubstTemplateTemplateParm();
3758 return getCanonicalTemplateName(subst->getReplacement());
3759 }
3760
3761 case TemplateName::SubstTemplateTemplateParmPack: {
3762 SubstTemplateTemplateParmPackStorage *subst
3763 = Name.getAsSubstTemplateTemplateParmPack();
3764 TemplateTemplateParmDecl *canonParameter
3765 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3766 TemplateArgument canonArgPack
3767 = getCanonicalTemplateArgument(subst->getArgumentPack());
3768 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3769 }
3770 }
3771
3772 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003773}
3774
Douglas Gregoradee3e32009-11-11 23:06:43 +00003775bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3776 X = getCanonicalTemplateName(X);
3777 Y = getCanonicalTemplateName(Y);
3778 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3779}
3780
Mike Stump11289f42009-09-09 15:08:12 +00003781TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003782ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003783 switch (Arg.getKind()) {
3784 case TemplateArgument::Null:
3785 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003786
Douglas Gregora8e02e72009-07-28 23:00:59 +00003787 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003788 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003789
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003790 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00003791 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
3792 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003793 }
Mike Stump11289f42009-09-09 15:08:12 +00003794
Eli Friedmanb826a002012-09-26 02:36:12 +00003795 case TemplateArgument::NullPtr:
3796 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
3797 /*isNullPtr*/true);
3798
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003799 case TemplateArgument::Template:
3800 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003801
3802 case TemplateArgument::TemplateExpansion:
3803 return TemplateArgument(getCanonicalTemplateName(
3804 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003805 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003806
Douglas Gregora8e02e72009-07-28 23:00:59 +00003807 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00003808 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003809
Douglas Gregora8e02e72009-07-28 23:00:59 +00003810 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003811 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003812
Douglas Gregora8e02e72009-07-28 23:00:59 +00003813 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003814 if (Arg.pack_size() == 0)
3815 return Arg;
3816
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003817 TemplateArgument *CanonArgs
3818 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003819 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003820 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003821 AEnd = Arg.pack_end();
3822 A != AEnd; (void)++A, ++Idx)
3823 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003824
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003825 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003826 }
3827 }
3828
3829 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003830 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003831}
3832
Douglas Gregor333489b2009-03-27 23:10:48 +00003833NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003834ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003835 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003836 return 0;
3837
3838 switch (NNS->getKind()) {
3839 case NestedNameSpecifier::Identifier:
3840 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003841 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003842 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3843 NNS->getAsIdentifier());
3844
3845 case NestedNameSpecifier::Namespace:
3846 // A namespace is canonical; build a nested-name-specifier with
3847 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003848 return NestedNameSpecifier::Create(*this, 0,
3849 NNS->getAsNamespace()->getOriginalNamespace());
3850
3851 case NestedNameSpecifier::NamespaceAlias:
3852 // A namespace is canonical; build a nested-name-specifier with
3853 // this namespace and no prefix.
3854 return NestedNameSpecifier::Create(*this, 0,
3855 NNS->getAsNamespaceAlias()->getNamespace()
3856 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003857
3858 case NestedNameSpecifier::TypeSpec:
3859 case NestedNameSpecifier::TypeSpecWithTemplate: {
3860 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003861
3862 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3863 // break it apart into its prefix and identifier, then reconsititute those
3864 // as the canonical nested-name-specifier. This is required to canonicalize
3865 // a dependent nested-name-specifier involving typedefs of dependent-name
3866 // types, e.g.,
3867 // typedef typename T::type T1;
3868 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00003869 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3870 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00003871 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003872
Eli Friedman5358a0a2012-03-03 04:09:56 +00003873 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3874 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3875 // first place?
John McCall33ddac02011-01-19 10:06:00 +00003876 return NestedNameSpecifier::Create(*this, 0, false,
3877 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003878 }
3879
3880 case NestedNameSpecifier::Global:
3881 // The global specifier is canonical and unique.
3882 return NNS;
3883 }
3884
David Blaikie8a40f702012-01-17 06:56:22 +00003885 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00003886}
3887
Chris Lattner7adf0762008-08-04 07:31:14 +00003888
Jay Foad39c79802011-01-12 09:06:06 +00003889const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003890 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003891 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003892 // Handle the common positive case fast.
3893 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3894 return AT;
3895 }
Mike Stump11289f42009-09-09 15:08:12 +00003896
John McCall8ccfcb52009-09-24 19:53:00 +00003897 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003898 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003899 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003900
John McCall8ccfcb52009-09-24 19:53:00 +00003901 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003902 // implements C99 6.7.3p8: "If the specification of an array type includes
3903 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003904
Chris Lattner7adf0762008-08-04 07:31:14 +00003905 // If we get here, we either have type qualifiers on the type, or we have
3906 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003907 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003908
John McCall33ddac02011-01-19 10:06:00 +00003909 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003910 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00003911
Chris Lattner7adf0762008-08-04 07:31:14 +00003912 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00003913 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00003914 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003915 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003916
Chris Lattner7adf0762008-08-04 07:31:14 +00003917 // Otherwise, we have an array and we have qualifiers on it. Push the
3918 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003919 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003920
Chris Lattner7adf0762008-08-04 07:31:14 +00003921 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3922 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3923 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003924 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003925 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3926 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3927 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003928 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003929
Mike Stump11289f42009-09-09 15:08:12 +00003930 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003931 = dyn_cast<DependentSizedArrayType>(ATy))
3932 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003933 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003934 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003935 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003936 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003937 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003938
Chris Lattner7adf0762008-08-04 07:31:14 +00003939 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003940 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003941 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003942 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003943 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003944 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003945}
3946
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003947QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003948 // C99 6.7.5.3p7:
3949 // A declaration of a parameter as "array of type" shall be
3950 // adjusted to "qualified pointer to type", where the type
3951 // qualifiers (if any) are those specified within the [ and ] of
3952 // the array type derivation.
3953 if (T->isArrayType())
3954 return getArrayDecayedType(T);
3955
3956 // C99 6.7.5.3p8:
3957 // A declaration of a parameter as "function returning type"
3958 // shall be adjusted to "pointer to function returning type", as
3959 // in 6.3.2.1.
3960 if (T->isFunctionType())
3961 return getPointerType(T);
3962
3963 return T;
3964}
3965
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003966QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003967 T = getVariableArrayDecayedType(T);
3968 T = getAdjustedParameterType(T);
3969 return T.getUnqualifiedType();
3970}
3971
Chris Lattnera21ad802008-04-02 05:18:44 +00003972/// getArrayDecayedType - Return the properly qualified result of decaying the
3973/// specified array type to a pointer. This operation is non-trivial when
3974/// handling typedefs etc. The canonical type of "T" must be an array type,
3975/// this returns a pointer to a properly qualified element of the array.
3976///
3977/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003978QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003979 // Get the element type with 'getAsArrayType' so that we don't lose any
3980 // typedefs in the element type of the array. This also handles propagation
3981 // of type qualifiers from the array type into the element type if present
3982 // (C99 6.7.3p8).
3983 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3984 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003985
Chris Lattner7adf0762008-08-04 07:31:14 +00003986 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003987
3988 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003989 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003990}
3991
John McCall33ddac02011-01-19 10:06:00 +00003992QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3993 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003994}
3995
John McCall33ddac02011-01-19 10:06:00 +00003996QualType ASTContext::getBaseElementType(QualType type) const {
3997 Qualifiers qs;
3998 while (true) {
3999 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004000 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004001 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004002
John McCall33ddac02011-01-19 10:06:00 +00004003 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004004 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004005 }
Mike Stump11289f42009-09-09 15:08:12 +00004006
John McCall33ddac02011-01-19 10:06:00 +00004007 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004008}
4009
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004010/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004011uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004012ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4013 uint64_t ElementCount = 1;
4014 do {
4015 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004016 CA = dyn_cast_or_null<ConstantArrayType>(
4017 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004018 } while (CA);
4019 return ElementCount;
4020}
4021
Steve Naroff0af91202007-04-27 21:51:21 +00004022/// getFloatingRank - Return a relative rank for floating point types.
4023/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004024static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004025 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004026 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004027
John McCall9dd450b2009-09-21 23:43:11 +00004028 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4029 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004030 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004031 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004032 case BuiltinType::Float: return FloatRank;
4033 case BuiltinType::Double: return DoubleRank;
4034 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004035 }
4036}
4037
Mike Stump11289f42009-09-09 15:08:12 +00004038/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4039/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004040/// 'typeDomain' is a real floating point or complex type.
4041/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004042QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4043 QualType Domain) const {
4044 FloatingRank EltRank = getFloatingRank(Size);
4045 if (Domain->isComplexType()) {
4046 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004047 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004048 case FloatRank: return FloatComplexTy;
4049 case DoubleRank: return DoubleComplexTy;
4050 case LongDoubleRank: return LongDoubleComplexTy;
4051 }
Steve Naroff0af91202007-04-27 21:51:21 +00004052 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004053
4054 assert(Domain->isRealFloatingType() && "Unknown domain!");
4055 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004056 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004057 case FloatRank: return FloatTy;
4058 case DoubleRank: return DoubleTy;
4059 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004060 }
David Blaikief47fa302012-01-17 02:30:50 +00004061 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004062}
4063
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004064/// getFloatingTypeOrder - Compare the rank of the two specified floating
4065/// point types, ignoring the domain of the type (i.e. 'double' ==
4066/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004067/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004068int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004069 FloatingRank LHSR = getFloatingRank(LHS);
4070 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004071
Chris Lattnerb90739d2008-04-06 23:38:49 +00004072 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004073 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004074 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004075 return 1;
4076 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004077}
4078
Chris Lattner76a00cf2008-04-06 22:59:24 +00004079/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4080/// routine will assert if passed a built-in type that isn't an integer or enum,
4081/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004082unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004083 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004084
Chris Lattner76a00cf2008-04-06 22:59:24 +00004085 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004086 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004087 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004088 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004089 case BuiltinType::Char_S:
4090 case BuiltinType::Char_U:
4091 case BuiltinType::SChar:
4092 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004093 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004094 case BuiltinType::Short:
4095 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004096 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004097 case BuiltinType::Int:
4098 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004099 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004100 case BuiltinType::Long:
4101 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004102 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004103 case BuiltinType::LongLong:
4104 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004105 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004106 case BuiltinType::Int128:
4107 case BuiltinType::UInt128:
4108 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004109 }
4110}
4111
Eli Friedman629ffb92009-08-20 04:21:42 +00004112/// \brief Whether this is a promotable bitfield reference according
4113/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4114///
4115/// \returns the type this bit-field will promote to, or NULL if no
4116/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004117QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004118 if (E->isTypeDependent() || E->isValueDependent())
4119 return QualType();
4120
Eli Friedman629ffb92009-08-20 04:21:42 +00004121 FieldDecl *Field = E->getBitField();
4122 if (!Field)
4123 return QualType();
4124
4125 QualType FT = Field->getType();
4126
Richard Smithcaf33902011-10-10 18:28:20 +00004127 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004128 uint64_t IntSize = getTypeSize(IntTy);
4129 // GCC extension compatibility: if the bit-field size is less than or equal
4130 // to the size of int, it gets promoted no matter what its type is.
4131 // For instance, unsigned long bf : 4 gets promoted to signed int.
4132 if (BitWidth < IntSize)
4133 return IntTy;
4134
4135 if (BitWidth == IntSize)
4136 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4137
4138 // Types bigger than int are not subject to promotions, and therefore act
4139 // like the base type.
4140 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4141 // is ridiculous.
4142 return QualType();
4143}
4144
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004145/// getPromotedIntegerType - Returns the type that Promotable will
4146/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4147/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004148QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004149 assert(!Promotable.isNull());
4150 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004151 if (const EnumType *ET = Promotable->getAs<EnumType>())
4152 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004153
4154 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4155 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4156 // (3.9.1) can be converted to a prvalue of the first of the following
4157 // types that can represent all the values of its underlying type:
4158 // int, unsigned int, long int, unsigned long int, long long int, or
4159 // unsigned long long int [...]
4160 // FIXME: Is there some better way to compute this?
4161 if (BT->getKind() == BuiltinType::WChar_S ||
4162 BT->getKind() == BuiltinType::WChar_U ||
4163 BT->getKind() == BuiltinType::Char16 ||
4164 BT->getKind() == BuiltinType::Char32) {
4165 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4166 uint64_t FromSize = getTypeSize(BT);
4167 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4168 LongLongTy, UnsignedLongLongTy };
4169 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4170 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4171 if (FromSize < ToSize ||
4172 (FromSize == ToSize &&
4173 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4174 return PromoteTypes[Idx];
4175 }
4176 llvm_unreachable("char type should fit into long long");
4177 }
4178 }
4179
4180 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004181 if (Promotable->isSignedIntegerType())
4182 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004183 uint64_t PromotableSize = getIntWidth(Promotable);
4184 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004185 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4186 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4187}
4188
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004189/// \brief Recurses in pointer/array types until it finds an objc retainable
4190/// type and returns its ownership.
4191Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4192 while (!T.isNull()) {
4193 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4194 return T.getObjCLifetime();
4195 if (T->isArrayType())
4196 T = getBaseElementType(T);
4197 else if (const PointerType *PT = T->getAs<PointerType>())
4198 T = PT->getPointeeType();
4199 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004200 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004201 else
4202 break;
4203 }
4204
4205 return Qualifiers::OCL_None;
4206}
4207
Mike Stump11289f42009-09-09 15:08:12 +00004208/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004209/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004210/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004211int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004212 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4213 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004214 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004215
Chris Lattner76a00cf2008-04-06 22:59:24 +00004216 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4217 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004218
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004219 unsigned LHSRank = getIntegerRank(LHSC);
4220 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004221
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004222 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4223 if (LHSRank == RHSRank) return 0;
4224 return LHSRank > RHSRank ? 1 : -1;
4225 }
Mike Stump11289f42009-09-09 15:08:12 +00004226
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004227 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4228 if (LHSUnsigned) {
4229 // If the unsigned [LHS] type is larger, return it.
4230 if (LHSRank >= RHSRank)
4231 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004232
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004233 // If the signed type can represent all values of the unsigned type, it
4234 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004235 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004236 return -1;
4237 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004238
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004239 // If the unsigned [RHS] type is larger, return it.
4240 if (RHSRank >= LHSRank)
4241 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004242
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004243 // If the signed type can represent all values of the unsigned type, it
4244 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004245 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004246 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004247}
Anders Carlsson98f07902007-08-17 05:31:46 +00004248
Anders Carlsson6d417272009-11-14 21:45:58 +00004249static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004250CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4251 DeclContext *DC, IdentifierInfo *Id) {
4252 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004253 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004254 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004255 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004256 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004257}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004258
Mike Stump11289f42009-09-09 15:08:12 +00004259// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004260QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004261 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00004262 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004263 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004264 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00004265 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004266
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004267 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004268
Anders Carlsson98f07902007-08-17 05:31:46 +00004269 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004270 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004271 // int flags;
4272 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004273 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004274 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004275 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004276 FieldTypes[3] = LongTy;
4277
Anders Carlsson98f07902007-08-17 05:31:46 +00004278 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004279 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004280 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004281 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004282 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00004283 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00004284 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004285 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004286 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004287 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004288 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004289 }
4290
Douglas Gregord5058122010-02-11 01:19:42 +00004291 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004292 }
Mike Stump11289f42009-09-09 15:08:12 +00004293
Anders Carlsson98f07902007-08-17 05:31:46 +00004294 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004295}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004296
Douglas Gregor512b0772009-04-23 22:29:11 +00004297void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004298 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004299 assert(Rec && "Invalid CFConstantStringType");
4300 CFConstantStringTypeDecl = Rec->getDecl();
4301}
4302
Jay Foad39c79802011-01-12 09:06:06 +00004303QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004304 if (BlockDescriptorType)
4305 return getTagDeclType(BlockDescriptorType);
4306
4307 RecordDecl *T;
4308 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004309 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004310 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00004311 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004312
4313 QualType FieldTypes[] = {
4314 UnsignedLongTy,
4315 UnsignedLongTy,
4316 };
4317
4318 const char *FieldNames[] = {
4319 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004320 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004321 };
4322
4323 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004324 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00004325 SourceLocation(),
4326 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004327 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00004328 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004329 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004330 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004331 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00004332 T->addDecl(Field);
4333 }
4334
Douglas Gregord5058122010-02-11 01:19:42 +00004335 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004336
4337 BlockDescriptorType = T;
4338
4339 return getTagDeclType(BlockDescriptorType);
4340}
4341
Jay Foad39c79802011-01-12 09:06:06 +00004342QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004343 if (BlockDescriptorExtendedType)
4344 return getTagDeclType(BlockDescriptorExtendedType);
4345
4346 RecordDecl *T;
4347 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004348 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004349 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00004350 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004351
4352 QualType FieldTypes[] = {
4353 UnsignedLongTy,
4354 UnsignedLongTy,
4355 getPointerType(VoidPtrTy),
4356 getPointerType(VoidPtrTy)
4357 };
4358
4359 const char *FieldNames[] = {
4360 "reserved",
4361 "Size",
4362 "CopyFuncPtr",
4363 "DestroyFuncPtr"
4364 };
4365
4366 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004367 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004368 SourceLocation(),
4369 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004370 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004371 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004372 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004373 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004374 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004375 T->addDecl(Field);
4376 }
4377
Douglas Gregord5058122010-02-11 01:19:42 +00004378 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004379
4380 BlockDescriptorExtendedType = T;
4381
4382 return getTagDeclType(BlockDescriptorExtendedType);
4383}
4384
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004385/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4386/// requires copy/dispose. Note that this must match the logic
4387/// in buildByrefHelpers.
4388bool ASTContext::BlockRequiresCopying(QualType Ty,
4389 const VarDecl *D) {
4390 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4391 const Expr *copyExpr = getBlockVarCopyInits(D);
4392 if (!copyExpr && record->hasTrivialDestructor()) return false;
4393
Mike Stump94967902009-10-21 18:16:27 +00004394 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004395 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004396
4397 if (!Ty->isObjCRetainableType()) return false;
4398
4399 Qualifiers qs = Ty.getQualifiers();
4400
4401 // If we have lifetime, that dominates.
4402 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4403 assert(getLangOpts().ObjCAutoRefCount);
4404
4405 switch (lifetime) {
4406 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4407
4408 // These are just bits as far as the runtime is concerned.
4409 case Qualifiers::OCL_ExplicitNone:
4410 case Qualifiers::OCL_Autoreleasing:
4411 return false;
4412
4413 // Tell the runtime that this is ARC __weak, called by the
4414 // byref routines.
4415 case Qualifiers::OCL_Weak:
4416 // ARC __strong __block variables need to be retained.
4417 case Qualifiers::OCL_Strong:
4418 return true;
4419 }
4420 llvm_unreachable("fell out of lifetime switch!");
4421 }
4422 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4423 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004424}
4425
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004426bool ASTContext::getByrefLifetime(QualType Ty,
4427 Qualifiers::ObjCLifetime &LifeTime,
4428 bool &HasByrefExtendedLayout) const {
4429
4430 if (!getLangOpts().ObjC1 ||
4431 getLangOpts().getGC() != LangOptions::NonGC)
4432 return false;
4433
4434 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004435 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004436 HasByrefExtendedLayout = true;
4437 LifeTime = Qualifiers::OCL_None;
4438 }
4439 else if (getLangOpts().ObjCAutoRefCount)
4440 LifeTime = Ty.getObjCLifetime();
4441 // MRR.
4442 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4443 LifeTime = Qualifiers::OCL_ExplicitNone;
4444 else
4445 LifeTime = Qualifiers::OCL_None;
4446 return true;
4447}
4448
Douglas Gregorbab8a962011-09-08 01:46:34 +00004449TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4450 if (!ObjCInstanceTypeDecl)
4451 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4452 getTranslationUnitDecl(),
4453 SourceLocation(),
4454 SourceLocation(),
4455 &Idents.get("instancetype"),
4456 getTrivialTypeSourceInfo(getObjCIdType()));
4457 return ObjCInstanceTypeDecl;
4458}
4459
Anders Carlsson18acd442007-10-29 06:33:42 +00004460// This returns true if a type has been typedefed to BOOL:
4461// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004462static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004463 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004464 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4465 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004466
Anders Carlssond8499822007-10-29 05:01:08 +00004467 return false;
4468}
4469
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004470/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004471/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004472CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004473 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4474 return CharUnits::Zero();
4475
Ken Dyck40775002010-01-11 17:06:35 +00004476 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004477
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004478 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004479 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004480 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004481 // Treat arrays as pointers, since that's how they're passed in.
4482 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004483 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004484 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004485}
4486
4487static inline
4488std::string charUnitsToString(const CharUnits &CU) {
4489 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004490}
4491
John McCall351762c2011-02-07 10:33:21 +00004492/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004493/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004494std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4495 std::string S;
4496
David Chisnall950a9512009-11-17 19:33:30 +00004497 const BlockDecl *Decl = Expr->getBlockDecl();
4498 QualType BlockTy =
4499 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4500 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004501 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004502 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4503 BlockTy->getAs<FunctionType>()->getResultType(),
4504 S, true /*Extended*/);
4505 else
4506 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4507 S);
David Chisnall950a9512009-11-17 19:33:30 +00004508 // Compute size of all parameters.
4509 // Start with computing size of a pointer in number of bytes.
4510 // FIXME: There might(should) be a better way of doing this computation!
4511 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004512 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4513 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004514 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004515 E = Decl->param_end(); PI != E; ++PI) {
4516 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004517 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004518 if (sz.isZero())
4519 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004520 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004521 ParmOffset += sz;
4522 }
4523 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004524 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004525 // Block pointer and offset.
4526 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004527
4528 // Argument types.
4529 ParmOffset = PtrSize;
4530 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4531 Decl->param_end(); PI != E; ++PI) {
4532 ParmVarDecl *PVDecl = *PI;
4533 QualType PType = PVDecl->getOriginalType();
4534 if (const ArrayType *AT =
4535 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4536 // Use array's original type only if it has known number of
4537 // elements.
4538 if (!isa<ConstantArrayType>(AT))
4539 PType = PVDecl->getType();
4540 } else if (PType->isFunctionType())
4541 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004542 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004543 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4544 S, true /*Extended*/);
4545 else
4546 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004547 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004548 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004549 }
John McCall351762c2011-02-07 10:33:21 +00004550
4551 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004552}
4553
Douglas Gregora9d84932011-05-27 01:19:52 +00004554bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004555 std::string& S) {
4556 // Encode result type.
4557 getObjCEncodingForType(Decl->getResultType(), S);
4558 CharUnits ParmOffset;
4559 // Compute size of all parameters.
4560 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4561 E = Decl->param_end(); PI != E; ++PI) {
4562 QualType PType = (*PI)->getType();
4563 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004564 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004565 continue;
4566
David Chisnall50e4eba2010-12-30 14:05:53 +00004567 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004568 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004569 ParmOffset += sz;
4570 }
4571 S += charUnitsToString(ParmOffset);
4572 ParmOffset = CharUnits::Zero();
4573
4574 // Argument types.
4575 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4576 E = 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();
4587 getObjCEncodingForType(PType, S);
4588 S += charUnitsToString(ParmOffset);
4589 ParmOffset += getObjCEncodingTypeSize(PType);
4590 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004591
4592 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004593}
4594
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004595/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4596/// method parameter or return type. If Extended, include class names and
4597/// block object types.
4598void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4599 QualType T, std::string& S,
4600 bool Extended) const {
4601 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4602 getObjCEncodingForTypeQualifier(QT, S);
4603 // Encode parameter type.
4604 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4605 true /*OutermostType*/,
4606 false /*EncodingProperty*/,
4607 false /*StructField*/,
4608 Extended /*EncodeBlockParameters*/,
4609 Extended /*EncodeClassNames*/);
4610}
4611
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004612/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004613/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004614bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004615 std::string& S,
4616 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004617 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004618 // Encode return type.
4619 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4620 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004621 // Compute size of all parameters.
4622 // Start with computing size of a pointer in number of bytes.
4623 // FIXME: There might(should) be a better way of doing this computation!
4624 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004625 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004626 // The first two arguments (self and _cmd) are pointers; account for
4627 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004628 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004629 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004630 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004631 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004632 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004633 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004634 continue;
4635
Ken Dyck40775002010-01-11 17:06:35 +00004636 assert (sz.isPositive() &&
4637 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004638 ParmOffset += sz;
4639 }
Ken Dyck40775002010-01-11 17:06:35 +00004640 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004641 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004642 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004643
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004644 // Argument types.
4645 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004646 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004647 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004648 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004649 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004650 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004651 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4652 // Use array's original type only if it has known number of
4653 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004654 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004655 PType = PVDecl->getType();
4656 } else if (PType->isFunctionType())
4657 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004658 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4659 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004660 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004661 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004662 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004663
4664 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004665}
4666
Daniel Dunbar4932b362008-08-28 04:38:10 +00004667/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004668/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004669/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4670/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004671/// Property attributes are stored as a comma-delimited C string. The simple
4672/// attributes readonly and bycopy are encoded as single characters. The
4673/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4674/// encoded as single characters, followed by an identifier. Property types
4675/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004676/// these attributes are defined by the following enumeration:
4677/// @code
4678/// enum PropertyAttributes {
4679/// kPropertyReadOnly = 'R', // property is read-only.
4680/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4681/// kPropertyByref = '&', // property is a reference to the value last assigned
4682/// kPropertyDynamic = 'D', // property is dynamic
4683/// kPropertyGetter = 'G', // followed by getter selector name
4684/// kPropertySetter = 'S', // followed by setter selector name
4685/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004686/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004687/// kPropertyWeak = 'W' // 'weak' property
4688/// kPropertyStrong = 'P' // property GC'able
4689/// kPropertyNonAtomic = 'N' // property non-atomic
4690/// };
4691/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004692void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004693 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004694 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004695 // Collect information from the property implementation decl(s).
4696 bool Dynamic = false;
4697 ObjCPropertyImplDecl *SynthesizePID = 0;
4698
4699 // FIXME: Duplicated code due to poor abstraction.
4700 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004701 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004702 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4703 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004704 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004705 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004706 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004707 if (PID->getPropertyDecl() == PD) {
4708 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4709 Dynamic = true;
4710 } else {
4711 SynthesizePID = PID;
4712 }
4713 }
4714 }
4715 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004716 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004717 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004718 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004719 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004720 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004721 if (PID->getPropertyDecl() == PD) {
4722 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4723 Dynamic = true;
4724 } else {
4725 SynthesizePID = PID;
4726 }
4727 }
Mike Stump11289f42009-09-09 15:08:12 +00004728 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004729 }
4730 }
4731
4732 // FIXME: This is not very efficient.
4733 S = "T";
4734
4735 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004736 // GCC has some special rules regarding encoding of properties which
4737 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004738 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004739 true /* outermost type */,
4740 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004741
4742 if (PD->isReadOnly()) {
4743 S += ",R";
4744 } else {
4745 switch (PD->getSetterKind()) {
4746 case ObjCPropertyDecl::Assign: break;
4747 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004748 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004749 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004750 }
4751 }
4752
4753 // It really isn't clear at all what this means, since properties
4754 // are "dynamic by default".
4755 if (Dynamic)
4756 S += ",D";
4757
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004758 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4759 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004760
Daniel Dunbar4932b362008-08-28 04:38:10 +00004761 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4762 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004763 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004764 }
4765
4766 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4767 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004768 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004769 }
4770
4771 if (SynthesizePID) {
4772 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4773 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004774 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004775 }
4776
4777 // FIXME: OBJCGC: weak & strong
4778}
4779
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004780/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004781/// Another legacy compatibility encoding: 32-bit longs are encoded as
4782/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004783/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4784///
4785void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004786 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004787 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004788 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004789 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004790 else
Jay Foad39c79802011-01-12 09:06:06 +00004791 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004792 PointeeTy = IntTy;
4793 }
4794 }
4795}
4796
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004797void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004798 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004799 // We follow the behavior of gcc, expanding structures which are
4800 // directly pointed to, and expanding embedded structures. Note that
4801 // these rules are sufficient to prevent recursive encoding of the
4802 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004803 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004804 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004805}
4806
David Chisnallb190a2c2010-06-04 01:10:52 +00004807static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4808 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004809 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnallb190a2c2010-06-04 01:10:52 +00004810 case BuiltinType::Void: return 'v';
4811 case BuiltinType::Bool: return 'B';
4812 case BuiltinType::Char_U:
4813 case BuiltinType::UChar: return 'C';
4814 case BuiltinType::UShort: return 'S';
4815 case BuiltinType::UInt: return 'I';
4816 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004817 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004818 case BuiltinType::UInt128: return 'T';
4819 case BuiltinType::ULongLong: return 'Q';
4820 case BuiltinType::Char_S:
4821 case BuiltinType::SChar: return 'c';
4822 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004823 case BuiltinType::WChar_S:
4824 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004825 case BuiltinType::Int: return 'i';
4826 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004827 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004828 case BuiltinType::LongLong: return 'q';
4829 case BuiltinType::Int128: return 't';
4830 case BuiltinType::Float: return 'f';
4831 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004832 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004833 }
4834}
4835
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004836static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4837 EnumDecl *Enum = ET->getDecl();
4838
4839 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4840 if (!Enum->isFixed())
4841 return 'i';
4842
4843 // The encoding of a fixed enum type matches its fixed underlying type.
4844 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4845}
4846
Jay Foad39c79802011-01-12 09:06:06 +00004847static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004848 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00004849 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004850 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004851 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4852 // The GNU runtime requires more information; bitfields are encoded as b,
4853 // then the offset (in bits) of the first element, then the type of the
4854 // bitfield, then the size in bits. For example, in this structure:
4855 //
4856 // struct
4857 // {
4858 // int integer;
4859 // int flags:2;
4860 // };
4861 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4862 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4863 // information is not especially sensible, but we're stuck with it for
4864 // compatibility with GCC, although providing it breaks anything that
4865 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00004866 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004867 const RecordDecl *RD = FD->getParent();
4868 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004869 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004870 if (const EnumType *ET = T->getAs<EnumType>())
4871 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnall6f0a7d22010-12-26 20:12:30 +00004872 else
Jay Foad39c79802011-01-12 09:06:06 +00004873 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004874 }
Richard Smithcaf33902011-10-10 18:28:20 +00004875 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004876}
4877
Daniel Dunbar07d07852009-10-18 21:17:35 +00004878// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004879void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4880 bool ExpandPointedToStructures,
4881 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004882 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004883 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004884 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004885 bool StructField,
4886 bool EncodeBlockParameters,
4887 bool EncodeClassNames) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004888 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004889 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004890 return EncodeBitField(this, S, T, FD);
4891 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004892 return;
4893 }
Mike Stump11289f42009-09-09 15:08:12 +00004894
John McCall9dd450b2009-09-21 23:43:11 +00004895 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004896 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004897 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004898 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004899 return;
4900 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004901
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004902 // encoding for pointer or r3eference types.
4903 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004904 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004905 if (PT->isObjCSelType()) {
4906 S += ':';
4907 return;
4908 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004909 PointeeTy = PT->getPointeeType();
4910 }
4911 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4912 PointeeTy = RT->getPointeeType();
4913 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004914 bool isReadOnly = false;
4915 // For historical/compatibility reasons, the read-only qualifier of the
4916 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4917 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004918 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004919 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004920 if (OutermostType && T.isConstQualified()) {
4921 isReadOnly = true;
4922 S += 'r';
4923 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004924 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004925 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004926 while (P->getAs<PointerType>())
4927 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004928 if (P.isConstQualified()) {
4929 isReadOnly = true;
4930 S += 'r';
4931 }
4932 }
4933 if (isReadOnly) {
4934 // Another legacy compatibility encoding. Some ObjC qualifier and type
4935 // combinations need to be rearranged.
4936 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004937 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004938 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004939 }
Mike Stump11289f42009-09-09 15:08:12 +00004940
Anders Carlssond8499822007-10-29 05:01:08 +00004941 if (PointeeTy->isCharType()) {
4942 // char pointer types should be encoded as '*' unless it is a
4943 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004944 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004945 S += '*';
4946 return;
4947 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004948 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004949 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4950 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4951 S += '#';
4952 return;
4953 }
4954 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4955 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4956 S += '@';
4957 return;
4958 }
4959 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004960 }
Anders Carlssond8499822007-10-29 05:01:08 +00004961 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004962 getLegacyIntegralTypeEncoding(PointeeTy);
4963
Mike Stump11289f42009-09-09 15:08:12 +00004964 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004965 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004966 return;
4967 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004968
Chris Lattnere7cabb92009-07-13 00:10:46 +00004969 if (const ArrayType *AT =
4970 // Ignore type qualifiers etc.
4971 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004972 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004973 // Incomplete arrays are encoded as a pointer to the array element.
4974 S += '^';
4975
Mike Stump11289f42009-09-09 15:08:12 +00004976 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004977 false, ExpandStructures, FD);
4978 } else {
4979 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004980
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004981 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4982 if (getTypeSize(CAT->getElementType()) == 0)
4983 S += '0';
4984 else
4985 S += llvm::utostr(CAT->getSize().getZExtValue());
4986 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004987 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004988 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4989 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00004990 S += '0';
4991 }
Mike Stump11289f42009-09-09 15:08:12 +00004992
4993 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004994 false, ExpandStructures, FD);
4995 S += ']';
4996 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004997 return;
4998 }
Mike Stump11289f42009-09-09 15:08:12 +00004999
John McCall9dd450b2009-09-21 23:43:11 +00005000 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00005001 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005002 return;
5003 }
Mike Stump11289f42009-09-09 15:08:12 +00005004
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005005 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005006 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005007 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005008 // Anonymous structures print as '?'
5009 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5010 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005011 if (ClassTemplateSpecializationDecl *Spec
5012 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5013 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
5014 std::string TemplateArgsStr
5015 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005016 TemplateArgs.data(),
5017 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005018 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005019
5020 S += TemplateArgsStr;
5021 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005022 } else {
5023 S += '?';
5024 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005025 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005026 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005027 if (!RDecl->isUnion()) {
5028 getObjCEncodingForStructureImpl(RDecl, S, FD);
5029 } else {
5030 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5031 FieldEnd = RDecl->field_end();
5032 Field != FieldEnd; ++Field) {
5033 if (FD) {
5034 S += '"';
5035 S += Field->getNameAsString();
5036 S += '"';
5037 }
Mike Stump11289f42009-09-09 15:08:12 +00005038
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005039 // Special case bit-fields.
5040 if (Field->isBitField()) {
5041 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00005042 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005043 } else {
5044 QualType qt = Field->getType();
5045 getLegacyIntegralTypeEncoding(qt);
5046 getObjCEncodingForTypeImpl(qt, S, false, true,
5047 FD, /*OutermostType*/false,
5048 /*EncodingProperty*/false,
5049 /*StructField*/true);
5050 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005051 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005052 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005053 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005054 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005055 return;
5056 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005057
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005058 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005059 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005060 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005061 else
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005062 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005063 return;
5064 }
Mike Stump11289f42009-09-09 15:08:12 +00005065
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005066 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00005067 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005068 if (EncodeBlockParameters) {
5069 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
5070
5071 S += '<';
5072 // Block return type
5073 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5074 ExpandPointedToStructures, ExpandStructures,
5075 FD,
5076 false /* OutermostType */,
5077 EncodingProperty,
5078 false /* StructField */,
5079 EncodeBlockParameters,
5080 EncodeClassNames);
5081 // Block self
5082 S += "@?";
5083 // Block parameters
5084 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5085 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5086 E = FPT->arg_type_end(); I && (I != E); ++I) {
5087 getObjCEncodingForTypeImpl(*I, S,
5088 ExpandPointedToStructures,
5089 ExpandStructures,
5090 FD,
5091 false /* OutermostType */,
5092 EncodingProperty,
5093 false /* StructField */,
5094 EncodeBlockParameters,
5095 EncodeClassNames);
5096 }
5097 }
5098 S += '>';
5099 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005100 return;
5101 }
Mike Stump11289f42009-09-09 15:08:12 +00005102
John McCall8b07ec22010-05-15 11:32:37 +00005103 // Ignore protocol qualifiers when mangling at this level.
5104 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
5105 T = OT->getBaseType();
5106
John McCall8ccfcb52009-09-24 19:53:00 +00005107 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005108 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005109 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005110 S += '{';
5111 const IdentifierInfo *II = OI->getIdentifier();
5112 S += II->getName();
5113 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005114 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005115 DeepCollectObjCIvars(OI, true, Ivars);
5116 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005117 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005118 if (Field->isBitField())
5119 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005120 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005121 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005122 }
5123 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005124 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005125 }
Mike Stump11289f42009-09-09 15:08:12 +00005126
John McCall9dd450b2009-09-21 23:43:11 +00005127 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005128 if (OPT->isObjCIdType()) {
5129 S += '@';
5130 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005131 }
Mike Stump11289f42009-09-09 15:08:12 +00005132
Steve Narofff0c86112009-10-28 22:03:49 +00005133 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5134 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5135 // Since this is a binary compatibility issue, need to consult with runtime
5136 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005137 S += '#';
5138 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005139 }
Mike Stump11289f42009-09-09 15:08:12 +00005140
Chris Lattnere7cabb92009-07-13 00:10:46 +00005141 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005142 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005143 ExpandPointedToStructures,
5144 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005145 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005146 // Note that we do extended encoding of protocol qualifer list
5147 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005148 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00005149 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5150 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005151 S += '<';
5152 S += (*I)->getNameAsString();
5153 S += '>';
5154 }
5155 S += '"';
5156 }
5157 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005158 }
Mike Stump11289f42009-09-09 15:08:12 +00005159
Chris Lattnere7cabb92009-07-13 00:10:46 +00005160 QualType PointeeTy = OPT->getPointeeType();
5161 if (!EncodingProperty &&
5162 isa<TypedefType>(PointeeTy.getTypePtr())) {
5163 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005164 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005165 // {...};
5166 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00005167 getObjCEncodingForTypeImpl(PointeeTy, S,
5168 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00005169 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005170 return;
5171 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005172
5173 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005174 if (OPT->getInterfaceDecl() &&
5175 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005176 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005177 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00005178 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5179 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005180 S += '<';
5181 S += (*I)->getNameAsString();
5182 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005183 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005184 S += '"';
5185 }
5186 return;
5187 }
Mike Stump11289f42009-09-09 15:08:12 +00005188
John McCalla9e6e8d2010-05-17 23:56:34 +00005189 // gcc just blithely ignores member pointers.
5190 // TODO: maybe there should be a mangling for these
5191 if (T->getAs<MemberPointerType>())
5192 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005193
5194 if (T->isVectorType()) {
5195 // This matches gcc's encoding, even though technically it is
5196 // insufficient.
5197 // FIXME. We should do a better job than gcc.
5198 return;
5199 }
5200
David Blaikie83d382b2011-09-23 05:06:16 +00005201 llvm_unreachable("@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00005202}
5203
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005204void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5205 std::string &S,
5206 const FieldDecl *FD,
5207 bool includeVBases) const {
5208 assert(RDecl && "Expected non-null RecordDecl");
5209 assert(!RDecl->isUnion() && "Should not be called for unions");
5210 if (!RDecl->getDefinition())
5211 return;
5212
5213 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5214 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5215 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5216
5217 if (CXXRec) {
5218 for (CXXRecordDecl::base_class_iterator
5219 BI = CXXRec->bases_begin(),
5220 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5221 if (!BI->isVirtual()) {
5222 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005223 if (base->isEmpty())
5224 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005225 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005226 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5227 std::make_pair(offs, base));
5228 }
5229 }
5230 }
5231
5232 unsigned i = 0;
5233 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5234 FieldEnd = RDecl->field_end();
5235 Field != FieldEnd; ++Field, ++i) {
5236 uint64_t offs = layout.getFieldOffset(i);
5237 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00005238 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005239 }
5240
5241 if (CXXRec && includeVBases) {
5242 for (CXXRecordDecl::base_class_iterator
5243 BI = CXXRec->vbases_begin(),
5244 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5245 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005246 if (base->isEmpty())
5247 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005248 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005249 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5250 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5251 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005252 }
5253 }
5254
5255 CharUnits size;
5256 if (CXXRec) {
5257 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5258 } else {
5259 size = layout.getSize();
5260 }
5261
5262 uint64_t CurOffs = 0;
5263 std::multimap<uint64_t, NamedDecl *>::iterator
5264 CurLayObj = FieldOrBaseOffsets.begin();
5265
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005266 if (CXXRec && CXXRec->isDynamicClass() &&
5267 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005268 if (FD) {
5269 S += "\"_vptr$";
5270 std::string recname = CXXRec->getNameAsString();
5271 if (recname.empty()) recname = "?";
5272 S += recname;
5273 S += '"';
5274 }
5275 S += "^^?";
5276 CurOffs += getTypeSize(VoidPtrTy);
5277 }
5278
5279 if (!RDecl->hasFlexibleArrayMember()) {
5280 // Mark the end of the structure.
5281 uint64_t offs = toBits(size);
5282 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5283 std::make_pair(offs, (NamedDecl*)0));
5284 }
5285
5286 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5287 assert(CurOffs <= CurLayObj->first);
5288
5289 if (CurOffs < CurLayObj->first) {
5290 uint64_t padding = CurLayObj->first - CurOffs;
5291 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5292 // packing/alignment of members is different that normal, in which case
5293 // the encoding will be out-of-sync with the real layout.
5294 // If the runtime switches to just consider the size of types without
5295 // taking into account alignment, we could make padding explicit in the
5296 // encoding (e.g. using arrays of chars). The encoding strings would be
5297 // longer then though.
5298 CurOffs += padding;
5299 }
5300
5301 NamedDecl *dcl = CurLayObj->second;
5302 if (dcl == 0)
5303 break; // reached end of structure.
5304
5305 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5306 // We expand the bases without their virtual bases since those are going
5307 // in the initial structure. Note that this differs from gcc which
5308 // expands virtual bases each time one is encountered in the hierarchy,
5309 // making the encoding type bigger than it really is.
5310 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005311 assert(!base->isEmpty());
5312 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005313 } else {
5314 FieldDecl *field = cast<FieldDecl>(dcl);
5315 if (FD) {
5316 S += '"';
5317 S += field->getNameAsString();
5318 S += '"';
5319 }
5320
5321 if (field->isBitField()) {
5322 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00005323 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005324 } else {
5325 QualType qt = field->getType();
5326 getLegacyIntegralTypeEncoding(qt);
5327 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5328 /*OutermostType*/false,
5329 /*EncodingProperty*/false,
5330 /*StructField*/true);
5331 CurOffs += getTypeSize(field->getType());
5332 }
5333 }
5334 }
5335}
5336
Mike Stump11289f42009-09-09 15:08:12 +00005337void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005338 std::string& S) const {
5339 if (QT & Decl::OBJC_TQ_In)
5340 S += 'n';
5341 if (QT & Decl::OBJC_TQ_Inout)
5342 S += 'N';
5343 if (QT & Decl::OBJC_TQ_Out)
5344 S += 'o';
5345 if (QT & Decl::OBJC_TQ_Bycopy)
5346 S += 'O';
5347 if (QT & Decl::OBJC_TQ_Byref)
5348 S += 'R';
5349 if (QT & Decl::OBJC_TQ_Oneway)
5350 S += 'V';
5351}
5352
Douglas Gregor3ea72692011-08-12 05:46:01 +00005353TypedefDecl *ASTContext::getObjCIdDecl() const {
5354 if (!ObjCIdDecl) {
5355 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5356 T = getObjCObjectPointerType(T);
5357 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5358 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5359 getTranslationUnitDecl(),
5360 SourceLocation(), SourceLocation(),
5361 &Idents.get("id"), IdInfo);
5362 }
5363
5364 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005365}
5366
Douglas Gregor52e02802011-08-12 06:17:30 +00005367TypedefDecl *ASTContext::getObjCSelDecl() const {
5368 if (!ObjCSelDecl) {
5369 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5370 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5371 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5372 getTranslationUnitDecl(),
5373 SourceLocation(), SourceLocation(),
5374 &Idents.get("SEL"), SelInfo);
5375 }
5376 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005377}
5378
Douglas Gregor0a586182011-08-12 05:59:41 +00005379TypedefDecl *ASTContext::getObjCClassDecl() const {
5380 if (!ObjCClassDecl) {
5381 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5382 T = getObjCObjectPointerType(T);
5383 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5384 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5385 getTranslationUnitDecl(),
5386 SourceLocation(), SourceLocation(),
5387 &Idents.get("Class"), ClassInfo);
5388 }
5389
5390 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005391}
5392
Douglas Gregord53ae832012-01-17 18:09:05 +00005393ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5394 if (!ObjCProtocolClassDecl) {
5395 ObjCProtocolClassDecl
5396 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5397 SourceLocation(),
5398 &Idents.get("Protocol"),
5399 /*PrevDecl=*/0,
5400 SourceLocation(), true);
5401 }
5402
5403 return ObjCProtocolClassDecl;
5404}
5405
Meador Inge5d3fb222012-06-16 03:34:49 +00005406//===----------------------------------------------------------------------===//
5407// __builtin_va_list Construction Functions
5408//===----------------------------------------------------------------------===//
5409
5410static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5411 // typedef char* __builtin_va_list;
5412 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5413 TypeSourceInfo *TInfo
5414 = Context->getTrivialTypeSourceInfo(CharPtrType);
5415
5416 TypedefDecl *VaListTypeDecl
5417 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5418 Context->getTranslationUnitDecl(),
5419 SourceLocation(), SourceLocation(),
5420 &Context->Idents.get("__builtin_va_list"),
5421 TInfo);
5422 return VaListTypeDecl;
5423}
5424
5425static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5426 // typedef void* __builtin_va_list;
5427 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5428 TypeSourceInfo *TInfo
5429 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5430
5431 TypedefDecl *VaListTypeDecl
5432 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5433 Context->getTranslationUnitDecl(),
5434 SourceLocation(), SourceLocation(),
5435 &Context->Idents.get("__builtin_va_list"),
5436 TInfo);
5437 return VaListTypeDecl;
5438}
5439
5440static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5441 // typedef struct __va_list_tag {
5442 RecordDecl *VaListTagDecl;
5443
5444 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5445 Context->getTranslationUnitDecl(),
5446 &Context->Idents.get("__va_list_tag"));
5447 VaListTagDecl->startDefinition();
5448
5449 const size_t NumFields = 5;
5450 QualType FieldTypes[NumFields];
5451 const char *FieldNames[NumFields];
5452
5453 // unsigned char gpr;
5454 FieldTypes[0] = Context->UnsignedCharTy;
5455 FieldNames[0] = "gpr";
5456
5457 // unsigned char fpr;
5458 FieldTypes[1] = Context->UnsignedCharTy;
5459 FieldNames[1] = "fpr";
5460
5461 // unsigned short reserved;
5462 FieldTypes[2] = Context->UnsignedShortTy;
5463 FieldNames[2] = "reserved";
5464
5465 // void* overflow_arg_area;
5466 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5467 FieldNames[3] = "overflow_arg_area";
5468
5469 // void* reg_save_area;
5470 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5471 FieldNames[4] = "reg_save_area";
5472
5473 // Create fields
5474 for (unsigned i = 0; i < NumFields; ++i) {
5475 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5476 SourceLocation(),
5477 SourceLocation(),
5478 &Context->Idents.get(FieldNames[i]),
5479 FieldTypes[i], /*TInfo=*/0,
5480 /*BitWidth=*/0,
5481 /*Mutable=*/false,
5482 ICIS_NoInit);
5483 Field->setAccess(AS_public);
5484 VaListTagDecl->addDecl(Field);
5485 }
5486 VaListTagDecl->completeDefinition();
5487 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005488 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005489
5490 // } __va_list_tag;
5491 TypedefDecl *VaListTagTypedefDecl
5492 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5493 Context->getTranslationUnitDecl(),
5494 SourceLocation(), SourceLocation(),
5495 &Context->Idents.get("__va_list_tag"),
5496 Context->getTrivialTypeSourceInfo(VaListTagType));
5497 QualType VaListTagTypedefType =
5498 Context->getTypedefType(VaListTagTypedefDecl);
5499
5500 // typedef __va_list_tag __builtin_va_list[1];
5501 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5502 QualType VaListTagArrayType
5503 = Context->getConstantArrayType(VaListTagTypedefType,
5504 Size, ArrayType::Normal, 0);
5505 TypeSourceInfo *TInfo
5506 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5507 TypedefDecl *VaListTypedefDecl
5508 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5509 Context->getTranslationUnitDecl(),
5510 SourceLocation(), SourceLocation(),
5511 &Context->Idents.get("__builtin_va_list"),
5512 TInfo);
5513
5514 return VaListTypedefDecl;
5515}
5516
5517static TypedefDecl *
5518CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5519 // typedef struct __va_list_tag {
5520 RecordDecl *VaListTagDecl;
5521 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5522 Context->getTranslationUnitDecl(),
5523 &Context->Idents.get("__va_list_tag"));
5524 VaListTagDecl->startDefinition();
5525
5526 const size_t NumFields = 4;
5527 QualType FieldTypes[NumFields];
5528 const char *FieldNames[NumFields];
5529
5530 // unsigned gp_offset;
5531 FieldTypes[0] = Context->UnsignedIntTy;
5532 FieldNames[0] = "gp_offset";
5533
5534 // unsigned fp_offset;
5535 FieldTypes[1] = Context->UnsignedIntTy;
5536 FieldNames[1] = "fp_offset";
5537
5538 // void* overflow_arg_area;
5539 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5540 FieldNames[2] = "overflow_arg_area";
5541
5542 // void* reg_save_area;
5543 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5544 FieldNames[3] = "reg_save_area";
5545
5546 // Create fields
5547 for (unsigned i = 0; i < NumFields; ++i) {
5548 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5549 VaListTagDecl,
5550 SourceLocation(),
5551 SourceLocation(),
5552 &Context->Idents.get(FieldNames[i]),
5553 FieldTypes[i], /*TInfo=*/0,
5554 /*BitWidth=*/0,
5555 /*Mutable=*/false,
5556 ICIS_NoInit);
5557 Field->setAccess(AS_public);
5558 VaListTagDecl->addDecl(Field);
5559 }
5560 VaListTagDecl->completeDefinition();
5561 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005562 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005563
5564 // } __va_list_tag;
5565 TypedefDecl *VaListTagTypedefDecl
5566 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5567 Context->getTranslationUnitDecl(),
5568 SourceLocation(), SourceLocation(),
5569 &Context->Idents.get("__va_list_tag"),
5570 Context->getTrivialTypeSourceInfo(VaListTagType));
5571 QualType VaListTagTypedefType =
5572 Context->getTypedefType(VaListTagTypedefDecl);
5573
5574 // typedef __va_list_tag __builtin_va_list[1];
5575 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5576 QualType VaListTagArrayType
5577 = Context->getConstantArrayType(VaListTagTypedefType,
5578 Size, ArrayType::Normal,0);
5579 TypeSourceInfo *TInfo
5580 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5581 TypedefDecl *VaListTypedefDecl
5582 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5583 Context->getTranslationUnitDecl(),
5584 SourceLocation(), SourceLocation(),
5585 &Context->Idents.get("__builtin_va_list"),
5586 TInfo);
5587
5588 return VaListTypedefDecl;
5589}
5590
5591static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5592 // typedef int __builtin_va_list[4];
5593 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5594 QualType IntArrayType
5595 = Context->getConstantArrayType(Context->IntTy,
5596 Size, ArrayType::Normal, 0);
5597 TypedefDecl *VaListTypedefDecl
5598 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5599 Context->getTranslationUnitDecl(),
5600 SourceLocation(), SourceLocation(),
5601 &Context->Idents.get("__builtin_va_list"),
5602 Context->getTrivialTypeSourceInfo(IntArrayType));
5603
5604 return VaListTypedefDecl;
5605}
5606
Logan Chien57086ce2012-10-10 06:56:20 +00005607static TypedefDecl *
5608CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
5609 RecordDecl *VaListDecl;
5610 if (Context->getLangOpts().CPlusPlus) {
5611 // namespace std { struct __va_list {
5612 NamespaceDecl *NS;
5613 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5614 Context->getTranslationUnitDecl(),
5615 /*Inline*/false, SourceLocation(),
5616 SourceLocation(), &Context->Idents.get("std"),
5617 /*PrevDecl*/0);
5618
5619 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5620 Context->getTranslationUnitDecl(),
5621 SourceLocation(), SourceLocation(),
5622 &Context->Idents.get("__va_list"));
5623
5624 VaListDecl->setDeclContext(NS);
5625
5626 } else {
5627 // struct __va_list {
5628 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
5629 Context->getTranslationUnitDecl(),
5630 &Context->Idents.get("__va_list"));
5631 }
5632
5633 VaListDecl->startDefinition();
5634
5635 // void * __ap;
5636 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5637 VaListDecl,
5638 SourceLocation(),
5639 SourceLocation(),
5640 &Context->Idents.get("__ap"),
5641 Context->getPointerType(Context->VoidTy),
5642 /*TInfo=*/0,
5643 /*BitWidth=*/0,
5644 /*Mutable=*/false,
5645 ICIS_NoInit);
5646 Field->setAccess(AS_public);
5647 VaListDecl->addDecl(Field);
5648
5649 // };
5650 VaListDecl->completeDefinition();
5651
5652 // typedef struct __va_list __builtin_va_list;
5653 TypeSourceInfo *TInfo
5654 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
5655
5656 TypedefDecl *VaListTypeDecl
5657 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5658 Context->getTranslationUnitDecl(),
5659 SourceLocation(), SourceLocation(),
5660 &Context->Idents.get("__builtin_va_list"),
5661 TInfo);
5662
5663 return VaListTypeDecl;
5664}
5665
Meador Inge5d3fb222012-06-16 03:34:49 +00005666static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5667 TargetInfo::BuiltinVaListKind Kind) {
5668 switch (Kind) {
5669 case TargetInfo::CharPtrBuiltinVaList:
5670 return CreateCharPtrBuiltinVaListDecl(Context);
5671 case TargetInfo::VoidPtrBuiltinVaList:
5672 return CreateVoidPtrBuiltinVaListDecl(Context);
5673 case TargetInfo::PowerABIBuiltinVaList:
5674 return CreatePowerABIBuiltinVaListDecl(Context);
5675 case TargetInfo::X86_64ABIBuiltinVaList:
5676 return CreateX86_64ABIBuiltinVaListDecl(Context);
5677 case TargetInfo::PNaClABIBuiltinVaList:
5678 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00005679 case TargetInfo::AAPCSABIBuiltinVaList:
5680 return CreateAAPCSABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00005681 }
5682
5683 llvm_unreachable("Unhandled __builtin_va_list type kind");
5684}
5685
5686TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5687 if (!BuiltinVaListDecl)
5688 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5689
5690 return BuiltinVaListDecl;
5691}
5692
Meador Ingecfb60902012-07-01 15:57:25 +00005693QualType ASTContext::getVaListTagType() const {
5694 // Force the creation of VaListTagTy by building the __builtin_va_list
5695 // declaration.
5696 if (VaListTagTy.isNull())
5697 (void) getBuiltinVaListDecl();
5698
5699 return VaListTagTy;
5700}
5701
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005702void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00005703 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00005704 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00005705
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005706 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00005707}
5708
John McCalld28ae272009-12-02 08:04:21 +00005709/// \brief Retrieve the template name that corresponds to a non-empty
5710/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00005711TemplateName
5712ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5713 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00005714 unsigned size = End - Begin;
5715 assert(size > 1 && "set is not overloaded!");
5716
5717 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5718 size * sizeof(FunctionTemplateDecl*));
5719 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5720
5721 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00005722 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00005723 NamedDecl *D = *I;
5724 assert(isa<FunctionTemplateDecl>(D) ||
5725 (isa<UsingShadowDecl>(D) &&
5726 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5727 *Storage++ = D;
5728 }
5729
5730 return TemplateName(OT);
5731}
5732
Douglas Gregordc572a32009-03-30 22:58:21 +00005733/// \brief Retrieve the template name that represents a qualified
5734/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00005735TemplateName
5736ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5737 bool TemplateKeyword,
5738 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00005739 assert(NNS && "Missing nested-name-specifier in qualified template name");
5740
Douglas Gregorc42075a2010-02-04 18:10:26 +00005741 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00005742 llvm::FoldingSetNodeID ID;
5743 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5744
5745 void *InsertPos = 0;
5746 QualifiedTemplateName *QTN =
5747 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5748 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00005749 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
5750 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00005751 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5752 }
5753
5754 return TemplateName(QTN);
5755}
5756
5757/// \brief Retrieve the template name that represents a dependent
5758/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00005759TemplateName
5760ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5761 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00005762 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00005763 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00005764
5765 llvm::FoldingSetNodeID ID;
5766 DependentTemplateName::Profile(ID, NNS, Name);
5767
5768 void *InsertPos = 0;
5769 DependentTemplateName *QTN =
5770 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5771
5772 if (QTN)
5773 return TemplateName(QTN);
5774
5775 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5776 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00005777 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5778 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00005779 } else {
5780 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00005781 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5782 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005783 DependentTemplateName *CheckQTN =
5784 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5785 assert(!CheckQTN && "Dependent type name canonicalization broken");
5786 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00005787 }
5788
5789 DependentTemplateNames.InsertNode(QTN, InsertPos);
5790 return TemplateName(QTN);
5791}
5792
Douglas Gregor71395fa2009-11-04 00:56:37 +00005793/// \brief Retrieve the template name that represents a dependent
5794/// template name such as \c MetaFun::template operator+.
5795TemplateName
5796ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00005797 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00005798 assert((!NNS || NNS->isDependent()) &&
5799 "Nested name specifier must be dependent");
5800
5801 llvm::FoldingSetNodeID ID;
5802 DependentTemplateName::Profile(ID, NNS, Operator);
5803
5804 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00005805 DependentTemplateName *QTN
5806 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005807
5808 if (QTN)
5809 return TemplateName(QTN);
5810
5811 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5812 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00005813 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5814 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005815 } else {
5816 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00005817 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5818 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005819
5820 DependentTemplateName *CheckQTN
5821 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5822 assert(!CheckQTN && "Dependent template name canonicalization broken");
5823 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00005824 }
5825
5826 DependentTemplateNames.InsertNode(QTN, InsertPos);
5827 return TemplateName(QTN);
5828}
5829
Douglas Gregor5590be02011-01-15 06:45:20 +00005830TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00005831ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5832 TemplateName replacement) const {
5833 llvm::FoldingSetNodeID ID;
5834 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5835
5836 void *insertPos = 0;
5837 SubstTemplateTemplateParmStorage *subst
5838 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5839
5840 if (!subst) {
5841 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5842 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5843 }
5844
5845 return TemplateName(subst);
5846}
5847
5848TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00005849ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5850 const TemplateArgument &ArgPack) const {
5851 ASTContext &Self = const_cast<ASTContext &>(*this);
5852 llvm::FoldingSetNodeID ID;
5853 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5854
5855 void *InsertPos = 0;
5856 SubstTemplateTemplateParmPackStorage *Subst
5857 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5858
5859 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00005860 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00005861 ArgPack.pack_size(),
5862 ArgPack.pack_begin());
5863 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5864 }
5865
5866 return TemplateName(Subst);
5867}
5868
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005869/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00005870/// TargetInfo, produce the corresponding type. The unsigned @p Type
5871/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00005872CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005873 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00005874 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005875 case TargetInfo::SignedShort: return ShortTy;
5876 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5877 case TargetInfo::SignedInt: return IntTy;
5878 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5879 case TargetInfo::SignedLong: return LongTy;
5880 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5881 case TargetInfo::SignedLongLong: return LongLongTy;
5882 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5883 }
5884
David Blaikie83d382b2011-09-23 05:06:16 +00005885 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005886}
Ted Kremenek77c51b22008-07-24 23:58:27 +00005887
5888//===----------------------------------------------------------------------===//
5889// Type Predicates.
5890//===----------------------------------------------------------------------===//
5891
Fariborz Jahanian96207692009-02-18 21:49:28 +00005892/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5893/// garbage collection attribute.
5894///
John McCall553d45a2011-01-12 00:34:59 +00005895Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005896 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00005897 return Qualifiers::GCNone;
5898
David Blaikiebbafb8a2012-03-11 07:00:24 +00005899 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00005900 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5901
5902 // Default behaviour under objective-C's gc is for ObjC pointers
5903 // (or pointers to them) be treated as though they were declared
5904 // as __strong.
5905 if (GCAttrs == Qualifiers::GCNone) {
5906 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5907 return Qualifiers::Strong;
5908 else if (Ty->isPointerType())
5909 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5910 } else {
5911 // It's not valid to set GC attributes on anything that isn't a
5912 // pointer.
5913#ifndef NDEBUG
5914 QualType CT = Ty->getCanonicalTypeInternal();
5915 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5916 CT = AT->getElementType();
5917 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5918#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00005919 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00005920 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00005921}
5922
Chris Lattner49af6a42008-04-07 06:51:04 +00005923//===----------------------------------------------------------------------===//
5924// Type Compatibility Testing
5925//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00005926
Mike Stump11289f42009-09-09 15:08:12 +00005927/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005928/// compatible.
5929static bool areCompatVectorTypes(const VectorType *LHS,
5930 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00005931 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00005932 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00005933 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00005934}
5935
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005936bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5937 QualType SecondVec) {
5938 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5939 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5940
5941 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5942 return true;
5943
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005944 // Treat Neon vector types and most AltiVec vector types as if they are the
5945 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005946 const VectorType *First = FirstVec->getAs<VectorType>();
5947 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005948 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005949 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005950 First->getVectorKind() != VectorType::AltiVecPixel &&
5951 First->getVectorKind() != VectorType::AltiVecBool &&
5952 Second->getVectorKind() != VectorType::AltiVecPixel &&
5953 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005954 return true;
5955
5956 return false;
5957}
5958
Steve Naroff8e6aee52009-07-23 01:01:38 +00005959//===----------------------------------------------------------------------===//
5960// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5961//===----------------------------------------------------------------------===//
5962
5963/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5964/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00005965bool
5966ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5967 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00005968 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005969 return true;
5970 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5971 E = rProto->protocol_end(); PI != E; ++PI)
5972 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5973 return true;
5974 return false;
5975}
5976
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00005977/// QualifiedIdConformsQualifiedId - compare id<pr,...> with id<pr1,...>
Steve Naroff8e6aee52009-07-23 01:01:38 +00005978/// return true if lhs's protocols conform to rhs's protocol; false
5979/// otherwise.
5980bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5981 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5982 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5983 return false;
5984}
5985
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00005986/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
5987/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005988bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5989 QualType rhs) {
5990 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5991 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5992 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5993
5994 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5995 E = lhsQID->qual_end(); I != E; ++I) {
5996 bool match = false;
5997 ObjCProtocolDecl *lhsProto = *I;
5998 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5999 E = rhsOPT->qual_end(); J != E; ++J) {
6000 ObjCProtocolDecl *rhsProto = *J;
6001 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6002 match = true;
6003 break;
6004 }
6005 }
6006 if (!match)
6007 return false;
6008 }
6009 return true;
6010}
6011
Steve Naroff8e6aee52009-07-23 01:01:38 +00006012/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6013/// ObjCQualifiedIDType.
6014bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6015 bool compare) {
6016 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006017 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006018 lhs->isObjCIdType() || lhs->isObjCClassType())
6019 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006020 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006021 rhs->isObjCIdType() || rhs->isObjCClassType())
6022 return true;
6023
6024 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006025 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006026
Steve Naroff8e6aee52009-07-23 01:01:38 +00006027 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006028
Steve Naroff8e6aee52009-07-23 01:01:38 +00006029 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006030 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006031 // make sure we check the class hierarchy.
6032 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6033 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6034 E = lhsQID->qual_end(); I != E; ++I) {
6035 // when comparing an id<P> on lhs with a static type on rhs,
6036 // see if static class implements all of id's protocols, directly or
6037 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006038 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006039 return false;
6040 }
6041 }
6042 // If there are no qualifiers and no interface, we have an 'id'.
6043 return true;
6044 }
Mike Stump11289f42009-09-09 15:08:12 +00006045 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006046 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6047 E = lhsQID->qual_end(); I != E; ++I) {
6048 ObjCProtocolDecl *lhsProto = *I;
6049 bool match = false;
6050
6051 // when comparing an id<P> on lhs with a static type on rhs,
6052 // see if static class implements all of id's protocols, directly or
6053 // through its super class and categories.
6054 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6055 E = rhsOPT->qual_end(); J != E; ++J) {
6056 ObjCProtocolDecl *rhsProto = *J;
6057 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6058 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6059 match = true;
6060 break;
6061 }
6062 }
Mike Stump11289f42009-09-09 15:08:12 +00006063 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006064 // make sure we check the class hierarchy.
6065 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6066 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6067 E = lhsQID->qual_end(); I != E; ++I) {
6068 // when comparing an id<P> on lhs with a static type on rhs,
6069 // see if static class implements all of id's protocols, directly or
6070 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006071 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006072 match = true;
6073 break;
6074 }
6075 }
6076 }
6077 if (!match)
6078 return false;
6079 }
Mike Stump11289f42009-09-09 15:08:12 +00006080
Steve Naroff8e6aee52009-07-23 01:01:38 +00006081 return true;
6082 }
Mike Stump11289f42009-09-09 15:08:12 +00006083
Steve Naroff8e6aee52009-07-23 01:01:38 +00006084 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6085 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6086
Mike Stump11289f42009-09-09 15:08:12 +00006087 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006088 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006089 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006090 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6091 E = lhsOPT->qual_end(); I != E; ++I) {
6092 ObjCProtocolDecl *lhsProto = *I;
6093 bool match = false;
6094
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006095 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006096 // see if static class implements all of id's protocols, directly or
6097 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006098 // First, lhs protocols in the qualifier list must be found, direct
6099 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006100 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6101 E = rhsQID->qual_end(); J != E; ++J) {
6102 ObjCProtocolDecl *rhsProto = *J;
6103 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6104 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6105 match = true;
6106 break;
6107 }
6108 }
6109 if (!match)
6110 return false;
6111 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006112
6113 // Static class's protocols, or its super class or category protocols
6114 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6115 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6116 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6117 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6118 // This is rather dubious but matches gcc's behavior. If lhs has
6119 // no type qualifier and its class has no static protocol(s)
6120 // assume that it is mismatch.
6121 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6122 return false;
6123 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6124 LHSInheritedProtocols.begin(),
6125 E = LHSInheritedProtocols.end(); I != E; ++I) {
6126 bool match = false;
6127 ObjCProtocolDecl *lhsProto = (*I);
6128 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6129 E = rhsQID->qual_end(); J != E; ++J) {
6130 ObjCProtocolDecl *rhsProto = *J;
6131 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6132 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6133 match = true;
6134 break;
6135 }
6136 }
6137 if (!match)
6138 return false;
6139 }
6140 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006141 return true;
6142 }
6143 return false;
6144}
6145
Eli Friedman47f77112008-08-22 00:56:42 +00006146/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006147/// compatible for assignment from RHS to LHS. This handles validation of any
6148/// protocol qualifiers on the LHS or RHS.
6149///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006150bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6151 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006152 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6153 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6154
Steve Naroff1329fa02009-07-15 18:40:39 +00006155 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006156 if (LHS->isObjCUnqualifiedIdOrClass() ||
6157 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006158 return true;
6159
John McCall8b07ec22010-05-15 11:32:37 +00006160 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006161 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6162 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006163 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006164
6165 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6166 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6167 QualType(RHSOPT,0));
6168
John McCall8b07ec22010-05-15 11:32:37 +00006169 // If we have 2 user-defined types, fall into that path.
6170 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006171 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006172
Steve Naroff8e6aee52009-07-23 01:01:38 +00006173 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006174}
6175
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006176/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006177/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006178/// arguments in block literals. When passed as arguments, passing 'A*' where
6179/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6180/// not OK. For the return type, the opposite is not OK.
6181bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6182 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006183 const ObjCObjectPointerType *RHSOPT,
6184 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006185 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006186 return true;
6187
6188 if (LHSOPT->isObjCBuiltinType()) {
6189 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6190 }
6191
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006192 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006193 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6194 QualType(RHSOPT,0),
6195 false);
6196
6197 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6198 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6199 if (LHS && RHS) { // We have 2 user-defined types.
6200 if (LHS != RHS) {
6201 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006202 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006203 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006204 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006205 }
6206 else
6207 return true;
6208 }
6209 return false;
6210}
6211
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006212/// getIntersectionOfProtocols - This routine finds the intersection of set
6213/// of protocols inherited from two distinct objective-c pointer objects.
6214/// It is used to build composite qualifier list of the composite type of
6215/// the conditional expression involving two objective-c pointer objects.
6216static
6217void getIntersectionOfProtocols(ASTContext &Context,
6218 const ObjCObjectPointerType *LHSOPT,
6219 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006220 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006221
John McCall8b07ec22010-05-15 11:32:37 +00006222 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6223 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6224 assert(LHS->getInterface() && "LHS must have an interface base");
6225 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006226
6227 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6228 unsigned LHSNumProtocols = LHS->getNumProtocols();
6229 if (LHSNumProtocols > 0)
6230 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6231 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006232 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006233 Context.CollectInheritedProtocols(LHS->getInterface(),
6234 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006235 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6236 LHSInheritedProtocols.end());
6237 }
6238
6239 unsigned RHSNumProtocols = RHS->getNumProtocols();
6240 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006241 ObjCProtocolDecl **RHSProtocols =
6242 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006243 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6244 if (InheritedProtocolSet.count(RHSProtocols[i]))
6245 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006246 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006247 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006248 Context.CollectInheritedProtocols(RHS->getInterface(),
6249 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006250 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6251 RHSInheritedProtocols.begin(),
6252 E = RHSInheritedProtocols.end(); I != E; ++I)
6253 if (InheritedProtocolSet.count((*I)))
6254 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006255 }
6256}
6257
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006258/// areCommonBaseCompatible - Returns common base class of the two classes if
6259/// one found. Note that this is O'2 algorithm. But it will be called as the
6260/// last type comparison in a ?-exp of ObjC pointer types before a
6261/// warning is issued. So, its invokation is extremely rare.
6262QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006263 const ObjCObjectPointerType *Lptr,
6264 const ObjCObjectPointerType *Rptr) {
6265 const ObjCObjectType *LHS = Lptr->getObjectType();
6266 const ObjCObjectType *RHS = Rptr->getObjectType();
6267 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6268 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006269 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006270 return QualType();
6271
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006272 do {
John McCall8b07ec22010-05-15 11:32:37 +00006273 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006274 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006275 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006276 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6277
6278 QualType Result = QualType(LHS, 0);
6279 if (!Protocols.empty())
6280 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6281 Result = getObjCObjectPointerType(Result);
6282 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006283 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006284 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006285
6286 return QualType();
6287}
6288
John McCall8b07ec22010-05-15 11:32:37 +00006289bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6290 const ObjCObjectType *RHS) {
6291 assert(LHS->getInterface() && "LHS is not an interface type");
6292 assert(RHS->getInterface() && "RHS is not an interface type");
6293
Chris Lattner49af6a42008-04-07 06:51:04 +00006294 // Verify that the base decls are compatible: the RHS must be a subclass of
6295 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006296 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006297 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006298
Chris Lattner49af6a42008-04-07 06:51:04 +00006299 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6300 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006301 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006302 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006303
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006304 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6305 // more detailed analysis is required.
6306 if (RHS->getNumProtocols() == 0) {
6307 // OK, if LHS is a superclass of RHS *and*
6308 // this superclass is assignment compatible with LHS.
6309 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006310 bool IsSuperClass =
6311 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6312 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006313 // OK if conversion of LHS to SuperClass results in narrowing of types
6314 // ; i.e., SuperClass may implement at least one of the protocols
6315 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6316 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6317 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006318 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006319 // If super class has no protocols, it is not a match.
6320 if (SuperClassInheritedProtocols.empty())
6321 return false;
6322
6323 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6324 LHSPE = LHS->qual_end();
6325 LHSPI != LHSPE; LHSPI++) {
6326 bool SuperImplementsProtocol = false;
6327 ObjCProtocolDecl *LHSProto = (*LHSPI);
6328
6329 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6330 SuperClassInheritedProtocols.begin(),
6331 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6332 ObjCProtocolDecl *SuperClassProto = (*I);
6333 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6334 SuperImplementsProtocol = true;
6335 break;
6336 }
6337 }
6338 if (!SuperImplementsProtocol)
6339 return false;
6340 }
6341 return true;
6342 }
6343 return false;
6344 }
Mike Stump11289f42009-09-09 15:08:12 +00006345
John McCall8b07ec22010-05-15 11:32:37 +00006346 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6347 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00006348 LHSPI != LHSPE; LHSPI++) {
6349 bool RHSImplementsProtocol = false;
6350
6351 // If the RHS doesn't implement the protocol on the left, the types
6352 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00006353 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6354 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00006355 RHSPI != RHSPE; RHSPI++) {
6356 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006357 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00006358 break;
6359 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006360 }
6361 // FIXME: For better diagnostics, consider passing back the protocol name.
6362 if (!RHSImplementsProtocol)
6363 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006364 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006365 // The RHS implements all protocols listed on the LHS.
6366 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006367}
6368
Steve Naroffb7605152009-02-12 17:52:19 +00006369bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6370 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006371 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6372 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006373
Steve Naroff7cae42b2009-07-10 23:34:53 +00006374 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006375 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006376
6377 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6378 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006379}
6380
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006381bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6382 return canAssignObjCInterfaces(
6383 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6384 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6385}
6386
Mike Stump11289f42009-09-09 15:08:12 +00006387/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006388/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006389/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006390/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006391bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6392 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006393 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006394 return hasSameType(LHS, RHS);
6395
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006396 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006397}
6398
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006399bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006400 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006401}
6402
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006403bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6404 return !mergeTypes(LHS, RHS, true).isNull();
6405}
6406
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006407/// mergeTransparentUnionType - if T is a transparent union type and a member
6408/// of T is compatible with SubType, return the merged type, else return
6409/// QualType()
6410QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6411 bool OfBlockPointer,
6412 bool Unqualified) {
6413 if (const RecordType *UT = T->getAsUnionType()) {
6414 RecordDecl *UD = UT->getDecl();
6415 if (UD->hasAttr<TransparentUnionAttr>()) {
6416 for (RecordDecl::field_iterator it = UD->field_begin(),
6417 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00006418 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006419 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6420 if (!MT.isNull())
6421 return MT;
6422 }
6423 }
6424 }
6425
6426 return QualType();
6427}
6428
6429/// mergeFunctionArgumentTypes - merge two types which appear as function
6430/// argument types
6431QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6432 bool OfBlockPointer,
6433 bool Unqualified) {
6434 // GNU extension: two types are compatible if they appear as a function
6435 // argument, one of the types is a transparent union type and the other
6436 // type is compatible with a union member
6437 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6438 Unqualified);
6439 if (!lmerge.isNull())
6440 return lmerge;
6441
6442 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6443 Unqualified);
6444 if (!rmerge.isNull())
6445 return rmerge;
6446
6447 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6448}
6449
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006450QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006451 bool OfBlockPointer,
6452 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006453 const FunctionType *lbase = lhs->getAs<FunctionType>();
6454 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006455 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6456 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006457 bool allLTypes = true;
6458 bool allRTypes = true;
6459
6460 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006461 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006462 if (OfBlockPointer) {
6463 QualType RHS = rbase->getResultType();
6464 QualType LHS = lbase->getResultType();
6465 bool UnqualifiedResult = Unqualified;
6466 if (!UnqualifiedResult)
6467 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006468 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006469 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006470 else
John McCall8c6b56f2010-12-15 01:06:38 +00006471 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6472 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006473 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006474
6475 if (Unqualified)
6476 retType = retType.getUnqualifiedType();
6477
6478 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6479 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6480 if (Unqualified) {
6481 LRetType = LRetType.getUnqualifiedType();
6482 RRetType = RRetType.getUnqualifiedType();
6483 }
6484
6485 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006486 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006487 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006488 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006489
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006490 // FIXME: double check this
6491 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6492 // rbase->getRegParmAttr() != 0 &&
6493 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006494 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6495 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006496
Douglas Gregor8c940862010-01-18 17:14:39 +00006497 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00006498 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00006499 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006500
John McCall8c6b56f2010-12-15 01:06:38 +00006501 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006502 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6503 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006504 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6505 return QualType();
6506
John McCall31168b02011-06-15 23:02:42 +00006507 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6508 return QualType();
6509
John McCall8c6b56f2010-12-15 01:06:38 +00006510 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6511 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006512
Rafael Espindola8778c282012-11-29 16:09:03 +00006513 if (lbaseInfo.getNoReturn() != NoReturn)
6514 allLTypes = false;
6515 if (rbaseInfo.getNoReturn() != NoReturn)
6516 allRTypes = false;
6517
John McCall31168b02011-06-15 23:02:42 +00006518 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006519
Eli Friedman47f77112008-08-22 00:56:42 +00006520 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006521 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6522 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006523 unsigned lproto_nargs = lproto->getNumArgs();
6524 unsigned rproto_nargs = rproto->getNumArgs();
6525
6526 // Compatible functions must have the same number of arguments
6527 if (lproto_nargs != rproto_nargs)
6528 return QualType();
6529
6530 // Variadic and non-variadic functions aren't compatible
6531 if (lproto->isVariadic() != rproto->isVariadic())
6532 return QualType();
6533
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006534 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6535 return QualType();
6536
Fariborz Jahanian97676972011-09-28 21:52:05 +00006537 if (LangOpts.ObjCAutoRefCount &&
6538 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6539 return QualType();
6540
Eli Friedman47f77112008-08-22 00:56:42 +00006541 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006542 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00006543 for (unsigned i = 0; i < lproto_nargs; i++) {
6544 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6545 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006546 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6547 OfBlockPointer,
6548 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006549 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006550
6551 if (Unqualified)
6552 argtype = argtype.getUnqualifiedType();
6553
Eli Friedman47f77112008-08-22 00:56:42 +00006554 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006555 if (Unqualified) {
6556 largtype = largtype.getUnqualifiedType();
6557 rargtype = rargtype.getUnqualifiedType();
6558 }
6559
Chris Lattner465fa322008-10-05 17:34:18 +00006560 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6561 allLTypes = false;
6562 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6563 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006564 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006565
Eli Friedman47f77112008-08-22 00:56:42 +00006566 if (allLTypes) return lhs;
6567 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006568
6569 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6570 EPI.ExtInfo = einfo;
6571 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006572 }
6573
6574 if (lproto) allRTypes = false;
6575 if (rproto) allLTypes = false;
6576
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006577 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006578 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006579 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006580 if (proto->isVariadic()) return QualType();
6581 // Check that the types are compatible with the types that
6582 // would result from default argument promotions (C99 6.7.5.3p15).
6583 // The only types actually affected are promotable integer
6584 // types and floats, which would be passed as a different
6585 // type depending on whether the prototype is visible.
6586 unsigned proto_nargs = proto->getNumArgs();
6587 for (unsigned i = 0; i < proto_nargs; ++i) {
6588 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00006589
Eli Friedman448ce402012-08-30 00:44:15 +00006590 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00006591 // to pass enum values.
Eli Friedman448ce402012-08-30 00:44:15 +00006592 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
6593 argTy = Enum->getDecl()->getIntegerType();
6594 if (argTy.isNull())
6595 return QualType();
6596 }
Douglas Gregor2973d402010-02-03 19:27:29 +00006597
Eli Friedman47f77112008-08-22 00:56:42 +00006598 if (argTy->isPromotableIntegerType() ||
6599 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6600 return QualType();
6601 }
6602
6603 if (allLTypes) return lhs;
6604 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006605
6606 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6607 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00006608 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006609 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006610 }
6611
6612 if (allLTypes) return lhs;
6613 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00006614 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00006615}
6616
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006617QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006618 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006619 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00006620 // C++ [expr]: If an expression initially has the type "reference to T", the
6621 // type is adjusted to "T" prior to any further analysis, the expression
6622 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006623 // expression is an lvalue unless the reference is an rvalue reference and
6624 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00006625 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6626 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006627
6628 if (Unqualified) {
6629 LHS = LHS.getUnqualifiedType();
6630 RHS = RHS.getUnqualifiedType();
6631 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00006632
Eli Friedman47f77112008-08-22 00:56:42 +00006633 QualType LHSCan = getCanonicalType(LHS),
6634 RHSCan = getCanonicalType(RHS);
6635
6636 // If two types are identical, they are compatible.
6637 if (LHSCan == RHSCan)
6638 return LHS;
6639
John McCall8ccfcb52009-09-24 19:53:00 +00006640 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006641 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6642 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00006643 if (LQuals != RQuals) {
6644 // If any of these qualifiers are different, we have a type
6645 // mismatch.
6646 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00006647 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6648 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00006649 return QualType();
6650
6651 // Exactly one GC qualifier difference is allowed: __strong is
6652 // okay if the other type has no GC qualifier but is an Objective
6653 // C object pointer (i.e. implicitly strong by default). We fix
6654 // this by pretending that the unqualified type was actually
6655 // qualified __strong.
6656 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6657 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6658 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6659
6660 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6661 return QualType();
6662
6663 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6664 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6665 }
6666 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6667 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6668 }
Eli Friedman47f77112008-08-22 00:56:42 +00006669 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00006670 }
6671
6672 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00006673
Eli Friedmandcca6332009-06-01 01:22:52 +00006674 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6675 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00006676
Chris Lattnerfd652912008-01-14 05:45:46 +00006677 // We want to consider the two function types to be the same for these
6678 // comparisons, just force one to the other.
6679 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6680 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00006681
6682 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00006683 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6684 LHSClass = Type::ConstantArray;
6685 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6686 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00006687
John McCall8b07ec22010-05-15 11:32:37 +00006688 // ObjCInterfaces are just specialized ObjCObjects.
6689 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6690 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6691
Nate Begemance4d7fc2008-04-18 23:10:10 +00006692 // Canonicalize ExtVector -> Vector.
6693 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6694 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00006695
Chris Lattner95554662008-04-07 05:43:21 +00006696 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006697 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00006698 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00006699 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00006700 // Compatibility is based on the underlying type, not the promotion
6701 // type.
John McCall9dd450b2009-09-21 23:43:11 +00006702 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006703 QualType TINT = ETy->getDecl()->getIntegerType();
6704 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006705 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006706 }
John McCall9dd450b2009-09-21 23:43:11 +00006707 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006708 QualType TINT = ETy->getDecl()->getIntegerType();
6709 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006710 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006711 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006712 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00006713 if (OfBlockPointer && !BlockReturnType) {
6714 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6715 return LHS;
6716 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6717 return RHS;
6718 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006719
Eli Friedman47f77112008-08-22 00:56:42 +00006720 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00006721 }
Eli Friedman47f77112008-08-22 00:56:42 +00006722
Steve Naroffc6edcbd2008-01-09 22:43:08 +00006723 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006724 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006725#define TYPE(Class, Base)
6726#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00006727#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006728#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6729#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6730#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00006731 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006732
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006733 case Type::LValueReference:
6734 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006735 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00006736 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006737
John McCall8b07ec22010-05-15 11:32:37 +00006738 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006739 case Type::IncompleteArray:
6740 case Type::VariableArray:
6741 case Type::FunctionProto:
6742 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00006743 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006744
Chris Lattnerfd652912008-01-14 05:45:46 +00006745 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00006746 {
6747 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006748 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6749 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006750 if (Unqualified) {
6751 LHSPointee = LHSPointee.getUnqualifiedType();
6752 RHSPointee = RHSPointee.getUnqualifiedType();
6753 }
6754 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6755 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006756 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00006757 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006758 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00006759 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006760 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006761 return getPointerType(ResultType);
6762 }
Steve Naroff68e167d2008-12-10 17:49:55 +00006763 case Type::BlockPointer:
6764 {
6765 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006766 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6767 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006768 if (Unqualified) {
6769 LHSPointee = LHSPointee.getUnqualifiedType();
6770 RHSPointee = RHSPointee.getUnqualifiedType();
6771 }
6772 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6773 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00006774 if (ResultType.isNull()) return QualType();
6775 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6776 return LHS;
6777 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6778 return RHS;
6779 return getBlockPointerType(ResultType);
6780 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00006781 case Type::Atomic:
6782 {
6783 // Merge two pointer types, while trying to preserve typedef info
6784 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6785 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6786 if (Unqualified) {
6787 LHSValue = LHSValue.getUnqualifiedType();
6788 RHSValue = RHSValue.getUnqualifiedType();
6789 }
6790 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6791 Unqualified);
6792 if (ResultType.isNull()) return QualType();
6793 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6794 return LHS;
6795 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6796 return RHS;
6797 return getAtomicType(ResultType);
6798 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006799 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00006800 {
6801 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6802 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6803 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6804 return QualType();
6805
6806 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6807 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006808 if (Unqualified) {
6809 LHSElem = LHSElem.getUnqualifiedType();
6810 RHSElem = RHSElem.getUnqualifiedType();
6811 }
6812
6813 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006814 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00006815 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6816 return LHS;
6817 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6818 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00006819 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6820 ArrayType::ArraySizeModifier(), 0);
6821 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6822 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006823 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6824 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00006825 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6826 return LHS;
6827 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6828 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006829 if (LVAT) {
6830 // FIXME: This isn't correct! But tricky to implement because
6831 // the array's size has to be the size of LHS, but the type
6832 // has to be different.
6833 return LHS;
6834 }
6835 if (RVAT) {
6836 // FIXME: This isn't correct! But tricky to implement because
6837 // the array's size has to be the size of RHS, but the type
6838 // has to be different.
6839 return RHS;
6840 }
Eli Friedman3e62c212008-08-22 01:48:21 +00006841 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6842 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00006843 return getIncompleteArrayType(ResultType,
6844 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006845 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006846 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006847 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006848 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006849 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00006850 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00006851 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006852 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00006853 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00006854 case Type::Complex:
6855 // Distinct complex types are incompatible.
6856 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006857 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00006858 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00006859 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6860 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00006861 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00006862 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00006863 case Type::ObjCObject: {
6864 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00006865 // FIXME: This should be type compatibility, e.g. whether
6866 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00006867 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6868 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6869 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00006870 return LHS;
6871
Eli Friedman47f77112008-08-22 00:56:42 +00006872 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00006873 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006874 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006875 if (OfBlockPointer) {
6876 if (canAssignObjCInterfacesInBlockPointer(
6877 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006878 RHS->getAs<ObjCObjectPointerType>(),
6879 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00006880 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006881 return QualType();
6882 }
John McCall9dd450b2009-09-21 23:43:11 +00006883 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6884 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006885 return LHS;
6886
Steve Naroffc68cfcf2008-12-10 22:14:21 +00006887 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00006888 }
Steve Naroff32e44c02007-10-15 20:41:53 +00006889 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006890
David Blaikie8a40f702012-01-17 06:56:22 +00006891 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00006892}
Ted Kremenekfc581a92007-10-31 17:10:13 +00006893
Fariborz Jahanian97676972011-09-28 21:52:05 +00006894bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6895 const FunctionProtoType *FromFunctionType,
6896 const FunctionProtoType *ToFunctionType) {
6897 if (FromFunctionType->hasAnyConsumedArgs() !=
6898 ToFunctionType->hasAnyConsumedArgs())
6899 return false;
6900 FunctionProtoType::ExtProtoInfo FromEPI =
6901 FromFunctionType->getExtProtoInfo();
6902 FunctionProtoType::ExtProtoInfo ToEPI =
6903 ToFunctionType->getExtProtoInfo();
6904 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6905 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6906 ArgIdx != NumArgs; ++ArgIdx) {
6907 if (FromEPI.ConsumedArguments[ArgIdx] !=
6908 ToEPI.ConsumedArguments[ArgIdx])
6909 return false;
6910 }
6911 return true;
6912}
6913
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006914/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6915/// 'RHS' attributes and returns the merged version; including for function
6916/// return types.
6917QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6918 QualType LHSCan = getCanonicalType(LHS),
6919 RHSCan = getCanonicalType(RHS);
6920 // If two types are identical, they are compatible.
6921 if (LHSCan == RHSCan)
6922 return LHS;
6923 if (RHSCan->isFunctionType()) {
6924 if (!LHSCan->isFunctionType())
6925 return QualType();
6926 QualType OldReturnType =
6927 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6928 QualType NewReturnType =
6929 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6930 QualType ResReturnType =
6931 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6932 if (ResReturnType.isNull())
6933 return QualType();
6934 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6935 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6936 // In either case, use OldReturnType to build the new function type.
6937 const FunctionType *F = LHS->getAs<FunctionType>();
6938 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00006939 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6940 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006941 QualType ResultType
6942 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006943 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006944 return ResultType;
6945 }
6946 }
6947 return QualType();
6948 }
6949
6950 // If the qualifiers are different, the types can still be merged.
6951 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6952 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6953 if (LQuals != RQuals) {
6954 // If any of these qualifiers are different, we have a type mismatch.
6955 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6956 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6957 return QualType();
6958
6959 // Exactly one GC qualifier difference is allowed: __strong is
6960 // okay if the other type has no GC qualifier but is an Objective
6961 // C object pointer (i.e. implicitly strong by default). We fix
6962 // this by pretending that the unqualified type was actually
6963 // qualified __strong.
6964 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6965 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6966 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6967
6968 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6969 return QualType();
6970
6971 if (GC_L == Qualifiers::Strong)
6972 return LHS;
6973 if (GC_R == Qualifiers::Strong)
6974 return RHS;
6975 return QualType();
6976 }
6977
6978 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6979 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6980 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6981 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6982 if (ResQT == LHSBaseQT)
6983 return LHS;
6984 if (ResQT == RHSBaseQT)
6985 return RHS;
6986 }
6987 return QualType();
6988}
6989
Chris Lattner4ba0cef2008-04-07 07:01:58 +00006990//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006991// Integer Predicates
6992//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00006993
Jay Foad39c79802011-01-12 09:06:06 +00006994unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00006995 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00006996 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00006997 if (T->isBooleanType())
6998 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00006999 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007000 return (unsigned)getTypeSize(T);
7001}
7002
Abramo Bagnara13640492012-09-09 10:21:24 +00007003QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007004 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007005
7006 // Turn <4 x signed int> -> <4 x unsigned int>
7007 if (const VectorType *VTy = T->getAs<VectorType>())
7008 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007009 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007010
7011 // For enums, we return the unsigned version of the base type.
7012 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007013 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007014
7015 const BuiltinType *BTy = T->getAs<BuiltinType>();
7016 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007017 switch (BTy->getKind()) {
7018 case BuiltinType::Char_S:
7019 case BuiltinType::SChar:
7020 return UnsignedCharTy;
7021 case BuiltinType::Short:
7022 return UnsignedShortTy;
7023 case BuiltinType::Int:
7024 return UnsignedIntTy;
7025 case BuiltinType::Long:
7026 return UnsignedLongTy;
7027 case BuiltinType::LongLong:
7028 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007029 case BuiltinType::Int128:
7030 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007031 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007032 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007033 }
7034}
7035
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007036ASTMutationListener::~ASTMutationListener() { }
7037
Chris Lattnerecd79c62009-06-14 00:45:47 +00007038
7039//===----------------------------------------------------------------------===//
7040// Builtin Type Computation
7041//===----------------------------------------------------------------------===//
7042
7043/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007044/// pointer over the consumed characters. This returns the resultant type. If
7045/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7046/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7047/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007048///
7049/// RequiresICE is filled in on return to indicate whether the value is required
7050/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007051static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007052 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007053 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007054 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007055 // Modifiers.
7056 int HowLong = 0;
7057 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007058 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007059
Chris Lattnerdc226c22010-10-01 22:42:38 +00007060 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007061 bool Done = false;
7062 while (!Done) {
7063 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007064 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007065 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007066 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007067 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007068 case 'S':
7069 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7070 assert(!Signed && "Can't use 'S' modifier multiple times!");
7071 Signed = true;
7072 break;
7073 case 'U':
7074 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7075 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7076 Unsigned = true;
7077 break;
7078 case 'L':
7079 assert(HowLong <= 2 && "Can't have LLLL modifier");
7080 ++HowLong;
7081 break;
7082 }
7083 }
7084
7085 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007086
Chris Lattnerecd79c62009-06-14 00:45:47 +00007087 // Read the base type.
7088 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007089 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007090 case 'v':
7091 assert(HowLong == 0 && !Signed && !Unsigned &&
7092 "Bad modifiers used with 'v'!");
7093 Type = Context.VoidTy;
7094 break;
7095 case 'f':
7096 assert(HowLong == 0 && !Signed && !Unsigned &&
7097 "Bad modifiers used with 'f'!");
7098 Type = Context.FloatTy;
7099 break;
7100 case 'd':
7101 assert(HowLong < 2 && !Signed && !Unsigned &&
7102 "Bad modifiers used with 'd'!");
7103 if (HowLong)
7104 Type = Context.LongDoubleTy;
7105 else
7106 Type = Context.DoubleTy;
7107 break;
7108 case 's':
7109 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7110 if (Unsigned)
7111 Type = Context.UnsignedShortTy;
7112 else
7113 Type = Context.ShortTy;
7114 break;
7115 case 'i':
7116 if (HowLong == 3)
7117 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7118 else if (HowLong == 2)
7119 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7120 else if (HowLong == 1)
7121 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7122 else
7123 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7124 break;
7125 case 'c':
7126 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7127 if (Signed)
7128 Type = Context.SignedCharTy;
7129 else if (Unsigned)
7130 Type = Context.UnsignedCharTy;
7131 else
7132 Type = Context.CharTy;
7133 break;
7134 case 'b': // boolean
7135 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7136 Type = Context.BoolTy;
7137 break;
7138 case 'z': // size_t.
7139 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7140 Type = Context.getSizeType();
7141 break;
7142 case 'F':
7143 Type = Context.getCFConstantStringType();
7144 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007145 case 'G':
7146 Type = Context.getObjCIdType();
7147 break;
7148 case 'H':
7149 Type = Context.getObjCSelType();
7150 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007151 case 'a':
7152 Type = Context.getBuiltinVaListType();
7153 assert(!Type.isNull() && "builtin va list type not initialized!");
7154 break;
7155 case 'A':
7156 // This is a "reference" to a va_list; however, what exactly
7157 // this means depends on how va_list is defined. There are two
7158 // different kinds of va_list: ones passed by value, and ones
7159 // passed by reference. An example of a by-value va_list is
7160 // x86, where va_list is a char*. An example of by-ref va_list
7161 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7162 // we want this argument to be a char*&; for x86-64, we want
7163 // it to be a __va_list_tag*.
7164 Type = Context.getBuiltinVaListType();
7165 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007166 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007167 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007168 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007169 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007170 break;
7171 case 'V': {
7172 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007173 unsigned NumElements = strtoul(Str, &End, 10);
7174 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007175 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007176
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007177 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7178 RequiresICE, false);
7179 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007180
7181 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007182 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007183 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007184 break;
7185 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007186 case 'E': {
7187 char *End;
7188
7189 unsigned NumElements = strtoul(Str, &End, 10);
7190 assert(End != Str && "Missing vector size");
7191
7192 Str = End;
7193
7194 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7195 false);
7196 Type = Context.getExtVectorType(ElementType, NumElements);
7197 break;
7198 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007199 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007200 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7201 false);
7202 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007203 Type = Context.getComplexType(ElementType);
7204 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007205 }
7206 case 'Y' : {
7207 Type = Context.getPointerDiffType();
7208 break;
7209 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007210 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007211 Type = Context.getFILEType();
7212 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007213 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007214 return QualType();
7215 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007216 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007217 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007218 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007219 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007220 else
7221 Type = Context.getjmp_bufType();
7222
Mike Stump2adb4da2009-07-28 23:47:15 +00007223 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007224 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007225 return QualType();
7226 }
7227 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007228 case 'K':
7229 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7230 Type = Context.getucontext_tType();
7231
7232 if (Type.isNull()) {
7233 Error = ASTContext::GE_Missing_ucontext;
7234 return QualType();
7235 }
7236 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00007237 case 'p':
7238 Type = Context.getProcessIDType();
7239 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007240 }
Mike Stump11289f42009-09-09 15:08:12 +00007241
Chris Lattnerdc226c22010-10-01 22:42:38 +00007242 // If there are modifiers and if we're allowed to parse them, go for it.
7243 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007244 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007245 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007246 default: Done = true; --Str; break;
7247 case '*':
7248 case '&': {
7249 // Both pointers and references can have their pointee types
7250 // qualified with an address space.
7251 char *End;
7252 unsigned AddrSpace = strtoul(Str, &End, 10);
7253 if (End != Str && AddrSpace != 0) {
7254 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7255 Str = End;
7256 }
7257 if (c == '*')
7258 Type = Context.getPointerType(Type);
7259 else
7260 Type = Context.getLValueReferenceType(Type);
7261 break;
7262 }
7263 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7264 case 'C':
7265 Type = Type.withConst();
7266 break;
7267 case 'D':
7268 Type = Context.getVolatileType(Type);
7269 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007270 case 'R':
7271 Type = Type.withRestrict();
7272 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007273 }
7274 }
Chris Lattner84733392010-10-01 07:13:18 +00007275
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007276 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007277 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007278
Chris Lattnerecd79c62009-06-14 00:45:47 +00007279 return Type;
7280}
7281
7282/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007283QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007284 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007285 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007286 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007287
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007288 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007289
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007290 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007291 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007292 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7293 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007294 if (Error != GE_None)
7295 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007296
7297 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7298
Chris Lattnerecd79c62009-06-14 00:45:47 +00007299 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007300 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007301 if (Error != GE_None)
7302 return QualType();
7303
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007304 // If this argument is required to be an IntegerConstantExpression and the
7305 // caller cares, fill in the bitmask we return.
7306 if (RequiresICE && IntegerConstantArgs)
7307 *IntegerConstantArgs |= 1 << ArgTypes.size();
7308
Chris Lattnerecd79c62009-06-14 00:45:47 +00007309 // Do array -> pointer decay. The builtin should use the decayed type.
7310 if (Ty->isArrayType())
7311 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007312
Chris Lattnerecd79c62009-06-14 00:45:47 +00007313 ArgTypes.push_back(Ty);
7314 }
7315
7316 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7317 "'.' should only occur at end of builtin type list!");
7318
John McCall991eb4b2010-12-21 00:44:39 +00007319 FunctionType::ExtInfo EI;
7320 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7321
7322 bool Variadic = (TypeStr[0] == '.');
7323
7324 // We really shouldn't be making a no-proto type here, especially in C++.
7325 if (ArgTypes.empty() && Variadic)
7326 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007327
John McCalldb40c7f2010-12-14 08:05:40 +00007328 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007329 EPI.ExtInfo = EI;
7330 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007331
7332 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007333}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007334
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007335GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
7336 GVALinkage External = GVA_StrongExternal;
7337
7338 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007339 switch (L) {
7340 case NoLinkage:
7341 case InternalLinkage:
7342 case UniqueExternalLinkage:
7343 return GVA_Internal;
7344
7345 case ExternalLinkage:
7346 switch (FD->getTemplateSpecializationKind()) {
7347 case TSK_Undeclared:
7348 case TSK_ExplicitSpecialization:
7349 External = GVA_StrongExternal;
7350 break;
7351
7352 case TSK_ExplicitInstantiationDefinition:
7353 return GVA_ExplicitTemplateInstantiation;
7354
7355 case TSK_ExplicitInstantiationDeclaration:
7356 case TSK_ImplicitInstantiation:
7357 External = GVA_TemplateInstantiation;
7358 break;
7359 }
7360 }
7361
7362 if (!FD->isInlined())
7363 return External;
7364
David Blaikiebbafb8a2012-03-11 07:00:24 +00007365 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007366 // GNU or C99 inline semantics. Determine whether this symbol should be
7367 // externally visible.
7368 if (FD->isInlineDefinitionExternallyVisible())
7369 return External;
7370
7371 // C99 inline semantics, where the symbol is not externally visible.
7372 return GVA_C99Inline;
7373 }
7374
7375 // C++0x [temp.explicit]p9:
7376 // [ Note: The intent is that an inline function that is the subject of
7377 // an explicit instantiation declaration will still be implicitly
7378 // instantiated when used so that the body can be considered for
7379 // inlining, but that no out-of-line copy of the inline function would be
7380 // generated in the translation unit. -- end note ]
7381 if (FD->getTemplateSpecializationKind()
7382 == TSK_ExplicitInstantiationDeclaration)
7383 return GVA_C99Inline;
7384
7385 return GVA_CXXInline;
7386}
7387
7388GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7389 // If this is a static data member, compute the kind of template
7390 // specialization. Otherwise, this variable is not part of a
7391 // template.
7392 TemplateSpecializationKind TSK = TSK_Undeclared;
7393 if (VD->isStaticDataMember())
7394 TSK = VD->getTemplateSpecializationKind();
7395
7396 Linkage L = VD->getLinkage();
David Blaikiebbafb8a2012-03-11 07:00:24 +00007397 if (L == ExternalLinkage && getLangOpts().CPlusPlus &&
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007398 VD->getType()->getLinkage() == UniqueExternalLinkage)
7399 L = UniqueExternalLinkage;
7400
7401 switch (L) {
7402 case NoLinkage:
7403 case InternalLinkage:
7404 case UniqueExternalLinkage:
7405 return GVA_Internal;
7406
7407 case ExternalLinkage:
7408 switch (TSK) {
7409 case TSK_Undeclared:
7410 case TSK_ExplicitSpecialization:
7411 return GVA_StrongExternal;
7412
7413 case TSK_ExplicitInstantiationDeclaration:
7414 llvm_unreachable("Variable should not be instantiated");
7415 // Fall through to treat this like any other instantiation.
7416
7417 case TSK_ExplicitInstantiationDefinition:
7418 return GVA_ExplicitTemplateInstantiation;
7419
7420 case TSK_ImplicitInstantiation:
7421 return GVA_TemplateInstantiation;
7422 }
7423 }
7424
David Blaikie8a40f702012-01-17 06:56:22 +00007425 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007426}
7427
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007428bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007429 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7430 if (!VD->isFileVarDecl())
7431 return false;
Argyrios Kyrtzidisa98e8612011-09-13 21:35:00 +00007432 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007433 return false;
7434
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007435 // Weak references don't produce any output by themselves.
7436 if (D->hasAttr<WeakRefAttr>())
7437 return false;
7438
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007439 // Aliases and used decls are required.
7440 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7441 return true;
7442
7443 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7444 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007445 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007446 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007447
7448 // Constructors and destructors are required.
7449 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7450 return true;
7451
7452 // The key function for a class is required.
7453 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7454 const CXXRecordDecl *RD = MD->getParent();
7455 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7456 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
7457 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7458 return true;
7459 }
7460 }
7461
7462 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7463
7464 // static, static inline, always_inline, and extern inline functions can
7465 // always be deferred. Normal inline functions can be deferred in C99/C++.
7466 // Implicit template instantiations can also be deferred in C++.
7467 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007468 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007469 return false;
7470 return true;
7471 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007472
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007473 const VarDecl *VD = cast<VarDecl>(D);
7474 assert(VD->isFileVarDecl() && "Expected file scoped var");
7475
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007476 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7477 return false;
7478
Richard Smitha0e5e542012-11-12 21:38:00 +00007479 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007480 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smitha0e5e542012-11-12 21:38:00 +00007481 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7482 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007483
Richard Smitha0e5e542012-11-12 21:38:00 +00007484 // Variables that have destruction with side-effects are required.
7485 if (VD->getType().isDestructedType())
7486 return true;
7487
7488 // Variables that have initialization with side-effects are required.
7489 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7490 return true;
7491
7492 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007493}
Charles Davis53c59df2010-08-16 03:33:14 +00007494
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007495CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davis99202b32010-11-09 18:04:24 +00007496 // Pass through to the C++ ABI object
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007497 return ABI->getDefaultMethodCallConv(isVariadic);
7498}
7499
7500CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
7501 if (CC == CC_C && !LangOpts.MRTD && getTargetInfo().getCXXABI() != CXXABI_Microsoft)
7502 return CC_Default;
7503 return CC;
Charles Davis99202b32010-11-09 18:04:24 +00007504}
7505
Jay Foad39c79802011-01-12 09:06:06 +00007506bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007507 // Pass through to the C++ ABI object
7508 return ABI->isNearlyEmpty(RD);
7509}
7510
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007511MangleContext *ASTContext::createMangleContext() {
Douglas Gregore8bbc122011-09-02 00:18:52 +00007512 switch (Target->getCXXABI()) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007513 case CXXABI_ARM:
7514 case CXXABI_Itanium:
7515 return createItaniumMangleContext(*this, getDiagnostics());
7516 case CXXABI_Microsoft:
7517 return createMicrosoftMangleContext(*this, getDiagnostics());
7518 }
David Blaikie83d382b2011-09-23 05:06:16 +00007519 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007520}
7521
Charles Davis53c59df2010-08-16 03:33:14 +00007522CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007523
7524size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00007525 return ASTRecordLayouts.getMemorySize()
7526 + llvm::capacity_in_bytes(ObjCLayouts)
7527 + llvm::capacity_in_bytes(KeyFunctions)
7528 + llvm::capacity_in_bytes(ObjCImpls)
7529 + llvm::capacity_in_bytes(BlockVarCopyInits)
7530 + llvm::capacity_in_bytes(DeclAttrs)
7531 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7532 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7533 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7534 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7535 + llvm::capacity_in_bytes(OverriddenMethods)
7536 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007537 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00007538 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007539}
Ted Kremenek540017e2011-10-06 05:00:56 +00007540
David Blaikie095deba2012-11-14 01:52:05 +00007541void ASTContext::addUnnamedTag(const TagDecl *Tag) {
7542 // FIXME: This mangling should be applied to function local classes too
7543 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl() ||
7544 !isa<CXXRecordDecl>(Tag->getParent()) || Tag->getLinkage() != ExternalLinkage)
7545 return;
7546
7547 std::pair<llvm::DenseMap<const DeclContext *, unsigned>::iterator, bool> P =
7548 UnnamedMangleContexts.insert(std::make_pair(Tag->getParent(), 0));
7549 UnnamedMangleNumbers.insert(std::make_pair(Tag, P.first->second++));
7550}
7551
7552int ASTContext::getUnnamedTagManglingNumber(const TagDecl *Tag) const {
7553 llvm::DenseMap<const TagDecl *, unsigned>::const_iterator I =
7554 UnnamedMangleNumbers.find(Tag);
7555 return I != UnnamedMangleNumbers.end() ? I->second : -1;
7556}
7557
Douglas Gregor63798542012-02-20 19:44:39 +00007558unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7559 CXXRecordDecl *Lambda = CallOperator->getParent();
7560 return LambdaMangleContexts[Lambda->getDeclContext()]
7561 .getManglingNumber(CallOperator);
7562}
7563
7564
Ted Kremenek540017e2011-10-06 05:00:56 +00007565void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7566 ParamIndices[D] = index;
7567}
7568
7569unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7570 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7571 assert(I != ParamIndices.end() &&
7572 "ParmIndices lacks entry set by ParmVarDecl");
7573 return I->second;
7574}