blob: 44f13b6906f7a783831d5fd81aa8ed3eca4f9f74 [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);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000877
878 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +0000879 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
880 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000881
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000882 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000883
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000884 // void * type
885 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000886
887 // nullptr type (C++0x 2.14.7)
888 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000889
890 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
891 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +0000892
893 // Builtin type used to help define __builtin_va_list.
894 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +0000895}
896
David Blaikie9c902b52011-09-25 23:23:43 +0000897DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000898 return SourceMgr.getDiagnostics();
899}
900
Douglas Gregor561eceb2010-08-30 16:49:28 +0000901AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
902 AttrVec *&Result = DeclAttrs[D];
903 if (!Result) {
904 void *Mem = Allocate(sizeof(AttrVec));
905 Result = new (Mem) AttrVec;
906 }
907
908 return *Result;
909}
910
911/// \brief Erase the attributes corresponding to the given declaration.
912void ASTContext::eraseDeclAttrs(const Decl *D) {
913 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
914 if (Pos != DeclAttrs.end()) {
915 Pos->second->~AttrVec();
916 DeclAttrs.erase(Pos);
917 }
918}
919
Douglas Gregor86d142a2009-10-08 07:24:58 +0000920MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000921ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000922 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000923 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000924 = InstantiatedFromStaticDataMember.find(Var);
925 if (Pos == InstantiatedFromStaticDataMember.end())
926 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000927
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000928 return Pos->second;
929}
930
Mike Stump11289f42009-09-09 15:08:12 +0000931void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000932ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000933 TemplateSpecializationKind TSK,
934 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000935 assert(Inst->isStaticDataMember() && "Not a static data member");
936 assert(Tmpl->isStaticDataMember() && "Not a static data member");
937 assert(!InstantiatedFromStaticDataMember[Inst] &&
938 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000939 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000940 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000941}
942
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000943FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
944 const FunctionDecl *FD){
945 assert(FD && "Specialization is 0");
946 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +0000947 = ClassScopeSpecializationPattern.find(FD);
948 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000949 return 0;
950
951 return Pos->second;
952}
953
954void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
955 FunctionDecl *Pattern) {
956 assert(FD && "Specialization is 0");
957 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +0000958 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000959}
960
John McCalle61f2ba2009-11-18 02:36:19 +0000961NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000962ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000963 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000964 = InstantiatedFromUsingDecl.find(UUD);
965 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000966 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000967
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000968 return Pos->second;
969}
970
971void
John McCallb96ec562009-12-04 22:46:56 +0000972ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
973 assert((isa<UsingDecl>(Pattern) ||
974 isa<UnresolvedUsingValueDecl>(Pattern) ||
975 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
976 "pattern decl is not a using decl");
977 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
978 InstantiatedFromUsingDecl[Inst] = Pattern;
979}
980
981UsingShadowDecl *
982ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
983 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
984 = InstantiatedFromUsingShadowDecl.find(Inst);
985 if (Pos == InstantiatedFromUsingShadowDecl.end())
986 return 0;
987
988 return Pos->second;
989}
990
991void
992ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
993 UsingShadowDecl *Pattern) {
994 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
995 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000996}
997
Anders Carlsson5da84842009-09-01 04:26:58 +0000998FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
999 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1000 = InstantiatedFromUnnamedFieldDecl.find(Field);
1001 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1002 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001003
Anders Carlsson5da84842009-09-01 04:26:58 +00001004 return Pos->second;
1005}
1006
1007void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1008 FieldDecl *Tmpl) {
1009 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1010 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1011 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1012 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001013
Anders Carlsson5da84842009-09-01 04:26:58 +00001014 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1015}
1016
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +00001017bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
1018 const FieldDecl *LastFD) const {
1019 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001020 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +00001021}
1022
Fariborz Jahanianeb397412011-05-02 17:20:56 +00001023bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
1024 const FieldDecl *LastFD) const {
1025 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001026 FD->getBitWidthValue(*this) == 0 &&
1027 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +00001028}
1029
Fariborz Jahanian84335f72011-05-04 18:51:37 +00001030bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
1031 const FieldDecl *LastFD) const {
1032 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001033 FD->getBitWidthValue(*this) &&
1034 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +00001035}
1036
Chad Rosierf01a7dd2011-08-04 23:34:15 +00001037bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001038 const FieldDecl *LastFD) const {
1039 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001040 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001041}
1042
Chad Rosierf01a7dd2011-08-04 23:34:15 +00001043bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001044 const FieldDecl *LastFD) const {
1045 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001046 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001047}
1048
Douglas Gregor832940b2010-03-02 23:58:15 +00001049ASTContext::overridden_cxx_method_iterator
1050ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1051 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001052 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001053 if (Pos == OverriddenMethods.end())
1054 return 0;
1055
1056 return Pos->second.begin();
1057}
1058
1059ASTContext::overridden_cxx_method_iterator
1060ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1061 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001062 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001063 if (Pos == OverriddenMethods.end())
1064 return 0;
1065
1066 return Pos->second.end();
1067}
1068
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001069unsigned
1070ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1071 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001072 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001073 if (Pos == OverriddenMethods.end())
1074 return 0;
1075
1076 return Pos->second.size();
1077}
1078
Douglas Gregor832940b2010-03-02 23:58:15 +00001079void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1080 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001081 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001082 OverriddenMethods[Method].push_back(Overridden);
1083}
1084
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001085void ASTContext::getOverriddenMethods(
1086 const NamedDecl *D,
1087 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001088 assert(D);
1089
1090 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001091 Overridden.append(CXXMethod->begin_overridden_methods(),
1092 CXXMethod->end_overridden_methods());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001093 return;
1094 }
1095
1096 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1097 if (!Method)
1098 return;
1099
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001100 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1101 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001102 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001103}
1104
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001105void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1106 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1107 assert(!Import->isFromASTFile() && "Non-local import declaration");
1108 if (!FirstLocalImport) {
1109 FirstLocalImport = Import;
1110 LastLocalImport = Import;
1111 return;
1112 }
1113
1114 LastLocalImport->NextLocalImport = Import;
1115 LastLocalImport = Import;
1116}
1117
Chris Lattner53cfe802007-07-18 17:52:12 +00001118//===----------------------------------------------------------------------===//
1119// Type Sizing and Analysis
1120//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001121
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001122/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1123/// scalar floating point type.
1124const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001125 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001126 assert(BT && "Not a floating point type!");
1127 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001128 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001129 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001130 case BuiltinType::Float: return Target->getFloatFormat();
1131 case BuiltinType::Double: return Target->getDoubleFormat();
1132 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001133 }
1134}
1135
Ken Dyck160146e2010-01-27 17:10:57 +00001136/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +00001137/// specified decl. Note that bitfields do not have a valid alignment, so
1138/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001139/// If @p RefAsPointee, references are treated like their underlying type
1140/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +00001141CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001142 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001143
John McCall94268702010-10-08 18:24:19 +00001144 bool UseAlignAttrOnly = false;
1145 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1146 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001147
John McCall94268702010-10-08 18:24:19 +00001148 // __attribute__((aligned)) can increase or decrease alignment
1149 // *except* on a struct or struct member, where it only increases
1150 // alignment unless 'packed' is also specified.
1151 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001152 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001153 // ignore that possibility; Sema should diagnose it.
1154 if (isa<FieldDecl>(D)) {
1155 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1156 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1157 } else {
1158 UseAlignAttrOnly = true;
1159 }
1160 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001161 else if (isa<FieldDecl>(D))
1162 UseAlignAttrOnly =
1163 D->hasAttr<PackedAttr>() ||
1164 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001165
John McCall4e819612011-01-20 07:57:12 +00001166 // If we're using the align attribute only, just ignore everything
1167 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001168 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001169 // do nothing
1170
John McCall94268702010-10-08 18:24:19 +00001171 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001172 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001173 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001174 if (RefAsPointee)
1175 T = RT->getPointeeType();
1176 else
1177 T = getPointerType(RT->getPointeeType());
1178 }
1179 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001180 // Adjust alignments of declarations with array type by the
1181 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +00001182 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +00001183 const ArrayType *arrayType;
1184 if (MinWidth && (arrayType = getAsArrayType(T))) {
1185 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001186 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +00001187 else if (isa<ConstantArrayType>(arrayType) &&
1188 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001189 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +00001190
John McCall33ddac02011-01-19 10:06:00 +00001191 // Walk through any array types while we're at it.
1192 T = getBaseElementType(arrayType);
1193 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001194 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +00001195 }
John McCall4e819612011-01-20 07:57:12 +00001196
1197 // Fields can be subject to extra alignment constraints, like if
1198 // the field is packed, the struct is packed, or the struct has a
1199 // a max-field-alignment constraint (#pragma pack). So calculate
1200 // the actual alignment of the field within the struct, and then
1201 // (as we're expected to) constrain that by the alignment of the type.
1202 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
1203 // So calculate the alignment of the field.
1204 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
1205
1206 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +00001207 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001208
1209 // Use the GCD of that and the offset within the record.
1210 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
1211 if (offset > 0) {
1212 // Alignment is always a power of 2, so the GCD will be a power of 2,
1213 // which means we get to do this crazy thing instead of Euclid's.
1214 uint64_t lowBitOfOffset = offset & (~offset + 1);
1215 if (lowBitOfOffset < fieldAlign)
1216 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
1217 }
1218
1219 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +00001220 }
Chris Lattner68061312009-01-24 21:53:27 +00001221 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001222
Ken Dyckcc56c542011-01-15 18:38:59 +00001223 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001224}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001225
John McCallf1249922012-08-21 04:10:00 +00001226// getTypeInfoDataSizeInChars - Return the size of a type, in
1227// chars. If the type is a record, its data size is returned. This is
1228// the size of the memcpy that's performed when assigning this type
1229// using a trivial copy/move assignment operator.
1230std::pair<CharUnits, CharUnits>
1231ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1232 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1233
1234 // In C++, objects can sometimes be allocated into the tail padding
1235 // of a base-class subobject. We decide whether that's possible
1236 // during class layout, so here we can just trust the layout results.
1237 if (getLangOpts().CPlusPlus) {
1238 if (const RecordType *RT = T->getAs<RecordType>()) {
1239 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1240 sizeAndAlign.first = layout.getDataSize();
1241 }
1242 }
1243
1244 return sizeAndAlign;
1245}
1246
John McCall87fe5d52010-05-20 01:18:31 +00001247std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001248ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001249 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +00001250 return std::make_pair(toCharUnitsFromBits(Info.first),
1251 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +00001252}
1253
1254std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001255ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001256 return getTypeInfoInChars(T.getTypePtr());
1257}
1258
Daniel Dunbarc6475872012-03-09 04:12:54 +00001259std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1260 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1261 if (it != MemoizedTypeInfo.end())
1262 return it->second;
1263
1264 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1265 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1266 return Info;
1267}
1268
1269/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1270/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001271///
1272/// FIXME: Pointers into different addr spaces could have different sizes and
1273/// alignment requirements: getPointerInfo should take an AddrSpace, this
1274/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +00001275std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +00001276ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +00001277 uint64_t Width=0;
1278 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001279 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001280#define TYPE(Class, Base)
1281#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001282#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001283#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1284#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001285 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001286
Chris Lattner355332d2007-07-13 22:27:08 +00001287 case Type::FunctionNoProto:
1288 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001289 // GCC extension: alignof(function) = 32 bits
1290 Width = 0;
1291 Align = 32;
1292 break;
1293
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001294 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001295 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001296 Width = 0;
1297 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1298 break;
1299
Steve Naroff5c131802007-08-30 01:06:46 +00001300 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001301 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001302
Chris Lattner37e05872008-03-05 18:54:05 +00001303 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001304 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +00001305 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1306 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001307 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001308 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +00001309 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001310 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001311 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001312 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001313 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001314 const VectorType *VT = cast<VectorType>(T);
1315 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1316 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001317 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001318 // If the alignment is not a power of 2, round up to the next power of 2.
1319 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001320 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001321 Align = llvm::NextPowerOf2(Align);
1322 Width = llvm::RoundUpToAlignment(Width, Align);
1323 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001324 // Adjust the alignment based on the target max.
1325 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1326 if (TargetVectorAlign && TargetVectorAlign < Align)
1327 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001328 break;
1329 }
Chris Lattner647fb222007-07-18 18:26:58 +00001330
Chris Lattner7570e9c2008-03-08 08:52:55 +00001331 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001332 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001333 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001334 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001335 // GCC extension: alignof(void) = 8 bits.
1336 Width = 0;
1337 Align = 8;
1338 break;
1339
Chris Lattner6a4f7452007-12-19 19:23:28 +00001340 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001341 Width = Target->getBoolWidth();
1342 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001343 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001344 case BuiltinType::Char_S:
1345 case BuiltinType::Char_U:
1346 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001347 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001348 Width = Target->getCharWidth();
1349 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001350 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001351 case BuiltinType::WChar_S:
1352 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001353 Width = Target->getWCharWidth();
1354 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001355 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001356 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001357 Width = Target->getChar16Width();
1358 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001359 break;
1360 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001361 Width = Target->getChar32Width();
1362 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001363 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001364 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001365 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001366 Width = Target->getShortWidth();
1367 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001368 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001369 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001370 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001371 Width = Target->getIntWidth();
1372 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001373 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001374 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001375 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001376 Width = Target->getLongWidth();
1377 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001378 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001379 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001380 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001381 Width = Target->getLongLongWidth();
1382 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001383 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001384 case BuiltinType::Int128:
1385 case BuiltinType::UInt128:
1386 Width = 128;
1387 Align = 128; // int128_t is 128-bit aligned on all targets.
1388 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001389 case BuiltinType::Half:
1390 Width = Target->getHalfWidth();
1391 Align = Target->getHalfAlign();
1392 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001393 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001394 Width = Target->getFloatWidth();
1395 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001396 break;
1397 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001398 Width = Target->getDoubleWidth();
1399 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001400 break;
1401 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001402 Width = Target->getLongDoubleWidth();
1403 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001404 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001405 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001406 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1407 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001408 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001409 case BuiltinType::ObjCId:
1410 case BuiltinType::ObjCClass:
1411 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001412 Width = Target->getPointerWidth(0);
1413 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001414 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001415 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001416 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001417 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001418 Width = Target->getPointerWidth(0);
1419 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001420 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001421 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001422 unsigned AS = getTargetAddressSpace(
1423 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001424 Width = Target->getPointerWidth(AS);
1425 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001426 break;
1427 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001428 case Type::LValueReference:
1429 case Type::RValueReference: {
1430 // alignof and sizeof should never enter this code path here, so we go
1431 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001432 unsigned AS = getTargetAddressSpace(
1433 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001434 Width = Target->getPointerWidth(AS);
1435 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001436 break;
1437 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001438 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001439 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001440 Width = Target->getPointerWidth(AS);
1441 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001442 break;
1443 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001444 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001445 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001446 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +00001447 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +00001448 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001449 Align = PtrDiffInfo.second;
1450 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001451 }
Chris Lattner647fb222007-07-18 18:26:58 +00001452 case Type::Complex: {
1453 // Complex types have the same alignment as their elements, but twice the
1454 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001455 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001456 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001457 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001458 Align = EltInfo.second;
1459 break;
1460 }
John McCall8b07ec22010-05-15 11:32:37 +00001461 case Type::ObjCObject:
1462 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001463 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001464 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001465 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001466 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001467 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001468 break;
1469 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001470 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001471 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001472 const TagType *TT = cast<TagType>(T);
1473
1474 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001475 Width = 8;
1476 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001477 break;
1478 }
Mike Stump11289f42009-09-09 15:08:12 +00001479
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001480 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001481 return getTypeInfo(ET->getDecl()->getIntegerType());
1482
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001483 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001484 const ASTRecordLayout &Layout = getASTRecordLayout(RT->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());
Chris Lattner49a953a2007-07-23 22:46:22 +00001487 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001488 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001489
Chris Lattner63d2b362009-10-22 05:17:15 +00001490 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001491 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1492 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001493
Richard Smith30482bc2011-02-20 03:19:35 +00001494 case Type::Auto: {
1495 const AutoType *A = cast<AutoType>(T);
1496 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001497 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001498 }
1499
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001500 case Type::Paren:
1501 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1502
Douglas Gregoref462e62009-04-30 17:32:17 +00001503 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001504 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001505 std::pair<uint64_t, unsigned> Info
1506 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001507 // If the typedef has an aligned attribute on it, it overrides any computed
1508 // alignment we have. This violates the GCC documentation (which says that
1509 // attribute(aligned) can only round up) but matches its implementation.
1510 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1511 Align = AttrAlign;
1512 else
1513 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001514 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001515 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001516 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001517
1518 case Type::TypeOfExpr:
1519 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1520 .getTypePtr());
1521
1522 case Type::TypeOf:
1523 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1524
Anders Carlsson81df7b82009-06-24 19:06:50 +00001525 case Type::Decltype:
1526 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1527 .getTypePtr());
1528
Alexis Hunte852b102011-05-24 22:41:36 +00001529 case Type::UnaryTransform:
1530 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1531
Abramo Bagnara6150c882010-05-11 21:36:43 +00001532 case Type::Elaborated:
1533 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001534
John McCall81904512011-01-06 01:58:22 +00001535 case Type::Attributed:
1536 return getTypeInfo(
1537 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1538
Richard Smith3f1b5d02011-05-05 21:57:07 +00001539 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001540 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001541 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001542 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1543 // A type alias template specialization may refer to a typedef with the
1544 // aligned attribute on it.
1545 if (TST->isTypeAlias())
1546 return getTypeInfo(TST->getAliasedType().getTypePtr());
1547 else
1548 return getTypeInfo(getCanonicalType(T));
1549 }
1550
Eli Friedman0dfb8892011-10-06 23:00:33 +00001551 case Type::Atomic: {
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001552 std::pair<uint64_t, unsigned> Info
1553 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1554 Width = Info.first;
1555 Align = Info.second;
1556 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1557 llvm::isPowerOf2_64(Width)) {
1558 // We can potentially perform lock-free atomic operations for this
1559 // type; promote the alignment appropriately.
1560 // FIXME: We could potentially promote the width here as well...
1561 // is that worthwhile? (Non-struct atomic types generally have
1562 // power-of-two size anyway, but structs might not. Requires a bit
1563 // of implementation work to make sure we zero out the extra bits.)
1564 Align = static_cast<unsigned>(Width);
1565 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001566 }
1567
Douglas Gregoref462e62009-04-30 17:32:17 +00001568 }
Mike Stump11289f42009-09-09 15:08:12 +00001569
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001570 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001571 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001572}
1573
Ken Dyckcc56c542011-01-15 18:38:59 +00001574/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1575CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1576 return CharUnits::fromQuantity(BitSize / getCharWidth());
1577}
1578
Ken Dyckb0fcc592011-02-11 01:54:29 +00001579/// toBits - Convert a size in characters to a size in characters.
1580int64_t ASTContext::toBits(CharUnits CharSize) const {
1581 return CharSize.getQuantity() * getCharWidth();
1582}
1583
Ken Dyck8c89d592009-12-22 14:23:30 +00001584/// getTypeSizeInChars - Return the size of the specified type, in characters.
1585/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001586CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001587 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001588}
Jay Foad39c79802011-01-12 09:06:06 +00001589CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001590 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001591}
1592
Ken Dycka6046ab2010-01-26 17:25:18 +00001593/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001594/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001595CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001596 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001597}
Jay Foad39c79802011-01-12 09:06:06 +00001598CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001599 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001600}
1601
Chris Lattnera3402cd2009-01-27 18:08:34 +00001602/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1603/// type for the current target in bits. This can be different than the ABI
1604/// alignment in cases where it is beneficial for performance to overalign
1605/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001606unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001607 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001608
1609 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001610 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001611 T = CT->getElementType().getTypePtr();
1612 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001613 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1614 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001615 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1616
Chris Lattnera3402cd2009-01-27 18:08:34 +00001617 return ABIAlign;
1618}
1619
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001620/// DeepCollectObjCIvars -
1621/// This routine first collects all declared, but not synthesized, ivars in
1622/// super class and then collects all ivars, including those synthesized for
1623/// current class. This routine is used for implementation of current class
1624/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001625///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001626void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1627 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001628 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001629 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1630 DeepCollectObjCIvars(SuperClass, false, Ivars);
1631 if (!leafClass) {
1632 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1633 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001634 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001635 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001636 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001637 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001638 Iv= Iv->getNextIvar())
1639 Ivars.push_back(Iv);
1640 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001641}
1642
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001643/// CollectInheritedProtocols - Collect all protocols in current class and
1644/// those inherited by it.
1645void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001646 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001647 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001648 // We can use protocol_iterator here instead of
1649 // all_referenced_protocol_iterator since we are walking all categories.
1650 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1651 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001652 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001653 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001654 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001655 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001656 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001657 CollectInheritedProtocols(*P, Protocols);
1658 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001659 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001660
1661 // Categories of this Interface.
1662 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1663 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1664 CollectInheritedProtocols(CDeclChain, Protocols);
1665 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1666 while (SD) {
1667 CollectInheritedProtocols(SD, Protocols);
1668 SD = SD->getSuperClass();
1669 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001670 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001671 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001672 PE = OC->protocol_end(); P != PE; ++P) {
1673 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001674 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001675 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1676 PE = Proto->protocol_end(); P != PE; ++P)
1677 CollectInheritedProtocols(*P, Protocols);
1678 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001679 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001680 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1681 PE = OP->protocol_end(); P != PE; ++P) {
1682 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001683 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001684 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1685 PE = Proto->protocol_end(); P != PE; ++P)
1686 CollectInheritedProtocols(*P, Protocols);
1687 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001688 }
1689}
1690
Jay Foad39c79802011-01-12 09:06:06 +00001691unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001692 unsigned count = 0;
1693 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001694 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1695 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001696 count += CDecl->ivar_size();
1697
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001698 // Count ivar defined in this class's implementation. This
1699 // includes synthesized ivars.
1700 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001701 count += ImplDecl->ivar_size();
1702
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001703 return count;
1704}
1705
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001706bool ASTContext::isSentinelNullExpr(const Expr *E) {
1707 if (!E)
1708 return false;
1709
1710 // nullptr_t is always treated as null.
1711 if (E->getType()->isNullPtrType()) return true;
1712
1713 if (E->getType()->isAnyPointerType() &&
1714 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1715 Expr::NPC_ValueDependentIsNull))
1716 return true;
1717
1718 // Unfortunately, __null has type 'int'.
1719 if (isa<GNUNullExpr>(E)) return true;
1720
1721 return false;
1722}
1723
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001724/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1725ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1726 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1727 I = ObjCImpls.find(D);
1728 if (I != ObjCImpls.end())
1729 return cast<ObjCImplementationDecl>(I->second);
1730 return 0;
1731}
1732/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1733ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1734 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1735 I = ObjCImpls.find(D);
1736 if (I != ObjCImpls.end())
1737 return cast<ObjCCategoryImplDecl>(I->second);
1738 return 0;
1739}
1740
1741/// \brief Set the implementation of ObjCInterfaceDecl.
1742void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1743 ObjCImplementationDecl *ImplD) {
1744 assert(IFaceD && ImplD && "Passed null params");
1745 ObjCImpls[IFaceD] = ImplD;
1746}
1747/// \brief Set the implementation of ObjCCategoryDecl.
1748void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1749 ObjCCategoryImplDecl *ImplD) {
1750 assert(CatD && ImplD && "Passed null params");
1751 ObjCImpls[CatD] = ImplD;
1752}
1753
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001754ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1755 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1756 return ID;
1757 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1758 return CD->getClassInterface();
1759 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1760 return IMD->getClassInterface();
1761
1762 return 0;
1763}
1764
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001765/// \brief Get the copy initialization expression of VarDecl,or NULL if
1766/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001767Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001768 assert(VD && "Passed null params");
1769 assert(VD->hasAttr<BlocksAttr>() &&
1770 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001771 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001772 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001773 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1774}
1775
1776/// \brief Set the copy inialization expression of a block var decl.
1777void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1778 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001779 assert(VD->hasAttr<BlocksAttr>() &&
1780 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001781 BlockVarCopyInits[VD] = Init;
1782}
1783
John McCallbcd03502009-12-07 02:54:59 +00001784TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001785 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001786 if (!DataSize)
1787 DataSize = TypeLoc::getFullDataSizeForType(T);
1788 else
1789 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001790 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001791
John McCallbcd03502009-12-07 02:54:59 +00001792 TypeSourceInfo *TInfo =
1793 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1794 new (TInfo) TypeSourceInfo(T);
1795 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001796}
1797
John McCallbcd03502009-12-07 02:54:59 +00001798TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001799 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001800 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001801 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001802 return DI;
1803}
1804
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001805const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001806ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001807 return getObjCLayout(D, 0);
1808}
1809
1810const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001811ASTContext::getASTObjCImplementationLayout(
1812 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001813 return getObjCLayout(D->getClassInterface(), D);
1814}
1815
Chris Lattner983a8bb2007-07-13 22:13:22 +00001816//===----------------------------------------------------------------------===//
1817// Type creation/memoization methods
1818//===----------------------------------------------------------------------===//
1819
Jay Foad39c79802011-01-12 09:06:06 +00001820QualType
John McCall33ddac02011-01-19 10:06:00 +00001821ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1822 unsigned fastQuals = quals.getFastQualifiers();
1823 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001824
1825 // Check if we've already instantiated this type.
1826 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001827 ExtQuals::Profile(ID, baseType, quals);
1828 void *insertPos = 0;
1829 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1830 assert(eq->getQualifiers() == quals);
1831 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001832 }
1833
John McCall33ddac02011-01-19 10:06:00 +00001834 // If the base type is not canonical, make the appropriate canonical type.
1835 QualType canon;
1836 if (!baseType->isCanonicalUnqualified()) {
1837 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00001838 canonSplit.Quals.addConsistentQualifiers(quals);
1839 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001840
1841 // Re-find the insert position.
1842 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1843 }
1844
1845 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1846 ExtQualNodes.InsertNode(eq, insertPos);
1847 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001848}
1849
Jay Foad39c79802011-01-12 09:06:06 +00001850QualType
1851ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001852 QualType CanT = getCanonicalType(T);
1853 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001854 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001855
John McCall8ccfcb52009-09-24 19:53:00 +00001856 // If we are composing extended qualifiers together, merge together
1857 // into one ExtQuals node.
1858 QualifierCollector Quals;
1859 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001860
John McCall8ccfcb52009-09-24 19:53:00 +00001861 // If this type already has an address space specified, it cannot get
1862 // another one.
1863 assert(!Quals.hasAddressSpace() &&
1864 "Type cannot be in multiple addr spaces!");
1865 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001866
John McCall8ccfcb52009-09-24 19:53:00 +00001867 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001868}
1869
Chris Lattnerd60183d2009-02-18 22:53:11 +00001870QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001871 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001872 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001873 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001874 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001875
John McCall53fa7142010-12-24 02:08:15 +00001876 if (const PointerType *ptr = T->getAs<PointerType>()) {
1877 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001878 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001879 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1880 return getPointerType(ResultType);
1881 }
1882 }
Mike Stump11289f42009-09-09 15:08:12 +00001883
John McCall8ccfcb52009-09-24 19:53:00 +00001884 // If we are composing extended qualifiers together, merge together
1885 // into one ExtQuals node.
1886 QualifierCollector Quals;
1887 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001888
John McCall8ccfcb52009-09-24 19:53:00 +00001889 // If this type already has an ObjCGC specified, it cannot get
1890 // another one.
1891 assert(!Quals.hasObjCGCAttr() &&
1892 "Type cannot have multiple ObjCGCs!");
1893 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001894
John McCall8ccfcb52009-09-24 19:53:00 +00001895 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001896}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001897
John McCall4f5019e2010-12-19 02:44:49 +00001898const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1899 FunctionType::ExtInfo Info) {
1900 if (T->getExtInfo() == Info)
1901 return T;
1902
1903 QualType Result;
1904 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1905 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1906 } else {
1907 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1908 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1909 EPI.ExtInfo = Info;
1910 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1911 FPT->getNumArgs(), EPI);
1912 }
1913
1914 return cast<FunctionType>(Result.getTypePtr());
1915}
1916
Chris Lattnerc6395932007-06-22 20:56:16 +00001917/// getComplexType - Return the uniqued reference to the type for a complex
1918/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001919QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001920 // Unique pointers, to guarantee there is only one pointer of a particular
1921 // structure.
1922 llvm::FoldingSetNodeID ID;
1923 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001924
Chris Lattnerc6395932007-06-22 20:56:16 +00001925 void *InsertPos = 0;
1926 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1927 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001928
Chris Lattnerc6395932007-06-22 20:56:16 +00001929 // If the pointee type isn't canonical, this won't be a canonical type either,
1930 // so fill in the canonical type field.
1931 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001932 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001933 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001934
Chris Lattnerc6395932007-06-22 20:56:16 +00001935 // Get the new insert position for the node we care about.
1936 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001937 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001938 }
John McCall90d1c2d2009-09-24 23:30:46 +00001939 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001940 Types.push_back(New);
1941 ComplexTypes.InsertNode(New, InsertPos);
1942 return QualType(New, 0);
1943}
1944
Chris Lattner970e54e2006-11-12 00:37:36 +00001945/// getPointerType - Return the uniqued reference to the type for a pointer to
1946/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001947QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001948 // Unique pointers, to guarantee there is only one pointer of a particular
1949 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001950 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001951 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001952
Chris Lattner67521df2007-01-27 01:29:36 +00001953 void *InsertPos = 0;
1954 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001955 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001956
Chris Lattner7ccecb92006-11-12 08:50:50 +00001957 // If the pointee type isn't canonical, this won't be a canonical type either,
1958 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001959 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001960 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001961 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001962
Chris Lattner67521df2007-01-27 01:29:36 +00001963 // Get the new insert position for the node we care about.
1964 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001965 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001966 }
John McCall90d1c2d2009-09-24 23:30:46 +00001967 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001968 Types.push_back(New);
1969 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001970 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001971}
1972
Mike Stump11289f42009-09-09 15:08:12 +00001973/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001974/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001975QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001976 assert(T->isFunctionType() && "block of function types only");
1977 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001978 // structure.
1979 llvm::FoldingSetNodeID ID;
1980 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001981
Steve Naroffec33ed92008-08-27 16:04:49 +00001982 void *InsertPos = 0;
1983 if (BlockPointerType *PT =
1984 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1985 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001986
1987 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001988 // type either so fill in the canonical type field.
1989 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001990 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001991 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001992
Steve Naroffec33ed92008-08-27 16:04:49 +00001993 // Get the new insert position for the node we care about.
1994 BlockPointerType *NewIP =
1995 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001996 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001997 }
John McCall90d1c2d2009-09-24 23:30:46 +00001998 BlockPointerType *New
1999 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002000 Types.push_back(New);
2001 BlockPointerTypes.InsertNode(New, InsertPos);
2002 return QualType(New, 0);
2003}
2004
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002005/// getLValueReferenceType - Return the uniqued reference to the type for an
2006/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002007QualType
2008ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002009 assert(getCanonicalType(T) != OverloadTy &&
2010 "Unresolved overloaded function type");
2011
Bill Wendling3708c182007-05-27 10:15:43 +00002012 // Unique pointers, to guarantee there is only one pointer of a particular
2013 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002014 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002015 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002016
2017 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002018 if (LValueReferenceType *RT =
2019 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002020 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002021
John McCallfc93cf92009-10-22 22:37:11 +00002022 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2023
Bill Wendling3708c182007-05-27 10:15:43 +00002024 // If the referencee type isn't canonical, this won't be a canonical type
2025 // either, so fill in the canonical type field.
2026 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002027 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2028 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2029 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002030
Bill Wendling3708c182007-05-27 10:15:43 +00002031 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002032 LValueReferenceType *NewIP =
2033 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002034 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002035 }
2036
John McCall90d1c2d2009-09-24 23:30:46 +00002037 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002038 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2039 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002040 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002041 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002042
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002043 return QualType(New, 0);
2044}
2045
2046/// getRValueReferenceType - Return the uniqued reference to the type for an
2047/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002048QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002049 // Unique pointers, to guarantee there is only one pointer of a particular
2050 // structure.
2051 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002052 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002053
2054 void *InsertPos = 0;
2055 if (RValueReferenceType *RT =
2056 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2057 return QualType(RT, 0);
2058
John McCallfc93cf92009-10-22 22:37:11 +00002059 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2060
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002061 // If the referencee type isn't canonical, this won't be a canonical type
2062 // either, so fill in the canonical type field.
2063 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002064 if (InnerRef || !T.isCanonical()) {
2065 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2066 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002067
2068 // Get the new insert position for the node we care about.
2069 RValueReferenceType *NewIP =
2070 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002071 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002072 }
2073
John McCall90d1c2d2009-09-24 23:30:46 +00002074 RValueReferenceType *New
2075 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002076 Types.push_back(New);
2077 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002078 return QualType(New, 0);
2079}
2080
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002081/// getMemberPointerType - Return the uniqued reference to the type for a
2082/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002083QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002084 // Unique pointers, to guarantee there is only one pointer of a particular
2085 // structure.
2086 llvm::FoldingSetNodeID ID;
2087 MemberPointerType::Profile(ID, T, Cls);
2088
2089 void *InsertPos = 0;
2090 if (MemberPointerType *PT =
2091 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2092 return QualType(PT, 0);
2093
2094 // If the pointee or class type isn't canonical, this won't be a canonical
2095 // type either, so fill in the canonical type field.
2096 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002097 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002098 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2099
2100 // Get the new insert position for the node we care about.
2101 MemberPointerType *NewIP =
2102 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002103 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002104 }
John McCall90d1c2d2009-09-24 23:30:46 +00002105 MemberPointerType *New
2106 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002107 Types.push_back(New);
2108 MemberPointerTypes.InsertNode(New, InsertPos);
2109 return QualType(New, 0);
2110}
2111
Mike Stump11289f42009-09-09 15:08:12 +00002112/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002113/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002114QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002115 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002116 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002117 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002118 assert((EltTy->isDependentType() ||
2119 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002120 "Constant array of VLAs is illegal!");
2121
Chris Lattnere2df3f92009-05-13 04:12:56 +00002122 // Convert the array size into a canonical width matching the pointer size for
2123 // the target.
2124 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002125 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002126 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002127
Chris Lattner23b7eb62007-06-15 23:05:46 +00002128 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002129 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002130
Chris Lattner36f8e652007-01-27 08:31:04 +00002131 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002132 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002133 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002134 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002135
John McCall33ddac02011-01-19 10:06:00 +00002136 // If the element type isn't canonical or has qualifiers, this won't
2137 // be a canonical type either, so fill in the canonical type field.
2138 QualType Canon;
2139 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2140 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002141 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002142 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002143 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002144
Chris Lattner36f8e652007-01-27 08:31:04 +00002145 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002146 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002147 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002148 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002149 }
Mike Stump11289f42009-09-09 15:08:12 +00002150
John McCall90d1c2d2009-09-24 23:30:46 +00002151 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002152 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002153 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002154 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002155 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002156}
2157
John McCall06549462011-01-18 08:40:38 +00002158/// getVariableArrayDecayedType - Turns the given type, which may be
2159/// variably-modified, into the corresponding type with all the known
2160/// sizes replaced with [*].
2161QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2162 // Vastly most common case.
2163 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002164
John McCall06549462011-01-18 08:40:38 +00002165 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002166
John McCall06549462011-01-18 08:40:38 +00002167 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002168 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002169 switch (ty->getTypeClass()) {
2170#define TYPE(Class, Base)
2171#define ABSTRACT_TYPE(Class, Base)
2172#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2173#include "clang/AST/TypeNodes.def"
2174 llvm_unreachable("didn't desugar past all non-canonical types?");
2175
2176 // These types should never be variably-modified.
2177 case Type::Builtin:
2178 case Type::Complex:
2179 case Type::Vector:
2180 case Type::ExtVector:
2181 case Type::DependentSizedExtVector:
2182 case Type::ObjCObject:
2183 case Type::ObjCInterface:
2184 case Type::ObjCObjectPointer:
2185 case Type::Record:
2186 case Type::Enum:
2187 case Type::UnresolvedUsing:
2188 case Type::TypeOfExpr:
2189 case Type::TypeOf:
2190 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002191 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002192 case Type::DependentName:
2193 case Type::InjectedClassName:
2194 case Type::TemplateSpecialization:
2195 case Type::DependentTemplateSpecialization:
2196 case Type::TemplateTypeParm:
2197 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002198 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002199 case Type::PackExpansion:
2200 llvm_unreachable("type should never be variably-modified");
2201
2202 // These types can be variably-modified but should never need to
2203 // further decay.
2204 case Type::FunctionNoProto:
2205 case Type::FunctionProto:
2206 case Type::BlockPointer:
2207 case Type::MemberPointer:
2208 return type;
2209
2210 // These types can be variably-modified. All these modifications
2211 // preserve structure except as noted by comments.
2212 // TODO: if we ever care about optimizing VLAs, there are no-op
2213 // optimizations available here.
2214 case Type::Pointer:
2215 result = getPointerType(getVariableArrayDecayedType(
2216 cast<PointerType>(ty)->getPointeeType()));
2217 break;
2218
2219 case Type::LValueReference: {
2220 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2221 result = getLValueReferenceType(
2222 getVariableArrayDecayedType(lv->getPointeeType()),
2223 lv->isSpelledAsLValue());
2224 break;
2225 }
2226
2227 case Type::RValueReference: {
2228 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2229 result = getRValueReferenceType(
2230 getVariableArrayDecayedType(lv->getPointeeType()));
2231 break;
2232 }
2233
Eli Friedman0dfb8892011-10-06 23:00:33 +00002234 case Type::Atomic: {
2235 const AtomicType *at = cast<AtomicType>(ty);
2236 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2237 break;
2238 }
2239
John McCall06549462011-01-18 08:40:38 +00002240 case Type::ConstantArray: {
2241 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2242 result = getConstantArrayType(
2243 getVariableArrayDecayedType(cat->getElementType()),
2244 cat->getSize(),
2245 cat->getSizeModifier(),
2246 cat->getIndexTypeCVRQualifiers());
2247 break;
2248 }
2249
2250 case Type::DependentSizedArray: {
2251 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2252 result = getDependentSizedArrayType(
2253 getVariableArrayDecayedType(dat->getElementType()),
2254 dat->getSizeExpr(),
2255 dat->getSizeModifier(),
2256 dat->getIndexTypeCVRQualifiers(),
2257 dat->getBracketsRange());
2258 break;
2259 }
2260
2261 // Turn incomplete types into [*] types.
2262 case Type::IncompleteArray: {
2263 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2264 result = getVariableArrayType(
2265 getVariableArrayDecayedType(iat->getElementType()),
2266 /*size*/ 0,
2267 ArrayType::Normal,
2268 iat->getIndexTypeCVRQualifiers(),
2269 SourceRange());
2270 break;
2271 }
2272
2273 // Turn VLA types into [*] types.
2274 case Type::VariableArray: {
2275 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2276 result = getVariableArrayType(
2277 getVariableArrayDecayedType(vat->getElementType()),
2278 /*size*/ 0,
2279 ArrayType::Star,
2280 vat->getIndexTypeCVRQualifiers(),
2281 vat->getBracketsRange());
2282 break;
2283 }
2284 }
2285
2286 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002287 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002288}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002289
Steve Naroffcadebd02007-08-30 18:14:25 +00002290/// getVariableArrayType - Returns a non-unique reference to the type for a
2291/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002292QualType ASTContext::getVariableArrayType(QualType EltTy,
2293 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002294 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002295 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002296 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002297 // Since we don't unique expressions, it isn't possible to unique VLA's
2298 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002299 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002300
John McCall33ddac02011-01-19 10:06:00 +00002301 // Be sure to pull qualifiers off the element type.
2302 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2303 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002304 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002305 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002306 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002307 }
2308
John McCall90d1c2d2009-09-24 23:30:46 +00002309 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002310 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002311
2312 VariableArrayTypes.push_back(New);
2313 Types.push_back(New);
2314 return QualType(New, 0);
2315}
2316
Douglas Gregor4619e432008-12-05 23:32:09 +00002317/// getDependentSizedArrayType - Returns a non-unique reference to
2318/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002319/// type.
John McCall33ddac02011-01-19 10:06:00 +00002320QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2321 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002322 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002323 unsigned elementTypeQuals,
2324 SourceRange brackets) const {
2325 assert((!numElements || numElements->isTypeDependent() ||
2326 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002327 "Size must be type- or value-dependent!");
2328
John McCall33ddac02011-01-19 10:06:00 +00002329 // Dependently-sized array types that do not have a specified number
2330 // of elements will have their sizes deduced from a dependent
2331 // initializer. We do no canonicalization here at all, which is okay
2332 // because they can't be used in most locations.
2333 if (!numElements) {
2334 DependentSizedArrayType *newType
2335 = new (*this, TypeAlignment)
2336 DependentSizedArrayType(*this, elementType, QualType(),
2337 numElements, ASM, elementTypeQuals,
2338 brackets);
2339 Types.push_back(newType);
2340 return QualType(newType, 0);
2341 }
2342
2343 // Otherwise, we actually build a new type every time, but we
2344 // also build a canonical type.
2345
2346 SplitQualType canonElementType = getCanonicalType(elementType).split();
2347
2348 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002349 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002350 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002351 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002352 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002353
John McCall33ddac02011-01-19 10:06:00 +00002354 // Look for an existing type with these properties.
2355 DependentSizedArrayType *canonTy =
2356 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002357
John McCall33ddac02011-01-19 10:06:00 +00002358 // If we don't have one, build one.
2359 if (!canonTy) {
2360 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002361 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002362 QualType(), numElements, ASM, elementTypeQuals,
2363 brackets);
2364 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2365 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002366 }
2367
John McCall33ddac02011-01-19 10:06:00 +00002368 // Apply qualifiers from the element type to the array.
2369 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002370 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002371
John McCall33ddac02011-01-19 10:06:00 +00002372 // If we didn't need extra canonicalization for the element type,
2373 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002374 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002375 return canon;
2376
2377 // Otherwise, we need to build a type which follows the spelling
2378 // of the element type.
2379 DependentSizedArrayType *sugaredType
2380 = new (*this, TypeAlignment)
2381 DependentSizedArrayType(*this, elementType, canon, numElements,
2382 ASM, elementTypeQuals, brackets);
2383 Types.push_back(sugaredType);
2384 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002385}
2386
John McCall33ddac02011-01-19 10:06:00 +00002387QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002388 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002389 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002390 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002391 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002392
John McCall33ddac02011-01-19 10:06:00 +00002393 void *insertPos = 0;
2394 if (IncompleteArrayType *iat =
2395 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2396 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002397
2398 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002399 // either, so fill in the canonical type field. We also have to pull
2400 // qualifiers off the element type.
2401 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002402
John McCall33ddac02011-01-19 10:06:00 +00002403 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2404 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002405 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002406 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002407 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002408
2409 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002410 IncompleteArrayType *existing =
2411 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2412 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002413 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002414
John McCall33ddac02011-01-19 10:06:00 +00002415 IncompleteArrayType *newType = new (*this, TypeAlignment)
2416 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002417
John McCall33ddac02011-01-19 10:06:00 +00002418 IncompleteArrayTypes.InsertNode(newType, insertPos);
2419 Types.push_back(newType);
2420 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002421}
2422
Steve Naroff91fcddb2007-07-18 18:00:27 +00002423/// getVectorType - Return the unique reference to a vector type of
2424/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002425QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002426 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002427 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002428
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002429 // Check if we've already instantiated a vector of this type.
2430 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002431 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002432
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002433 void *InsertPos = 0;
2434 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2435 return QualType(VTP, 0);
2436
2437 // If the element type isn't canonical, this won't be a canonical type either,
2438 // so fill in the canonical type field.
2439 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002440 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002441 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002442
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002443 // Get the new insert position for the node we care about.
2444 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002445 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002446 }
John McCall90d1c2d2009-09-24 23:30:46 +00002447 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002448 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002449 VectorTypes.InsertNode(New, InsertPos);
2450 Types.push_back(New);
2451 return QualType(New, 0);
2452}
2453
Nate Begemance4d7fc2008-04-18 23:10:10 +00002454/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002455/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002456QualType
2457ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002458 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002459
Steve Naroff91fcddb2007-07-18 18:00:27 +00002460 // Check if we've already instantiated a vector of this type.
2461 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002462 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002463 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002464 void *InsertPos = 0;
2465 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2466 return QualType(VTP, 0);
2467
2468 // If the element type isn't canonical, this won't be a canonical type either,
2469 // so fill in the canonical type field.
2470 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002471 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002472 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002473
Steve Naroff91fcddb2007-07-18 18:00:27 +00002474 // Get the new insert position for the node we care about.
2475 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002476 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002477 }
John McCall90d1c2d2009-09-24 23:30:46 +00002478 ExtVectorType *New = new (*this, TypeAlignment)
2479 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002480 VectorTypes.InsertNode(New, InsertPos);
2481 Types.push_back(New);
2482 return QualType(New, 0);
2483}
2484
Jay Foad39c79802011-01-12 09:06:06 +00002485QualType
2486ASTContext::getDependentSizedExtVectorType(QualType vecType,
2487 Expr *SizeExpr,
2488 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002489 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002490 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002491 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002492
Douglas Gregor352169a2009-07-31 03:54:25 +00002493 void *InsertPos = 0;
2494 DependentSizedExtVectorType *Canon
2495 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2496 DependentSizedExtVectorType *New;
2497 if (Canon) {
2498 // We already have a canonical version of this array type; use it as
2499 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002500 New = new (*this, TypeAlignment)
2501 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2502 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002503 } else {
2504 QualType CanonVecTy = getCanonicalType(vecType);
2505 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002506 New = new (*this, TypeAlignment)
2507 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2508 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002509
2510 DependentSizedExtVectorType *CanonCheck
2511 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2512 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2513 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002514 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2515 } else {
2516 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2517 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002518 New = new (*this, TypeAlignment)
2519 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002520 }
2521 }
Mike Stump11289f42009-09-09 15:08:12 +00002522
Douglas Gregor758a8692009-06-17 21:51:59 +00002523 Types.push_back(New);
2524 return QualType(New, 0);
2525}
2526
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002527/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002528///
Jay Foad39c79802011-01-12 09:06:06 +00002529QualType
2530ASTContext::getFunctionNoProtoType(QualType ResultTy,
2531 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002532 const CallingConv DefaultCC = Info.getCC();
2533 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2534 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002535 // Unique functions, to guarantee there is only one function of a particular
2536 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002537 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002538 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002539
Chris Lattner47955de2007-01-27 08:37:20 +00002540 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002541 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002542 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002543 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002544
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002545 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002546 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002547 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002548 Canonical =
2549 getFunctionNoProtoType(getCanonicalType(ResultTy),
2550 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002551
Chris Lattner47955de2007-01-27 08:37:20 +00002552 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002553 FunctionNoProtoType *NewIP =
2554 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002555 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002556 }
Mike Stump11289f42009-09-09 15:08:12 +00002557
Roman Divacky65b88cd2011-03-01 17:40:53 +00002558 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002559 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002560 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002561 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002562 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002563 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002564}
2565
2566/// getFunctionType - Return a normal function type with a typed argument
2567/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002568QualType
2569ASTContext::getFunctionType(QualType ResultTy,
2570 const QualType *ArgArray, unsigned NumArgs,
2571 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002572 // Unique functions, to guarantee there is only one function of a particular
2573 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002574 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002575 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002576
2577 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002578 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002579 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002580 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002581
2582 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002583 bool isCanonical =
2584 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2585 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002586 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002587 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002588 isCanonical = false;
2589
Roman Divacky65b88cd2011-03-01 17:40:53 +00002590 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2591 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2592 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002593
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002594 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002595 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002596 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002597 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002598 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002599 CanonicalArgs.reserve(NumArgs);
2600 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002601 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002602
John McCalldb40c7f2010-12-14 08:05:40 +00002603 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002604 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002605 CanonicalEPI.ExceptionSpecType = EST_None;
2606 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002607 CanonicalEPI.ExtInfo
2608 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2609
Chris Lattner76a00cf2008-04-06 22:59:24 +00002610 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002611 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002612 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002613
Chris Lattnerfd4de792007-01-27 01:15:32 +00002614 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002615 FunctionProtoType *NewIP =
2616 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002617 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002618 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002619
John McCall31168b02011-06-15 23:02:42 +00002620 // FunctionProtoType objects are allocated with extra bytes after
2621 // them for three variable size arrays at the end:
2622 // - parameter types
2623 // - exception types
2624 // - consumed-arguments flags
2625 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002626 // expression, or information used to resolve the exception
2627 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002628 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002629 NumArgs * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002630 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002631 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002632 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002633 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002634 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002635 Size += 2 * sizeof(FunctionDecl*);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002636 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2637 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002638 }
John McCall31168b02011-06-15 23:02:42 +00002639 if (EPI.ConsumedArguments)
2640 Size += NumArgs * sizeof(bool);
2641
John McCalldb40c7f2010-12-14 08:05:40 +00002642 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002643 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2644 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002645 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002646 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002647 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002648 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002649}
Chris Lattneref51c202006-11-10 07:17:23 +00002650
John McCalle78aac42010-03-10 03:28:59 +00002651#ifndef NDEBUG
2652static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2653 if (!isa<CXXRecordDecl>(D)) return false;
2654 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2655 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2656 return true;
2657 if (RD->getDescribedClassTemplate() &&
2658 !isa<ClassTemplateSpecializationDecl>(RD))
2659 return true;
2660 return false;
2661}
2662#endif
2663
2664/// getInjectedClassNameType - Return the unique reference to the
2665/// injected class name type for the specified templated declaration.
2666QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002667 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002668 assert(NeedsInjectedClassNameType(Decl));
2669 if (Decl->TypeForDecl) {
2670 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002671 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002672 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2673 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2674 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2675 } else {
John McCall424cec92011-01-19 06:33:43 +00002676 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002677 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002678 Decl->TypeForDecl = newType;
2679 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002680 }
2681 return QualType(Decl->TypeForDecl, 0);
2682}
2683
Douglas Gregor83a586e2008-04-13 21:07:44 +00002684/// getTypeDeclType - Return the unique reference to the type for the
2685/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002686QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002687 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002688 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002689
Richard Smithdda56e42011-04-15 14:24:37 +00002690 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002691 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002692
John McCall96f0b5f2010-03-10 06:48:02 +00002693 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2694 "Template type parameter types are always available.");
2695
John McCall81e38502010-02-16 03:57:14 +00002696 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002697 assert(!Record->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002698 "struct/union has previous declaration");
2699 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002700 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002701 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002702 assert(!Enum->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002703 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002704 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002705 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002706 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002707 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2708 Decl->TypeForDecl = newType;
2709 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002710 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002711 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002712
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002713 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002714}
2715
Chris Lattner32d920b2007-01-26 02:01:53 +00002716/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002717/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002718QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002719ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2720 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002721 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002722
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002723 if (Canonical.isNull())
2724 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002725 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002726 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002727 Decl->TypeForDecl = newType;
2728 Types.push_back(newType);
2729 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002730}
2731
Jay Foad39c79802011-01-12 09:06:06 +00002732QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002733 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2734
Douglas Gregorec9fd132012-01-14 16:38:05 +00002735 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002736 if (PrevDecl->TypeForDecl)
2737 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2738
John McCall424cec92011-01-19 06:33:43 +00002739 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2740 Decl->TypeForDecl = newType;
2741 Types.push_back(newType);
2742 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002743}
2744
Jay Foad39c79802011-01-12 09:06:06 +00002745QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002746 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2747
Douglas Gregorec9fd132012-01-14 16:38:05 +00002748 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002749 if (PrevDecl->TypeForDecl)
2750 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2751
John McCall424cec92011-01-19 06:33:43 +00002752 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2753 Decl->TypeForDecl = newType;
2754 Types.push_back(newType);
2755 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002756}
2757
John McCall81904512011-01-06 01:58:22 +00002758QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2759 QualType modifiedType,
2760 QualType equivalentType) {
2761 llvm::FoldingSetNodeID id;
2762 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2763
2764 void *insertPos = 0;
2765 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2766 if (type) return QualType(type, 0);
2767
2768 QualType canon = getCanonicalType(equivalentType);
2769 type = new (*this, TypeAlignment)
2770 AttributedType(canon, attrKind, modifiedType, equivalentType);
2771
2772 Types.push_back(type);
2773 AttributedTypes.InsertNode(type, insertPos);
2774
2775 return QualType(type, 0);
2776}
2777
2778
John McCallcebee162009-10-18 09:09:24 +00002779/// \brief Retrieve a substitution-result type.
2780QualType
2781ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002782 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002783 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002784 && "replacement types must always be canonical");
2785
2786 llvm::FoldingSetNodeID ID;
2787 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2788 void *InsertPos = 0;
2789 SubstTemplateTypeParmType *SubstParm
2790 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2791
2792 if (!SubstParm) {
2793 SubstParm = new (*this, TypeAlignment)
2794 SubstTemplateTypeParmType(Parm, Replacement);
2795 Types.push_back(SubstParm);
2796 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2797 }
2798
2799 return QualType(SubstParm, 0);
2800}
2801
Douglas Gregorada4b792011-01-14 02:55:32 +00002802/// \brief Retrieve a
2803QualType ASTContext::getSubstTemplateTypeParmPackType(
2804 const TemplateTypeParmType *Parm,
2805 const TemplateArgument &ArgPack) {
2806#ifndef NDEBUG
2807 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2808 PEnd = ArgPack.pack_end();
2809 P != PEnd; ++P) {
2810 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2811 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2812 }
2813#endif
2814
2815 llvm::FoldingSetNodeID ID;
2816 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2817 void *InsertPos = 0;
2818 if (SubstTemplateTypeParmPackType *SubstParm
2819 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2820 return QualType(SubstParm, 0);
2821
2822 QualType Canon;
2823 if (!Parm->isCanonicalUnqualified()) {
2824 Canon = getCanonicalType(QualType(Parm, 0));
2825 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2826 ArgPack);
2827 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2828 }
2829
2830 SubstTemplateTypeParmPackType *SubstParm
2831 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2832 ArgPack);
2833 Types.push_back(SubstParm);
2834 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2835 return QualType(SubstParm, 0);
2836}
2837
Douglas Gregoreff93e02009-02-05 23:33:38 +00002838/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002839/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002840/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002841QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002842 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002843 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002844 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002845 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002846 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002847 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002848 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2849
2850 if (TypeParm)
2851 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002852
Chandler Carruth08836322011-05-01 00:51:33 +00002853 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002854 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002855 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002856
2857 TemplateTypeParmType *TypeCheck
2858 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2859 assert(!TypeCheck && "Template type parameter canonical type broken");
2860 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002861 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002862 TypeParm = new (*this, TypeAlignment)
2863 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002864
2865 Types.push_back(TypeParm);
2866 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2867
2868 return QualType(TypeParm, 0);
2869}
2870
John McCalle78aac42010-03-10 03:28:59 +00002871TypeSourceInfo *
2872ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2873 SourceLocation NameLoc,
2874 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002875 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002876 assert(!Name.getAsDependentTemplateName() &&
2877 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002878 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002879
2880 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2881 TemplateSpecializationTypeLoc TL
2882 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002883 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00002884 TL.setTemplateNameLoc(NameLoc);
2885 TL.setLAngleLoc(Args.getLAngleLoc());
2886 TL.setRAngleLoc(Args.getRAngleLoc());
2887 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2888 TL.setArgLocInfo(i, Args[i].getLocInfo());
2889 return DI;
2890}
2891
Mike Stump11289f42009-09-09 15:08:12 +00002892QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002893ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002894 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002895 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002896 assert(!Template.getAsDependentTemplateName() &&
2897 "No dependent template names here!");
2898
John McCall6b51f282009-11-23 01:53:49 +00002899 unsigned NumArgs = Args.size();
2900
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002901 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002902 ArgVec.reserve(NumArgs);
2903 for (unsigned i = 0; i != NumArgs; ++i)
2904 ArgVec.push_back(Args[i].getArgument());
2905
John McCall2408e322010-04-27 00:57:59 +00002906 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002907 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002908}
2909
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002910#ifndef NDEBUG
2911static bool hasAnyPackExpansions(const TemplateArgument *Args,
2912 unsigned NumArgs) {
2913 for (unsigned I = 0; I != NumArgs; ++I)
2914 if (Args[I].isPackExpansion())
2915 return true;
2916
2917 return true;
2918}
2919#endif
2920
John McCall0ad16662009-10-29 08:12:44 +00002921QualType
2922ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002923 const TemplateArgument *Args,
2924 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002925 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002926 assert(!Template.getAsDependentTemplateName() &&
2927 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002928 // Look through qualified template names.
2929 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2930 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002931
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002932 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00002933 Template.getAsTemplateDecl() &&
2934 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00002935 QualType CanonType;
2936 if (!Underlying.isNull())
2937 CanonType = getCanonicalType(Underlying);
2938 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002939 // We can get here with an alias template when the specialization contains
2940 // a pack expansion that does not match up with a parameter pack.
2941 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2942 "Caller must compute aliased type");
2943 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00002944 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2945 NumArgs);
2946 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002947
Douglas Gregora8e02e72009-07-28 23:00:59 +00002948 // Allocate the (non-canonical) template specialization type, but don't
2949 // try to unique it: these types typically have location information that
2950 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002951 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2952 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002953 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002954 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002955 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002956 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2957 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002958
Douglas Gregor8bf42052009-02-09 18:46:07 +00002959 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002960 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002961}
2962
Mike Stump11289f42009-09-09 15:08:12 +00002963QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002964ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2965 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002966 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002967 assert(!Template.getAsDependentTemplateName() &&
2968 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002969
Douglas Gregore29139c2011-03-03 17:04:51 +00002970 // Look through qualified template names.
2971 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2972 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002973
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002974 // Build the canonical template specialization type.
2975 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002976 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002977 CanonArgs.reserve(NumArgs);
2978 for (unsigned I = 0; I != NumArgs; ++I)
2979 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2980
2981 // Determine whether this canonical template specialization type already
2982 // exists.
2983 llvm::FoldingSetNodeID ID;
2984 TemplateSpecializationType::Profile(ID, CanonTemplate,
2985 CanonArgs.data(), NumArgs, *this);
2986
2987 void *InsertPos = 0;
2988 TemplateSpecializationType *Spec
2989 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2990
2991 if (!Spec) {
2992 // Allocate a new canonical template specialization type.
2993 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2994 sizeof(TemplateArgument) * NumArgs),
2995 TypeAlignment);
2996 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2997 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002998 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002999 Types.push_back(Spec);
3000 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3001 }
3002
3003 assert(Spec->isDependentType() &&
3004 "Non-dependent template-id type must have a canonical type");
3005 return QualType(Spec, 0);
3006}
3007
3008QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003009ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3010 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003011 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003012 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003013 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003014
3015 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003016 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003017 if (T)
3018 return QualType(T, 0);
3019
Douglas Gregorc42075a2010-02-04 18:10:26 +00003020 QualType Canon = NamedType;
3021 if (!Canon.isCanonical()) {
3022 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003023 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3024 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003025 (void)CheckT;
3026 }
3027
Abramo Bagnara6150c882010-05-11 21:36:43 +00003028 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003029 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003030 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003031 return QualType(T, 0);
3032}
3033
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003034QualType
Jay Foad39c79802011-01-12 09:06:06 +00003035ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003036 llvm::FoldingSetNodeID ID;
3037 ParenType::Profile(ID, InnerType);
3038
3039 void *InsertPos = 0;
3040 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3041 if (T)
3042 return QualType(T, 0);
3043
3044 QualType Canon = InnerType;
3045 if (!Canon.isCanonical()) {
3046 Canon = getCanonicalType(InnerType);
3047 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3048 assert(!CheckT && "Paren canonical type broken");
3049 (void)CheckT;
3050 }
3051
3052 T = new (*this) ParenType(InnerType, Canon);
3053 Types.push_back(T);
3054 ParenTypes.InsertNode(T, InsertPos);
3055 return QualType(T, 0);
3056}
3057
Douglas Gregor02085352010-03-31 20:19:30 +00003058QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3059 NestedNameSpecifier *NNS,
3060 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003061 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003062 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3063
3064 if (Canon.isNull()) {
3065 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003066 ElaboratedTypeKeyword CanonKeyword = Keyword;
3067 if (Keyword == ETK_None)
3068 CanonKeyword = ETK_Typename;
3069
3070 if (CanonNNS != NNS || CanonKeyword != Keyword)
3071 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003072 }
3073
3074 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003075 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003076
3077 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003078 DependentNameType *T
3079 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003080 if (T)
3081 return QualType(T, 0);
3082
Douglas Gregor02085352010-03-31 20:19:30 +00003083 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003084 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003085 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003086 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003087}
3088
Mike Stump11289f42009-09-09 15:08:12 +00003089QualType
John McCallc392f372010-06-11 00:33:02 +00003090ASTContext::getDependentTemplateSpecializationType(
3091 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003092 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003093 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003094 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003095 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003096 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003097 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3098 ArgCopy.push_back(Args[I].getArgument());
3099 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3100 ArgCopy.size(),
3101 ArgCopy.data());
3102}
3103
3104QualType
3105ASTContext::getDependentTemplateSpecializationType(
3106 ElaboratedTypeKeyword Keyword,
3107 NestedNameSpecifier *NNS,
3108 const IdentifierInfo *Name,
3109 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003110 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003111 assert((!NNS || NNS->isDependent()) &&
3112 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003113
Douglas Gregorc42075a2010-02-04 18:10:26 +00003114 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003115 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3116 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003117
3118 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00003119 DependentTemplateSpecializationType *T
3120 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003121 if (T)
3122 return QualType(T, 0);
3123
John McCallc392f372010-06-11 00:33:02 +00003124 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003125
John McCallc392f372010-06-11 00:33:02 +00003126 ElaboratedTypeKeyword CanonKeyword = Keyword;
3127 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3128
3129 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003130 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003131 for (unsigned I = 0; I != NumArgs; ++I) {
3132 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3133 if (!CanonArgs[I].structurallyEquals(Args[I]))
3134 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003135 }
3136
John McCallc392f372010-06-11 00:33:02 +00003137 QualType Canon;
3138 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3139 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3140 Name, NumArgs,
3141 CanonArgs.data());
3142
3143 // Find the insert position again.
3144 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3145 }
3146
3147 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3148 sizeof(TemplateArgument) * NumArgs),
3149 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003150 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003151 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003152 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003153 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003154 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003155}
3156
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003157QualType ASTContext::getPackExpansionType(QualType Pattern,
3158 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003159 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003160 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003161
3162 assert(Pattern->containsUnexpandedParameterPack() &&
3163 "Pack expansions must expand one or more parameter packs");
3164 void *InsertPos = 0;
3165 PackExpansionType *T
3166 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3167 if (T)
3168 return QualType(T, 0);
3169
3170 QualType Canon;
3171 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003172 Canon = getCanonicalType(Pattern);
3173 // The canonical type might not contain an unexpanded parameter pack, if it
3174 // contains an alias template specialization which ignores one of its
3175 // parameters.
3176 if (Canon->containsUnexpandedParameterPack()) {
3177 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003178
Richard Smith68eea502012-07-16 00:20:35 +00003179 // Find the insert position again, in case we inserted an element into
3180 // PackExpansionTypes and invalidated our insert position.
3181 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3182 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003183 }
3184
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003185 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003186 Types.push_back(T);
3187 PackExpansionTypes.InsertNode(T, InsertPos);
3188 return QualType(T, 0);
3189}
3190
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003191/// CmpProtocolNames - Comparison predicate for sorting protocols
3192/// alphabetically.
3193static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3194 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003195 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003196}
3197
John McCall8b07ec22010-05-15 11:32:37 +00003198static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003199 unsigned NumProtocols) {
3200 if (NumProtocols == 0) return true;
3201
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003202 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3203 return false;
3204
John McCallfc93cf92009-10-22 22:37:11 +00003205 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003206 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3207 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003208 return false;
3209 return true;
3210}
3211
3212static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003213 unsigned &NumProtocols) {
3214 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003215
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003216 // Sort protocols, keyed by name.
3217 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3218
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003219 // Canonicalize.
3220 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3221 Protocols[I] = Protocols[I]->getCanonicalDecl();
3222
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003223 // Remove duplicates.
3224 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3225 NumProtocols = ProtocolsEnd-Protocols;
3226}
3227
John McCall8b07ec22010-05-15 11:32:37 +00003228QualType ASTContext::getObjCObjectType(QualType BaseType,
3229 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003230 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003231 // If the base type is an interface and there aren't any protocols
3232 // to add, then the interface type will do just fine.
3233 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3234 return BaseType;
3235
3236 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003237 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003238 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00003239 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00003240 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3241 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003242
John McCall8b07ec22010-05-15 11:32:37 +00003243 // Build the canonical type, which has the canonical base type and
3244 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003245 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003246 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3247 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3248 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003249 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003250 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003251 unsigned UniqueCount = NumProtocols;
3252
John McCallfc93cf92009-10-22 22:37:11 +00003253 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003254 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3255 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003256 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003257 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3258 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003259 }
3260
3261 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003262 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3263 }
3264
3265 unsigned Size = sizeof(ObjCObjectTypeImpl);
3266 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3267 void *Mem = Allocate(Size, TypeAlignment);
3268 ObjCObjectTypeImpl *T =
3269 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3270
3271 Types.push_back(T);
3272 ObjCObjectTypes.InsertNode(T, InsertPos);
3273 return QualType(T, 0);
3274}
3275
3276/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3277/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003278QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003279 llvm::FoldingSetNodeID ID;
3280 ObjCObjectPointerType::Profile(ID, ObjectT);
3281
3282 void *InsertPos = 0;
3283 if (ObjCObjectPointerType *QT =
3284 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3285 return QualType(QT, 0);
3286
3287 // Find the canonical object type.
3288 QualType Canonical;
3289 if (!ObjectT.isCanonical()) {
3290 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3291
3292 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003293 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3294 }
3295
Douglas Gregorf85bee62010-02-08 22:59:26 +00003296 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003297 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3298 ObjCObjectPointerType *QType =
3299 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003300
Steve Narofffb4330f2009-06-17 22:40:22 +00003301 Types.push_back(QType);
3302 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003303 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003304}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003305
Douglas Gregor1c283312010-08-11 12:19:30 +00003306/// getObjCInterfaceType - Return the unique reference to the type for the
3307/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003308QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3309 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003310 if (Decl->TypeForDecl)
3311 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003312
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003313 if (PrevDecl) {
3314 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3315 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3316 return QualType(PrevDecl->TypeForDecl, 0);
3317 }
3318
Douglas Gregor7671e532011-12-16 16:34:57 +00003319 // Prefer the definition, if there is one.
3320 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3321 Decl = Def;
3322
Douglas Gregor1c283312010-08-11 12:19:30 +00003323 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3324 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3325 Decl->TypeForDecl = T;
3326 Types.push_back(T);
3327 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003328}
3329
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003330/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3331/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003332/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003333/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003334/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003335QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003336 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003337 if (tofExpr->isTypeDependent()) {
3338 llvm::FoldingSetNodeID ID;
3339 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003340
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003341 void *InsertPos = 0;
3342 DependentTypeOfExprType *Canon
3343 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3344 if (Canon) {
3345 // We already have a "canonical" version of an identical, dependent
3346 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003347 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003348 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003349 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003350 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003351 Canon
3352 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003353 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3354 toe = Canon;
3355 }
3356 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003357 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003358 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003359 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003360 Types.push_back(toe);
3361 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003362}
3363
Steve Naroffa773cd52007-08-01 18:02:17 +00003364/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3365/// TypeOfType AST's. The only motivation to unique these nodes would be
3366/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003367/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003368/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003369QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003370 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003371 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003372 Types.push_back(tot);
3373 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003374}
3375
Anders Carlssonad6bd352009-06-24 21:24:56 +00003376
Anders Carlsson81df7b82009-06-24 19:06:50 +00003377/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3378/// DecltypeType AST's. The only motivation to unique these nodes would be
3379/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003380/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003381/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003382QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003383 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003384
3385 // C++0x [temp.type]p2:
3386 // If an expression e involves a template parameter, decltype(e) denotes a
3387 // unique dependent type. Two such decltype-specifiers refer to the same
3388 // type only if their expressions are equivalent (14.5.6.1).
3389 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003390 llvm::FoldingSetNodeID ID;
3391 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003392
Douglas Gregora21f6c32009-07-30 23:36:40 +00003393 void *InsertPos = 0;
3394 DependentDecltypeType *Canon
3395 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3396 if (Canon) {
3397 // We already have a "canonical" version of an equivalent, dependent
3398 // decltype type. Use that as our canonical type.
Richard Smithef8bf432012-08-13 20:08:14 +00003399 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003400 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003401 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003402 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003403 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003404 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3405 dt = Canon;
3406 }
3407 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003408 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3409 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003410 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003411 Types.push_back(dt);
3412 return QualType(dt, 0);
3413}
3414
Alexis Hunte852b102011-05-24 22:41:36 +00003415/// getUnaryTransformationType - We don't unique these, since the memory
3416/// savings are minimal and these are rare.
3417QualType ASTContext::getUnaryTransformType(QualType BaseType,
3418 QualType UnderlyingType,
3419 UnaryTransformType::UTTKind Kind)
3420 const {
3421 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003422 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3423 Kind,
3424 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003425 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003426 Types.push_back(Ty);
3427 return QualType(Ty, 0);
3428}
3429
Richard Smithb2bc2e62011-02-21 20:05:19 +00003430/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003431QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00003432 void *InsertPos = 0;
3433 if (!DeducedType.isNull()) {
3434 // Look in the folding set for an existing type.
3435 llvm::FoldingSetNodeID ID;
3436 AutoType::Profile(ID, DeducedType);
3437 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3438 return QualType(AT, 0);
3439 }
3440
3441 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3442 Types.push_back(AT);
3443 if (InsertPos)
3444 AutoTypes.InsertNode(AT, InsertPos);
3445 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003446}
3447
Eli Friedman0dfb8892011-10-06 23:00:33 +00003448/// getAtomicType - Return the uniqued reference to the atomic type for
3449/// the given value type.
3450QualType ASTContext::getAtomicType(QualType T) const {
3451 // Unique pointers, to guarantee there is only one pointer of a particular
3452 // structure.
3453 llvm::FoldingSetNodeID ID;
3454 AtomicType::Profile(ID, T);
3455
3456 void *InsertPos = 0;
3457 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3458 return QualType(AT, 0);
3459
3460 // If the atomic value type isn't canonical, this won't be a canonical type
3461 // either, so fill in the canonical type field.
3462 QualType Canonical;
3463 if (!T.isCanonical()) {
3464 Canonical = getAtomicType(getCanonicalType(T));
3465
3466 // Get the new insert position for the node we care about.
3467 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3468 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3469 }
3470 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3471 Types.push_back(New);
3472 AtomicTypes.InsertNode(New, InsertPos);
3473 return QualType(New, 0);
3474}
3475
Richard Smith02e85f32011-04-14 22:09:26 +00003476/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3477QualType ASTContext::getAutoDeductType() const {
3478 if (AutoDeductTy.isNull())
3479 AutoDeductTy = getAutoType(QualType());
3480 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3481 return AutoDeductTy;
3482}
3483
3484/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3485QualType ASTContext::getAutoRRefDeductType() const {
3486 if (AutoRRefDeductTy.isNull())
3487 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3488 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3489 return AutoRRefDeductTy;
3490}
3491
Chris Lattnerfb072462007-01-23 05:45:31 +00003492/// getTagDeclType - Return the unique reference to the type for the
3493/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003494QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003495 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003496 // FIXME: What is the design on getTagDeclType when it requires casting
3497 // away const? mutable?
3498 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003499}
3500
Mike Stump11289f42009-09-09 15:08:12 +00003501/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3502/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3503/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003504CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003505 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003506}
Chris Lattnerfb072462007-01-23 05:45:31 +00003507
Hans Wennborg27541db2011-10-27 08:29:09 +00003508/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3509CanQualType ASTContext::getIntMaxType() const {
3510 return getFromTargetType(Target->getIntMaxType());
3511}
3512
3513/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3514CanQualType ASTContext::getUIntMaxType() const {
3515 return getFromTargetType(Target->getUIntMaxType());
3516}
3517
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003518/// getSignedWCharType - Return the type of "signed wchar_t".
3519/// Used when in C++, as a GCC extension.
3520QualType ASTContext::getSignedWCharType() const {
3521 // FIXME: derive from "Target" ?
3522 return WCharTy;
3523}
3524
3525/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3526/// Used when in C++, as a GCC extension.
3527QualType ASTContext::getUnsignedWCharType() const {
3528 // FIXME: derive from "Target" ?
3529 return UnsignedIntTy;
3530}
3531
Hans Wennborg27541db2011-10-27 08:29:09 +00003532/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003533/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3534QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003535 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003536}
3537
Eli Friedman4e91899e2012-11-27 02:58:24 +00003538/// \brief Return the unique type for "pid_t" defined in
3539/// <sys/types.h>. We need this to compute the correct type for vfork().
3540QualType ASTContext::getProcessIDType() const {
3541 return getFromTargetType(Target->getProcessIDType());
3542}
3543
Chris Lattnera21ad802008-04-02 05:18:44 +00003544//===----------------------------------------------------------------------===//
3545// Type Operators
3546//===----------------------------------------------------------------------===//
3547
Jay Foad39c79802011-01-12 09:06:06 +00003548CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003549 // Push qualifiers into arrays, and then discard any remaining
3550 // qualifiers.
3551 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003552 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003553 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003554 QualType Result;
3555 if (isa<ArrayType>(Ty)) {
3556 Result = getArrayDecayedType(QualType(Ty,0));
3557 } else if (isa<FunctionType>(Ty)) {
3558 Result = getPointerType(QualType(Ty, 0));
3559 } else {
3560 Result = QualType(Ty, 0);
3561 }
3562
3563 return CanQualType::CreateUnsafe(Result);
3564}
3565
John McCall6c9dd522011-01-18 07:41:22 +00003566QualType ASTContext::getUnqualifiedArrayType(QualType type,
3567 Qualifiers &quals) {
3568 SplitQualType splitType = type.getSplitUnqualifiedType();
3569
3570 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3571 // the unqualified desugared type and then drops it on the floor.
3572 // We then have to strip that sugar back off with
3573 // getUnqualifiedDesugaredType(), which is silly.
3574 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003575 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003576
3577 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003578 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003579 quals = splitType.Quals;
3580 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003581 }
3582
John McCall6c9dd522011-01-18 07:41:22 +00003583 // Otherwise, recurse on the array's element type.
3584 QualType elementType = AT->getElementType();
3585 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3586
3587 // If that didn't change the element type, AT has no qualifiers, so we
3588 // can just use the results in splitType.
3589 if (elementType == unqualElementType) {
3590 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003591 quals = splitType.Quals;
3592 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003593 }
3594
3595 // Otherwise, add in the qualifiers from the outermost type, then
3596 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003597 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003598
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003599 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003600 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003601 CAT->getSizeModifier(), 0);
3602 }
3603
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003604 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003605 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003606 }
3607
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003608 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003609 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003610 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003611 VAT->getSizeModifier(),
3612 VAT->getIndexTypeCVRQualifiers(),
3613 VAT->getBracketsRange());
3614 }
3615
3616 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003617 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003618 DSAT->getSizeModifier(), 0,
3619 SourceRange());
3620}
3621
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003622/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3623/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3624/// they point to and return true. If T1 and T2 aren't pointer types
3625/// or pointer-to-member types, or if they are not similar at this
3626/// level, returns false and leaves T1 and T2 unchanged. Top-level
3627/// qualifiers on T1 and T2 are ignored. This function will typically
3628/// be called in a loop that successively "unwraps" pointer and
3629/// pointer-to-member types to compare them at each level.
3630bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3631 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3632 *T2PtrType = T2->getAs<PointerType>();
3633 if (T1PtrType && T2PtrType) {
3634 T1 = T1PtrType->getPointeeType();
3635 T2 = T2PtrType->getPointeeType();
3636 return true;
3637 }
3638
3639 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3640 *T2MPType = T2->getAs<MemberPointerType>();
3641 if (T1MPType && T2MPType &&
3642 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3643 QualType(T2MPType->getClass(), 0))) {
3644 T1 = T1MPType->getPointeeType();
3645 T2 = T2MPType->getPointeeType();
3646 return true;
3647 }
3648
David Blaikiebbafb8a2012-03-11 07:00:24 +00003649 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003650 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3651 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3652 if (T1OPType && T2OPType) {
3653 T1 = T1OPType->getPointeeType();
3654 T2 = T2OPType->getPointeeType();
3655 return true;
3656 }
3657 }
3658
3659 // FIXME: Block pointers, too?
3660
3661 return false;
3662}
3663
Jay Foad39c79802011-01-12 09:06:06 +00003664DeclarationNameInfo
3665ASTContext::getNameForTemplate(TemplateName Name,
3666 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003667 switch (Name.getKind()) {
3668 case TemplateName::QualifiedTemplate:
3669 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003670 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003671 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3672 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003673
John McCalld9dfe3a2011-06-30 08:33:18 +00003674 case TemplateName::OverloadedTemplate: {
3675 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3676 // DNInfo work in progress: CHECKME: what about DNLoc?
3677 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3678 }
3679
3680 case TemplateName::DependentTemplate: {
3681 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003682 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003683 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003684 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3685 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003686 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003687 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3688 // DNInfo work in progress: FIXME: source locations?
3689 DeclarationNameLoc DNLoc;
3690 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3691 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3692 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003693 }
3694 }
3695
John McCalld9dfe3a2011-06-30 08:33:18 +00003696 case TemplateName::SubstTemplateTemplateParm: {
3697 SubstTemplateTemplateParmStorage *subst
3698 = Name.getAsSubstTemplateTemplateParm();
3699 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3700 NameLoc);
3701 }
3702
3703 case TemplateName::SubstTemplateTemplateParmPack: {
3704 SubstTemplateTemplateParmPackStorage *subst
3705 = Name.getAsSubstTemplateTemplateParmPack();
3706 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3707 NameLoc);
3708 }
3709 }
3710
3711 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003712}
3713
Jay Foad39c79802011-01-12 09:06:06 +00003714TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003715 switch (Name.getKind()) {
3716 case TemplateName::QualifiedTemplate:
3717 case TemplateName::Template: {
3718 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003719 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003720 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003721 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3722
3723 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003724 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003725 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003726
John McCalld9dfe3a2011-06-30 08:33:18 +00003727 case TemplateName::OverloadedTemplate:
3728 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003729
John McCalld9dfe3a2011-06-30 08:33:18 +00003730 case TemplateName::DependentTemplate: {
3731 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3732 assert(DTN && "Non-dependent template names must refer to template decls.");
3733 return DTN->CanonicalTemplateName;
3734 }
3735
3736 case TemplateName::SubstTemplateTemplateParm: {
3737 SubstTemplateTemplateParmStorage *subst
3738 = Name.getAsSubstTemplateTemplateParm();
3739 return getCanonicalTemplateName(subst->getReplacement());
3740 }
3741
3742 case TemplateName::SubstTemplateTemplateParmPack: {
3743 SubstTemplateTemplateParmPackStorage *subst
3744 = Name.getAsSubstTemplateTemplateParmPack();
3745 TemplateTemplateParmDecl *canonParameter
3746 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3747 TemplateArgument canonArgPack
3748 = getCanonicalTemplateArgument(subst->getArgumentPack());
3749 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3750 }
3751 }
3752
3753 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003754}
3755
Douglas Gregoradee3e32009-11-11 23:06:43 +00003756bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3757 X = getCanonicalTemplateName(X);
3758 Y = getCanonicalTemplateName(Y);
3759 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3760}
3761
Mike Stump11289f42009-09-09 15:08:12 +00003762TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003763ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003764 switch (Arg.getKind()) {
3765 case TemplateArgument::Null:
3766 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003767
Douglas Gregora8e02e72009-07-28 23:00:59 +00003768 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003769 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003770
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003771 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00003772 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
3773 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003774 }
Mike Stump11289f42009-09-09 15:08:12 +00003775
Eli Friedmanb826a002012-09-26 02:36:12 +00003776 case TemplateArgument::NullPtr:
3777 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
3778 /*isNullPtr*/true);
3779
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003780 case TemplateArgument::Template:
3781 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003782
3783 case TemplateArgument::TemplateExpansion:
3784 return TemplateArgument(getCanonicalTemplateName(
3785 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003786 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003787
Douglas Gregora8e02e72009-07-28 23:00:59 +00003788 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00003789 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003790
Douglas Gregora8e02e72009-07-28 23:00:59 +00003791 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003792 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003793
Douglas Gregora8e02e72009-07-28 23:00:59 +00003794 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003795 if (Arg.pack_size() == 0)
3796 return Arg;
3797
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003798 TemplateArgument *CanonArgs
3799 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003800 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003801 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003802 AEnd = Arg.pack_end();
3803 A != AEnd; (void)++A, ++Idx)
3804 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003805
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003806 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003807 }
3808 }
3809
3810 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003811 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003812}
3813
Douglas Gregor333489b2009-03-27 23:10:48 +00003814NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003815ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003816 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003817 return 0;
3818
3819 switch (NNS->getKind()) {
3820 case NestedNameSpecifier::Identifier:
3821 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003822 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003823 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3824 NNS->getAsIdentifier());
3825
3826 case NestedNameSpecifier::Namespace:
3827 // A namespace is canonical; build a nested-name-specifier with
3828 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003829 return NestedNameSpecifier::Create(*this, 0,
3830 NNS->getAsNamespace()->getOriginalNamespace());
3831
3832 case NestedNameSpecifier::NamespaceAlias:
3833 // A namespace is canonical; build a nested-name-specifier with
3834 // this namespace and no prefix.
3835 return NestedNameSpecifier::Create(*this, 0,
3836 NNS->getAsNamespaceAlias()->getNamespace()
3837 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003838
3839 case NestedNameSpecifier::TypeSpec:
3840 case NestedNameSpecifier::TypeSpecWithTemplate: {
3841 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003842
3843 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3844 // break it apart into its prefix and identifier, then reconsititute those
3845 // as the canonical nested-name-specifier. This is required to canonicalize
3846 // a dependent nested-name-specifier involving typedefs of dependent-name
3847 // types, e.g.,
3848 // typedef typename T::type T1;
3849 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00003850 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3851 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00003852 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003853
Eli Friedman5358a0a2012-03-03 04:09:56 +00003854 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3855 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3856 // first place?
John McCall33ddac02011-01-19 10:06:00 +00003857 return NestedNameSpecifier::Create(*this, 0, false,
3858 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003859 }
3860
3861 case NestedNameSpecifier::Global:
3862 // The global specifier is canonical and unique.
3863 return NNS;
3864 }
3865
David Blaikie8a40f702012-01-17 06:56:22 +00003866 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00003867}
3868
Chris Lattner7adf0762008-08-04 07:31:14 +00003869
Jay Foad39c79802011-01-12 09:06:06 +00003870const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003871 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003872 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003873 // Handle the common positive case fast.
3874 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3875 return AT;
3876 }
Mike Stump11289f42009-09-09 15:08:12 +00003877
John McCall8ccfcb52009-09-24 19:53:00 +00003878 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003879 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003880 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003881
John McCall8ccfcb52009-09-24 19:53:00 +00003882 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003883 // implements C99 6.7.3p8: "If the specification of an array type includes
3884 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003885
Chris Lattner7adf0762008-08-04 07:31:14 +00003886 // If we get here, we either have type qualifiers on the type, or we have
3887 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003888 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003889
John McCall33ddac02011-01-19 10:06:00 +00003890 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003891 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00003892
Chris Lattner7adf0762008-08-04 07:31:14 +00003893 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00003894 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00003895 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003896 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003897
Chris Lattner7adf0762008-08-04 07:31:14 +00003898 // Otherwise, we have an array and we have qualifiers on it. Push the
3899 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003900 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003901
Chris Lattner7adf0762008-08-04 07:31:14 +00003902 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3903 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3904 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003905 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003906 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3907 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3908 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003909 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003910
Mike Stump11289f42009-09-09 15:08:12 +00003911 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003912 = dyn_cast<DependentSizedArrayType>(ATy))
3913 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003914 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003915 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003916 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003917 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003918 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003919
Chris Lattner7adf0762008-08-04 07:31:14 +00003920 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003921 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003922 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003923 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003924 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003925 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003926}
3927
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003928QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003929 // C99 6.7.5.3p7:
3930 // A declaration of a parameter as "array of type" shall be
3931 // adjusted to "qualified pointer to type", where the type
3932 // qualifiers (if any) are those specified within the [ and ] of
3933 // the array type derivation.
3934 if (T->isArrayType())
3935 return getArrayDecayedType(T);
3936
3937 // C99 6.7.5.3p8:
3938 // A declaration of a parameter as "function returning type"
3939 // shall be adjusted to "pointer to function returning type", as
3940 // in 6.3.2.1.
3941 if (T->isFunctionType())
3942 return getPointerType(T);
3943
3944 return T;
3945}
3946
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003947QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003948 T = getVariableArrayDecayedType(T);
3949 T = getAdjustedParameterType(T);
3950 return T.getUnqualifiedType();
3951}
3952
Chris Lattnera21ad802008-04-02 05:18:44 +00003953/// getArrayDecayedType - Return the properly qualified result of decaying the
3954/// specified array type to a pointer. This operation is non-trivial when
3955/// handling typedefs etc. The canonical type of "T" must be an array type,
3956/// this returns a pointer to a properly qualified element of the array.
3957///
3958/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003959QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003960 // Get the element type with 'getAsArrayType' so that we don't lose any
3961 // typedefs in the element type of the array. This also handles propagation
3962 // of type qualifiers from the array type into the element type if present
3963 // (C99 6.7.3p8).
3964 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3965 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003966
Chris Lattner7adf0762008-08-04 07:31:14 +00003967 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003968
3969 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003970 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003971}
3972
John McCall33ddac02011-01-19 10:06:00 +00003973QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3974 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003975}
3976
John McCall33ddac02011-01-19 10:06:00 +00003977QualType ASTContext::getBaseElementType(QualType type) const {
3978 Qualifiers qs;
3979 while (true) {
3980 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003981 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00003982 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003983
John McCall33ddac02011-01-19 10:06:00 +00003984 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00003985 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003986 }
Mike Stump11289f42009-09-09 15:08:12 +00003987
John McCall33ddac02011-01-19 10:06:00 +00003988 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003989}
3990
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003991/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003992uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003993ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3994 uint64_t ElementCount = 1;
3995 do {
3996 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00003997 CA = dyn_cast_or_null<ConstantArrayType>(
3998 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003999 } while (CA);
4000 return ElementCount;
4001}
4002
Steve Naroff0af91202007-04-27 21:51:21 +00004003/// getFloatingRank - Return a relative rank for floating point types.
4004/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004005static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004006 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004007 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004008
John McCall9dd450b2009-09-21 23:43:11 +00004009 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4010 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004011 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004012 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004013 case BuiltinType::Float: return FloatRank;
4014 case BuiltinType::Double: return DoubleRank;
4015 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004016 }
4017}
4018
Mike Stump11289f42009-09-09 15:08:12 +00004019/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4020/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004021/// 'typeDomain' is a real floating point or complex type.
4022/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004023QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4024 QualType Domain) const {
4025 FloatingRank EltRank = getFloatingRank(Size);
4026 if (Domain->isComplexType()) {
4027 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004028 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004029 case FloatRank: return FloatComplexTy;
4030 case DoubleRank: return DoubleComplexTy;
4031 case LongDoubleRank: return LongDoubleComplexTy;
4032 }
Steve Naroff0af91202007-04-27 21:51:21 +00004033 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004034
4035 assert(Domain->isRealFloatingType() && "Unknown domain!");
4036 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004037 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004038 case FloatRank: return FloatTy;
4039 case DoubleRank: return DoubleTy;
4040 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004041 }
David Blaikief47fa302012-01-17 02:30:50 +00004042 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004043}
4044
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004045/// getFloatingTypeOrder - Compare the rank of the two specified floating
4046/// point types, ignoring the domain of the type (i.e. 'double' ==
4047/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004048/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004049int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004050 FloatingRank LHSR = getFloatingRank(LHS);
4051 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004052
Chris Lattnerb90739d2008-04-06 23:38:49 +00004053 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004054 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004055 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004056 return 1;
4057 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004058}
4059
Chris Lattner76a00cf2008-04-06 22:59:24 +00004060/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4061/// routine will assert if passed a built-in type that isn't an integer or enum,
4062/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004063unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004064 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004065
Chris Lattner76a00cf2008-04-06 22:59:24 +00004066 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004067 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004068 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004069 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004070 case BuiltinType::Char_S:
4071 case BuiltinType::Char_U:
4072 case BuiltinType::SChar:
4073 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004074 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004075 case BuiltinType::Short:
4076 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004077 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004078 case BuiltinType::Int:
4079 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004080 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004081 case BuiltinType::Long:
4082 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004083 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004084 case BuiltinType::LongLong:
4085 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004086 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004087 case BuiltinType::Int128:
4088 case BuiltinType::UInt128:
4089 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004090 }
4091}
4092
Eli Friedman629ffb92009-08-20 04:21:42 +00004093/// \brief Whether this is a promotable bitfield reference according
4094/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4095///
4096/// \returns the type this bit-field will promote to, or NULL if no
4097/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004098QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004099 if (E->isTypeDependent() || E->isValueDependent())
4100 return QualType();
4101
Eli Friedman629ffb92009-08-20 04:21:42 +00004102 FieldDecl *Field = E->getBitField();
4103 if (!Field)
4104 return QualType();
4105
4106 QualType FT = Field->getType();
4107
Richard Smithcaf33902011-10-10 18:28:20 +00004108 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004109 uint64_t IntSize = getTypeSize(IntTy);
4110 // GCC extension compatibility: if the bit-field size is less than or equal
4111 // to the size of int, it gets promoted no matter what its type is.
4112 // For instance, unsigned long bf : 4 gets promoted to signed int.
4113 if (BitWidth < IntSize)
4114 return IntTy;
4115
4116 if (BitWidth == IntSize)
4117 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4118
4119 // Types bigger than int are not subject to promotions, and therefore act
4120 // like the base type.
4121 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4122 // is ridiculous.
4123 return QualType();
4124}
4125
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004126/// getPromotedIntegerType - Returns the type that Promotable will
4127/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4128/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004129QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004130 assert(!Promotable.isNull());
4131 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004132 if (const EnumType *ET = Promotable->getAs<EnumType>())
4133 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004134
4135 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4136 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4137 // (3.9.1) can be converted to a prvalue of the first of the following
4138 // types that can represent all the values of its underlying type:
4139 // int, unsigned int, long int, unsigned long int, long long int, or
4140 // unsigned long long int [...]
4141 // FIXME: Is there some better way to compute this?
4142 if (BT->getKind() == BuiltinType::WChar_S ||
4143 BT->getKind() == BuiltinType::WChar_U ||
4144 BT->getKind() == BuiltinType::Char16 ||
4145 BT->getKind() == BuiltinType::Char32) {
4146 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4147 uint64_t FromSize = getTypeSize(BT);
4148 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4149 LongLongTy, UnsignedLongLongTy };
4150 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4151 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4152 if (FromSize < ToSize ||
4153 (FromSize == ToSize &&
4154 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4155 return PromoteTypes[Idx];
4156 }
4157 llvm_unreachable("char type should fit into long long");
4158 }
4159 }
4160
4161 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004162 if (Promotable->isSignedIntegerType())
4163 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004164 uint64_t PromotableSize = getIntWidth(Promotable);
4165 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004166 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4167 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4168}
4169
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004170/// \brief Recurses in pointer/array types until it finds an objc retainable
4171/// type and returns its ownership.
4172Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4173 while (!T.isNull()) {
4174 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4175 return T.getObjCLifetime();
4176 if (T->isArrayType())
4177 T = getBaseElementType(T);
4178 else if (const PointerType *PT = T->getAs<PointerType>())
4179 T = PT->getPointeeType();
4180 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004181 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004182 else
4183 break;
4184 }
4185
4186 return Qualifiers::OCL_None;
4187}
4188
Mike Stump11289f42009-09-09 15:08:12 +00004189/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004190/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004191/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004192int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004193 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4194 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004195 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004196
Chris Lattner76a00cf2008-04-06 22:59:24 +00004197 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4198 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004199
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004200 unsigned LHSRank = getIntegerRank(LHSC);
4201 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004202
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004203 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4204 if (LHSRank == RHSRank) return 0;
4205 return LHSRank > RHSRank ? 1 : -1;
4206 }
Mike Stump11289f42009-09-09 15:08:12 +00004207
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004208 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4209 if (LHSUnsigned) {
4210 // If the unsigned [LHS] type is larger, return it.
4211 if (LHSRank >= RHSRank)
4212 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004213
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004214 // If the signed type can represent all values of the unsigned type, it
4215 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004216 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004217 return -1;
4218 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004219
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004220 // If the unsigned [RHS] type is larger, return it.
4221 if (RHSRank >= LHSRank)
4222 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004223
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004224 // If the signed type can represent all values of the unsigned type, it
4225 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004226 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004227 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004228}
Anders Carlsson98f07902007-08-17 05:31:46 +00004229
Anders Carlsson6d417272009-11-14 21:45:58 +00004230static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004231CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4232 DeclContext *DC, IdentifierInfo *Id) {
4233 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004234 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004235 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004236 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004237 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004238}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004239
Mike Stump11289f42009-09-09 15:08:12 +00004240// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004241QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004242 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00004243 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004244 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004245 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00004246 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004247
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004248 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004249
Anders Carlsson98f07902007-08-17 05:31:46 +00004250 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004251 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004252 // int flags;
4253 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004254 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004255 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004256 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004257 FieldTypes[3] = LongTy;
4258
Anders Carlsson98f07902007-08-17 05:31:46 +00004259 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004260 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004261 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004262 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004263 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00004264 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00004265 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004266 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004267 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004268 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004269 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004270 }
4271
Douglas Gregord5058122010-02-11 01:19:42 +00004272 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004273 }
Mike Stump11289f42009-09-09 15:08:12 +00004274
Anders Carlsson98f07902007-08-17 05:31:46 +00004275 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004276}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004277
Douglas Gregor512b0772009-04-23 22:29:11 +00004278void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004279 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004280 assert(Rec && "Invalid CFConstantStringType");
4281 CFConstantStringTypeDecl = Rec->getDecl();
4282}
4283
Jay Foad39c79802011-01-12 09:06:06 +00004284QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004285 if (BlockDescriptorType)
4286 return getTagDeclType(BlockDescriptorType);
4287
4288 RecordDecl *T;
4289 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004290 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004291 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00004292 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004293
4294 QualType FieldTypes[] = {
4295 UnsignedLongTy,
4296 UnsignedLongTy,
4297 };
4298
4299 const char *FieldNames[] = {
4300 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004301 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004302 };
4303
4304 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004305 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00004306 SourceLocation(),
4307 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004308 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00004309 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004310 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004311 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004312 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00004313 T->addDecl(Field);
4314 }
4315
Douglas Gregord5058122010-02-11 01:19:42 +00004316 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004317
4318 BlockDescriptorType = T;
4319
4320 return getTagDeclType(BlockDescriptorType);
4321}
4322
Jay Foad39c79802011-01-12 09:06:06 +00004323QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004324 if (BlockDescriptorExtendedType)
4325 return getTagDeclType(BlockDescriptorExtendedType);
4326
4327 RecordDecl *T;
4328 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004329 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004330 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00004331 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004332
4333 QualType FieldTypes[] = {
4334 UnsignedLongTy,
4335 UnsignedLongTy,
4336 getPointerType(VoidPtrTy),
4337 getPointerType(VoidPtrTy)
4338 };
4339
4340 const char *FieldNames[] = {
4341 "reserved",
4342 "Size",
4343 "CopyFuncPtr",
4344 "DestroyFuncPtr"
4345 };
4346
4347 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004348 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004349 SourceLocation(),
4350 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004351 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004352 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004353 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004354 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004355 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004356 T->addDecl(Field);
4357 }
4358
Douglas Gregord5058122010-02-11 01:19:42 +00004359 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004360
4361 BlockDescriptorExtendedType = T;
4362
4363 return getTagDeclType(BlockDescriptorExtendedType);
4364}
4365
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004366/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4367/// requires copy/dispose. Note that this must match the logic
4368/// in buildByrefHelpers.
4369bool ASTContext::BlockRequiresCopying(QualType Ty,
4370 const VarDecl *D) {
4371 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4372 const Expr *copyExpr = getBlockVarCopyInits(D);
4373 if (!copyExpr && record->hasTrivialDestructor()) return false;
4374
Mike Stump94967902009-10-21 18:16:27 +00004375 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004376 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004377
4378 if (!Ty->isObjCRetainableType()) return false;
4379
4380 Qualifiers qs = Ty.getQualifiers();
4381
4382 // If we have lifetime, that dominates.
4383 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4384 assert(getLangOpts().ObjCAutoRefCount);
4385
4386 switch (lifetime) {
4387 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4388
4389 // These are just bits as far as the runtime is concerned.
4390 case Qualifiers::OCL_ExplicitNone:
4391 case Qualifiers::OCL_Autoreleasing:
4392 return false;
4393
4394 // Tell the runtime that this is ARC __weak, called by the
4395 // byref routines.
4396 case Qualifiers::OCL_Weak:
4397 // ARC __strong __block variables need to be retained.
4398 case Qualifiers::OCL_Strong:
4399 return true;
4400 }
4401 llvm_unreachable("fell out of lifetime switch!");
4402 }
4403 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4404 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004405}
4406
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004407bool ASTContext::getByrefLifetime(QualType Ty,
4408 Qualifiers::ObjCLifetime &LifeTime,
4409 bool &HasByrefExtendedLayout) const {
4410
4411 if (!getLangOpts().ObjC1 ||
4412 getLangOpts().getGC() != LangOptions::NonGC)
4413 return false;
4414
4415 HasByrefExtendedLayout = false;
4416 if (Ty->isAggregateType()) {
4417 HasByrefExtendedLayout = true;
4418 LifeTime = Qualifiers::OCL_None;
4419 }
4420 else if (getLangOpts().ObjCAutoRefCount)
4421 LifeTime = Ty.getObjCLifetime();
4422 // MRR.
4423 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4424 LifeTime = Qualifiers::OCL_ExplicitNone;
4425 else
4426 LifeTime = Qualifiers::OCL_None;
4427 return true;
4428}
4429
Douglas Gregorbab8a962011-09-08 01:46:34 +00004430TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4431 if (!ObjCInstanceTypeDecl)
4432 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4433 getTranslationUnitDecl(),
4434 SourceLocation(),
4435 SourceLocation(),
4436 &Idents.get("instancetype"),
4437 getTrivialTypeSourceInfo(getObjCIdType()));
4438 return ObjCInstanceTypeDecl;
4439}
4440
Anders Carlsson18acd442007-10-29 06:33:42 +00004441// This returns true if a type has been typedefed to BOOL:
4442// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004443static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004444 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004445 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4446 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004447
Anders Carlssond8499822007-10-29 05:01:08 +00004448 return false;
4449}
4450
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004451/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004452/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004453CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004454 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4455 return CharUnits::Zero();
4456
Ken Dyck40775002010-01-11 17:06:35 +00004457 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004458
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004459 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004460 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004461 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004462 // Treat arrays as pointers, since that's how they're passed in.
4463 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004464 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004465 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004466}
4467
4468static inline
4469std::string charUnitsToString(const CharUnits &CU) {
4470 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004471}
4472
John McCall351762c2011-02-07 10:33:21 +00004473/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004474/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004475std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4476 std::string S;
4477
David Chisnall950a9512009-11-17 19:33:30 +00004478 const BlockDecl *Decl = Expr->getBlockDecl();
4479 QualType BlockTy =
4480 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4481 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004482 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004483 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4484 BlockTy->getAs<FunctionType>()->getResultType(),
4485 S, true /*Extended*/);
4486 else
4487 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4488 S);
David Chisnall950a9512009-11-17 19:33:30 +00004489 // Compute size of all parameters.
4490 // Start with computing size of a pointer in number of bytes.
4491 // FIXME: There might(should) be a better way of doing this computation!
4492 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004493 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4494 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004495 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004496 E = Decl->param_end(); PI != E; ++PI) {
4497 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004498 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004499 if (sz.isZero())
4500 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004501 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004502 ParmOffset += sz;
4503 }
4504 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004505 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004506 // Block pointer and offset.
4507 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004508
4509 // Argument types.
4510 ParmOffset = PtrSize;
4511 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4512 Decl->param_end(); PI != E; ++PI) {
4513 ParmVarDecl *PVDecl = *PI;
4514 QualType PType = PVDecl->getOriginalType();
4515 if (const ArrayType *AT =
4516 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4517 // Use array's original type only if it has known number of
4518 // elements.
4519 if (!isa<ConstantArrayType>(AT))
4520 PType = PVDecl->getType();
4521 } else if (PType->isFunctionType())
4522 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004523 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004524 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4525 S, true /*Extended*/);
4526 else
4527 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004528 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004529 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004530 }
John McCall351762c2011-02-07 10:33:21 +00004531
4532 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004533}
4534
Douglas Gregora9d84932011-05-27 01:19:52 +00004535bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004536 std::string& S) {
4537 // Encode result type.
4538 getObjCEncodingForType(Decl->getResultType(), S);
4539 CharUnits ParmOffset;
4540 // Compute size of all parameters.
4541 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4542 E = Decl->param_end(); PI != E; ++PI) {
4543 QualType PType = (*PI)->getType();
4544 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004545 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004546 continue;
4547
David Chisnall50e4eba2010-12-30 14:05:53 +00004548 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004549 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004550 ParmOffset += sz;
4551 }
4552 S += charUnitsToString(ParmOffset);
4553 ParmOffset = CharUnits::Zero();
4554
4555 // Argument types.
4556 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4557 E = Decl->param_end(); PI != E; ++PI) {
4558 ParmVarDecl *PVDecl = *PI;
4559 QualType PType = PVDecl->getOriginalType();
4560 if (const ArrayType *AT =
4561 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4562 // Use array's original type only if it has known number of
4563 // elements.
4564 if (!isa<ConstantArrayType>(AT))
4565 PType = PVDecl->getType();
4566 } else if (PType->isFunctionType())
4567 PType = PVDecl->getType();
4568 getObjCEncodingForType(PType, S);
4569 S += charUnitsToString(ParmOffset);
4570 ParmOffset += getObjCEncodingTypeSize(PType);
4571 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004572
4573 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004574}
4575
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004576/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4577/// method parameter or return type. If Extended, include class names and
4578/// block object types.
4579void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4580 QualType T, std::string& S,
4581 bool Extended) const {
4582 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4583 getObjCEncodingForTypeQualifier(QT, S);
4584 // Encode parameter type.
4585 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4586 true /*OutermostType*/,
4587 false /*EncodingProperty*/,
4588 false /*StructField*/,
4589 Extended /*EncodeBlockParameters*/,
4590 Extended /*EncodeClassNames*/);
4591}
4592
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004593/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004594/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004595bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004596 std::string& S,
4597 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004598 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004599 // Encode return type.
4600 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4601 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004602 // Compute size of all parameters.
4603 // Start with computing size of a pointer in number of bytes.
4604 // FIXME: There might(should) be a better way of doing this computation!
4605 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004606 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004607 // The first two arguments (self and _cmd) are pointers; account for
4608 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004609 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004610 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004611 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004612 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004613 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004614 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004615 continue;
4616
Ken Dyck40775002010-01-11 17:06:35 +00004617 assert (sz.isPositive() &&
4618 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004619 ParmOffset += sz;
4620 }
Ken Dyck40775002010-01-11 17:06:35 +00004621 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004622 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004623 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004624
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004625 // Argument types.
4626 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004627 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004628 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004629 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004630 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004631 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004632 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4633 // Use array's original type only if it has known number of
4634 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004635 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004636 PType = PVDecl->getType();
4637 } else if (PType->isFunctionType())
4638 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004639 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4640 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004641 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004642 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004643 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004644
4645 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004646}
4647
Daniel Dunbar4932b362008-08-28 04:38:10 +00004648/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004649/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004650/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4651/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004652/// Property attributes are stored as a comma-delimited C string. The simple
4653/// attributes readonly and bycopy are encoded as single characters. The
4654/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4655/// encoded as single characters, followed by an identifier. Property types
4656/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004657/// these attributes are defined by the following enumeration:
4658/// @code
4659/// enum PropertyAttributes {
4660/// kPropertyReadOnly = 'R', // property is read-only.
4661/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4662/// kPropertyByref = '&', // property is a reference to the value last assigned
4663/// kPropertyDynamic = 'D', // property is dynamic
4664/// kPropertyGetter = 'G', // followed by getter selector name
4665/// kPropertySetter = 'S', // followed by setter selector name
4666/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004667/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004668/// kPropertyWeak = 'W' // 'weak' property
4669/// kPropertyStrong = 'P' // property GC'able
4670/// kPropertyNonAtomic = 'N' // property non-atomic
4671/// };
4672/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004673void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004674 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004675 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004676 // Collect information from the property implementation decl(s).
4677 bool Dynamic = false;
4678 ObjCPropertyImplDecl *SynthesizePID = 0;
4679
4680 // FIXME: Duplicated code due to poor abstraction.
4681 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004682 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004683 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4684 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004685 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004686 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004687 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004688 if (PID->getPropertyDecl() == PD) {
4689 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4690 Dynamic = true;
4691 } else {
4692 SynthesizePID = PID;
4693 }
4694 }
4695 }
4696 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004697 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004698 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004699 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004700 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004701 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004702 if (PID->getPropertyDecl() == PD) {
4703 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4704 Dynamic = true;
4705 } else {
4706 SynthesizePID = PID;
4707 }
4708 }
Mike Stump11289f42009-09-09 15:08:12 +00004709 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004710 }
4711 }
4712
4713 // FIXME: This is not very efficient.
4714 S = "T";
4715
4716 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004717 // GCC has some special rules regarding encoding of properties which
4718 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004719 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004720 true /* outermost type */,
4721 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004722
4723 if (PD->isReadOnly()) {
4724 S += ",R";
4725 } else {
4726 switch (PD->getSetterKind()) {
4727 case ObjCPropertyDecl::Assign: break;
4728 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004729 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004730 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004731 }
4732 }
4733
4734 // It really isn't clear at all what this means, since properties
4735 // are "dynamic by default".
4736 if (Dynamic)
4737 S += ",D";
4738
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004739 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4740 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004741
Daniel Dunbar4932b362008-08-28 04:38:10 +00004742 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4743 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004744 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004745 }
4746
4747 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4748 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004749 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004750 }
4751
4752 if (SynthesizePID) {
4753 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4754 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004755 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004756 }
4757
4758 // FIXME: OBJCGC: weak & strong
4759}
4760
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004761/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004762/// Another legacy compatibility encoding: 32-bit longs are encoded as
4763/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004764/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4765///
4766void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004767 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004768 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004769 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004770 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004771 else
Jay Foad39c79802011-01-12 09:06:06 +00004772 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004773 PointeeTy = IntTy;
4774 }
4775 }
4776}
4777
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004778void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004779 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004780 // We follow the behavior of gcc, expanding structures which are
4781 // directly pointed to, and expanding embedded structures. Note that
4782 // these rules are sufficient to prevent recursive encoding of the
4783 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004784 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004785 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004786}
4787
David Chisnallb190a2c2010-06-04 01:10:52 +00004788static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4789 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004790 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnallb190a2c2010-06-04 01:10:52 +00004791 case BuiltinType::Void: return 'v';
4792 case BuiltinType::Bool: return 'B';
4793 case BuiltinType::Char_U:
4794 case BuiltinType::UChar: return 'C';
4795 case BuiltinType::UShort: return 'S';
4796 case BuiltinType::UInt: return 'I';
4797 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004798 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004799 case BuiltinType::UInt128: return 'T';
4800 case BuiltinType::ULongLong: return 'Q';
4801 case BuiltinType::Char_S:
4802 case BuiltinType::SChar: return 'c';
4803 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004804 case BuiltinType::WChar_S:
4805 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004806 case BuiltinType::Int: return 'i';
4807 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004808 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004809 case BuiltinType::LongLong: return 'q';
4810 case BuiltinType::Int128: return 't';
4811 case BuiltinType::Float: return 'f';
4812 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004813 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004814 }
4815}
4816
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004817static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4818 EnumDecl *Enum = ET->getDecl();
4819
4820 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4821 if (!Enum->isFixed())
4822 return 'i';
4823
4824 // The encoding of a fixed enum type matches its fixed underlying type.
4825 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4826}
4827
Jay Foad39c79802011-01-12 09:06:06 +00004828static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004829 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00004830 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004831 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004832 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4833 // The GNU runtime requires more information; bitfields are encoded as b,
4834 // then the offset (in bits) of the first element, then the type of the
4835 // bitfield, then the size in bits. For example, in this structure:
4836 //
4837 // struct
4838 // {
4839 // int integer;
4840 // int flags:2;
4841 // };
4842 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4843 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4844 // information is not especially sensible, but we're stuck with it for
4845 // compatibility with GCC, although providing it breaks anything that
4846 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00004847 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004848 const RecordDecl *RD = FD->getParent();
4849 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004850 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004851 if (const EnumType *ET = T->getAs<EnumType>())
4852 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnall6f0a7d22010-12-26 20:12:30 +00004853 else
Jay Foad39c79802011-01-12 09:06:06 +00004854 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004855 }
Richard Smithcaf33902011-10-10 18:28:20 +00004856 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004857}
4858
Daniel Dunbar07d07852009-10-18 21:17:35 +00004859// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004860void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4861 bool ExpandPointedToStructures,
4862 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004863 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004864 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004865 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004866 bool StructField,
4867 bool EncodeBlockParameters,
4868 bool EncodeClassNames) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004869 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004870 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004871 return EncodeBitField(this, S, T, FD);
4872 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004873 return;
4874 }
Mike Stump11289f42009-09-09 15:08:12 +00004875
John McCall9dd450b2009-09-21 23:43:11 +00004876 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004877 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004878 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004879 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004880 return;
4881 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004882
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004883 // encoding for pointer or r3eference types.
4884 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004885 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004886 if (PT->isObjCSelType()) {
4887 S += ':';
4888 return;
4889 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004890 PointeeTy = PT->getPointeeType();
4891 }
4892 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4893 PointeeTy = RT->getPointeeType();
4894 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004895 bool isReadOnly = false;
4896 // For historical/compatibility reasons, the read-only qualifier of the
4897 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4898 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004899 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004900 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004901 if (OutermostType && T.isConstQualified()) {
4902 isReadOnly = true;
4903 S += 'r';
4904 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004905 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004906 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004907 while (P->getAs<PointerType>())
4908 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004909 if (P.isConstQualified()) {
4910 isReadOnly = true;
4911 S += 'r';
4912 }
4913 }
4914 if (isReadOnly) {
4915 // Another legacy compatibility encoding. Some ObjC qualifier and type
4916 // combinations need to be rearranged.
4917 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004918 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004919 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004920 }
Mike Stump11289f42009-09-09 15:08:12 +00004921
Anders Carlssond8499822007-10-29 05:01:08 +00004922 if (PointeeTy->isCharType()) {
4923 // char pointer types should be encoded as '*' unless it is a
4924 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004925 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004926 S += '*';
4927 return;
4928 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004929 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004930 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4931 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4932 S += '#';
4933 return;
4934 }
4935 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4936 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4937 S += '@';
4938 return;
4939 }
4940 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004941 }
Anders Carlssond8499822007-10-29 05:01:08 +00004942 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004943 getLegacyIntegralTypeEncoding(PointeeTy);
4944
Mike Stump11289f42009-09-09 15:08:12 +00004945 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004946 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004947 return;
4948 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004949
Chris Lattnere7cabb92009-07-13 00:10:46 +00004950 if (const ArrayType *AT =
4951 // Ignore type qualifiers etc.
4952 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004953 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004954 // Incomplete arrays are encoded as a pointer to the array element.
4955 S += '^';
4956
Mike Stump11289f42009-09-09 15:08:12 +00004957 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004958 false, ExpandStructures, FD);
4959 } else {
4960 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004961
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004962 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4963 if (getTypeSize(CAT->getElementType()) == 0)
4964 S += '0';
4965 else
4966 S += llvm::utostr(CAT->getSize().getZExtValue());
4967 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004968 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004969 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4970 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00004971 S += '0';
4972 }
Mike Stump11289f42009-09-09 15:08:12 +00004973
4974 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004975 false, ExpandStructures, FD);
4976 S += ']';
4977 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004978 return;
4979 }
Mike Stump11289f42009-09-09 15:08:12 +00004980
John McCall9dd450b2009-09-21 23:43:11 +00004981 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004982 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004983 return;
4984 }
Mike Stump11289f42009-09-09 15:08:12 +00004985
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004986 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004987 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004988 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004989 // Anonymous structures print as '?'
4990 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4991 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004992 if (ClassTemplateSpecializationDecl *Spec
4993 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4994 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4995 std::string TemplateArgsStr
4996 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004997 TemplateArgs.data(),
4998 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00004999 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005000
5001 S += TemplateArgsStr;
5002 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005003 } else {
5004 S += '?';
5005 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005006 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005007 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005008 if (!RDecl->isUnion()) {
5009 getObjCEncodingForStructureImpl(RDecl, S, FD);
5010 } else {
5011 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5012 FieldEnd = RDecl->field_end();
5013 Field != FieldEnd; ++Field) {
5014 if (FD) {
5015 S += '"';
5016 S += Field->getNameAsString();
5017 S += '"';
5018 }
Mike Stump11289f42009-09-09 15:08:12 +00005019
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005020 // Special case bit-fields.
5021 if (Field->isBitField()) {
5022 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00005023 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005024 } else {
5025 QualType qt = Field->getType();
5026 getLegacyIntegralTypeEncoding(qt);
5027 getObjCEncodingForTypeImpl(qt, S, false, true,
5028 FD, /*OutermostType*/false,
5029 /*EncodingProperty*/false,
5030 /*StructField*/true);
5031 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005032 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005033 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005034 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005035 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005036 return;
5037 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005038
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005039 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005040 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005041 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005042 else
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005043 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005044 return;
5045 }
Mike Stump11289f42009-09-09 15:08:12 +00005046
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005047 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00005048 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005049 if (EncodeBlockParameters) {
5050 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
5051
5052 S += '<';
5053 // Block return type
5054 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5055 ExpandPointedToStructures, ExpandStructures,
5056 FD,
5057 false /* OutermostType */,
5058 EncodingProperty,
5059 false /* StructField */,
5060 EncodeBlockParameters,
5061 EncodeClassNames);
5062 // Block self
5063 S += "@?";
5064 // Block parameters
5065 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5066 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5067 E = FPT->arg_type_end(); I && (I != E); ++I) {
5068 getObjCEncodingForTypeImpl(*I, S,
5069 ExpandPointedToStructures,
5070 ExpandStructures,
5071 FD,
5072 false /* OutermostType */,
5073 EncodingProperty,
5074 false /* StructField */,
5075 EncodeBlockParameters,
5076 EncodeClassNames);
5077 }
5078 }
5079 S += '>';
5080 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005081 return;
5082 }
Mike Stump11289f42009-09-09 15:08:12 +00005083
John McCall8b07ec22010-05-15 11:32:37 +00005084 // Ignore protocol qualifiers when mangling at this level.
5085 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
5086 T = OT->getBaseType();
5087
John McCall8ccfcb52009-09-24 19:53:00 +00005088 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005089 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005090 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005091 S += '{';
5092 const IdentifierInfo *II = OI->getIdentifier();
5093 S += II->getName();
5094 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005095 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005096 DeepCollectObjCIvars(OI, true, Ivars);
5097 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005098 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005099 if (Field->isBitField())
5100 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005101 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005102 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005103 }
5104 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005105 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005106 }
Mike Stump11289f42009-09-09 15:08:12 +00005107
John McCall9dd450b2009-09-21 23:43:11 +00005108 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005109 if (OPT->isObjCIdType()) {
5110 S += '@';
5111 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005112 }
Mike Stump11289f42009-09-09 15:08:12 +00005113
Steve Narofff0c86112009-10-28 22:03:49 +00005114 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5115 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5116 // Since this is a binary compatibility issue, need to consult with runtime
5117 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005118 S += '#';
5119 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005120 }
Mike Stump11289f42009-09-09 15:08:12 +00005121
Chris Lattnere7cabb92009-07-13 00:10:46 +00005122 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005123 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005124 ExpandPointedToStructures,
5125 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005126 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005127 // Note that we do extended encoding of protocol qualifer list
5128 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005129 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00005130 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5131 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005132 S += '<';
5133 S += (*I)->getNameAsString();
5134 S += '>';
5135 }
5136 S += '"';
5137 }
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 QualType PointeeTy = OPT->getPointeeType();
5142 if (!EncodingProperty &&
5143 isa<TypedefType>(PointeeTy.getTypePtr())) {
5144 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005145 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005146 // {...};
5147 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00005148 getObjCEncodingForTypeImpl(PointeeTy, S,
5149 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00005150 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005151 return;
5152 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005153
5154 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005155 if (OPT->getInterfaceDecl() &&
5156 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005157 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005158 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00005159 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5160 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005161 S += '<';
5162 S += (*I)->getNameAsString();
5163 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005164 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005165 S += '"';
5166 }
5167 return;
5168 }
Mike Stump11289f42009-09-09 15:08:12 +00005169
John McCalla9e6e8d2010-05-17 23:56:34 +00005170 // gcc just blithely ignores member pointers.
5171 // TODO: maybe there should be a mangling for these
5172 if (T->getAs<MemberPointerType>())
5173 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005174
5175 if (T->isVectorType()) {
5176 // This matches gcc's encoding, even though technically it is
5177 // insufficient.
5178 // FIXME. We should do a better job than gcc.
5179 return;
5180 }
5181
David Blaikie83d382b2011-09-23 05:06:16 +00005182 llvm_unreachable("@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00005183}
5184
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005185void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5186 std::string &S,
5187 const FieldDecl *FD,
5188 bool includeVBases) const {
5189 assert(RDecl && "Expected non-null RecordDecl");
5190 assert(!RDecl->isUnion() && "Should not be called for unions");
5191 if (!RDecl->getDefinition())
5192 return;
5193
5194 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5195 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5196 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5197
5198 if (CXXRec) {
5199 for (CXXRecordDecl::base_class_iterator
5200 BI = CXXRec->bases_begin(),
5201 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5202 if (!BI->isVirtual()) {
5203 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005204 if (base->isEmpty())
5205 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005206 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005207 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5208 std::make_pair(offs, base));
5209 }
5210 }
5211 }
5212
5213 unsigned i = 0;
5214 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5215 FieldEnd = RDecl->field_end();
5216 Field != FieldEnd; ++Field, ++i) {
5217 uint64_t offs = layout.getFieldOffset(i);
5218 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00005219 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005220 }
5221
5222 if (CXXRec && includeVBases) {
5223 for (CXXRecordDecl::base_class_iterator
5224 BI = CXXRec->vbases_begin(),
5225 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5226 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005227 if (base->isEmpty())
5228 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005229 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005230 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5231 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5232 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005233 }
5234 }
5235
5236 CharUnits size;
5237 if (CXXRec) {
5238 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5239 } else {
5240 size = layout.getSize();
5241 }
5242
5243 uint64_t CurOffs = 0;
5244 std::multimap<uint64_t, NamedDecl *>::iterator
5245 CurLayObj = FieldOrBaseOffsets.begin();
5246
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005247 if (CXXRec && CXXRec->isDynamicClass() &&
5248 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005249 if (FD) {
5250 S += "\"_vptr$";
5251 std::string recname = CXXRec->getNameAsString();
5252 if (recname.empty()) recname = "?";
5253 S += recname;
5254 S += '"';
5255 }
5256 S += "^^?";
5257 CurOffs += getTypeSize(VoidPtrTy);
5258 }
5259
5260 if (!RDecl->hasFlexibleArrayMember()) {
5261 // Mark the end of the structure.
5262 uint64_t offs = toBits(size);
5263 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5264 std::make_pair(offs, (NamedDecl*)0));
5265 }
5266
5267 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5268 assert(CurOffs <= CurLayObj->first);
5269
5270 if (CurOffs < CurLayObj->first) {
5271 uint64_t padding = CurLayObj->first - CurOffs;
5272 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5273 // packing/alignment of members is different that normal, in which case
5274 // the encoding will be out-of-sync with the real layout.
5275 // If the runtime switches to just consider the size of types without
5276 // taking into account alignment, we could make padding explicit in the
5277 // encoding (e.g. using arrays of chars). The encoding strings would be
5278 // longer then though.
5279 CurOffs += padding;
5280 }
5281
5282 NamedDecl *dcl = CurLayObj->second;
5283 if (dcl == 0)
5284 break; // reached end of structure.
5285
5286 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5287 // We expand the bases without their virtual bases since those are going
5288 // in the initial structure. Note that this differs from gcc which
5289 // expands virtual bases each time one is encountered in the hierarchy,
5290 // making the encoding type bigger than it really is.
5291 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005292 assert(!base->isEmpty());
5293 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005294 } else {
5295 FieldDecl *field = cast<FieldDecl>(dcl);
5296 if (FD) {
5297 S += '"';
5298 S += field->getNameAsString();
5299 S += '"';
5300 }
5301
5302 if (field->isBitField()) {
5303 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00005304 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005305 } else {
5306 QualType qt = field->getType();
5307 getLegacyIntegralTypeEncoding(qt);
5308 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5309 /*OutermostType*/false,
5310 /*EncodingProperty*/false,
5311 /*StructField*/true);
5312 CurOffs += getTypeSize(field->getType());
5313 }
5314 }
5315 }
5316}
5317
Mike Stump11289f42009-09-09 15:08:12 +00005318void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005319 std::string& S) const {
5320 if (QT & Decl::OBJC_TQ_In)
5321 S += 'n';
5322 if (QT & Decl::OBJC_TQ_Inout)
5323 S += 'N';
5324 if (QT & Decl::OBJC_TQ_Out)
5325 S += 'o';
5326 if (QT & Decl::OBJC_TQ_Bycopy)
5327 S += 'O';
5328 if (QT & Decl::OBJC_TQ_Byref)
5329 S += 'R';
5330 if (QT & Decl::OBJC_TQ_Oneway)
5331 S += 'V';
5332}
5333
Douglas Gregor3ea72692011-08-12 05:46:01 +00005334TypedefDecl *ASTContext::getObjCIdDecl() const {
5335 if (!ObjCIdDecl) {
5336 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5337 T = getObjCObjectPointerType(T);
5338 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5339 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5340 getTranslationUnitDecl(),
5341 SourceLocation(), SourceLocation(),
5342 &Idents.get("id"), IdInfo);
5343 }
5344
5345 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005346}
5347
Douglas Gregor52e02802011-08-12 06:17:30 +00005348TypedefDecl *ASTContext::getObjCSelDecl() const {
5349 if (!ObjCSelDecl) {
5350 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5351 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5352 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5353 getTranslationUnitDecl(),
5354 SourceLocation(), SourceLocation(),
5355 &Idents.get("SEL"), SelInfo);
5356 }
5357 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005358}
5359
Douglas Gregor0a586182011-08-12 05:59:41 +00005360TypedefDecl *ASTContext::getObjCClassDecl() const {
5361 if (!ObjCClassDecl) {
5362 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5363 T = getObjCObjectPointerType(T);
5364 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5365 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5366 getTranslationUnitDecl(),
5367 SourceLocation(), SourceLocation(),
5368 &Idents.get("Class"), ClassInfo);
5369 }
5370
5371 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005372}
5373
Douglas Gregord53ae832012-01-17 18:09:05 +00005374ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5375 if (!ObjCProtocolClassDecl) {
5376 ObjCProtocolClassDecl
5377 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5378 SourceLocation(),
5379 &Idents.get("Protocol"),
5380 /*PrevDecl=*/0,
5381 SourceLocation(), true);
5382 }
5383
5384 return ObjCProtocolClassDecl;
5385}
5386
Meador Inge5d3fb222012-06-16 03:34:49 +00005387//===----------------------------------------------------------------------===//
5388// __builtin_va_list Construction Functions
5389//===----------------------------------------------------------------------===//
5390
5391static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5392 // typedef char* __builtin_va_list;
5393 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5394 TypeSourceInfo *TInfo
5395 = Context->getTrivialTypeSourceInfo(CharPtrType);
5396
5397 TypedefDecl *VaListTypeDecl
5398 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5399 Context->getTranslationUnitDecl(),
5400 SourceLocation(), SourceLocation(),
5401 &Context->Idents.get("__builtin_va_list"),
5402 TInfo);
5403 return VaListTypeDecl;
5404}
5405
5406static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5407 // typedef void* __builtin_va_list;
5408 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5409 TypeSourceInfo *TInfo
5410 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5411
5412 TypedefDecl *VaListTypeDecl
5413 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5414 Context->getTranslationUnitDecl(),
5415 SourceLocation(), SourceLocation(),
5416 &Context->Idents.get("__builtin_va_list"),
5417 TInfo);
5418 return VaListTypeDecl;
5419}
5420
5421static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5422 // typedef struct __va_list_tag {
5423 RecordDecl *VaListTagDecl;
5424
5425 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5426 Context->getTranslationUnitDecl(),
5427 &Context->Idents.get("__va_list_tag"));
5428 VaListTagDecl->startDefinition();
5429
5430 const size_t NumFields = 5;
5431 QualType FieldTypes[NumFields];
5432 const char *FieldNames[NumFields];
5433
5434 // unsigned char gpr;
5435 FieldTypes[0] = Context->UnsignedCharTy;
5436 FieldNames[0] = "gpr";
5437
5438 // unsigned char fpr;
5439 FieldTypes[1] = Context->UnsignedCharTy;
5440 FieldNames[1] = "fpr";
5441
5442 // unsigned short reserved;
5443 FieldTypes[2] = Context->UnsignedShortTy;
5444 FieldNames[2] = "reserved";
5445
5446 // void* overflow_arg_area;
5447 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5448 FieldNames[3] = "overflow_arg_area";
5449
5450 // void* reg_save_area;
5451 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5452 FieldNames[4] = "reg_save_area";
5453
5454 // Create fields
5455 for (unsigned i = 0; i < NumFields; ++i) {
5456 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5457 SourceLocation(),
5458 SourceLocation(),
5459 &Context->Idents.get(FieldNames[i]),
5460 FieldTypes[i], /*TInfo=*/0,
5461 /*BitWidth=*/0,
5462 /*Mutable=*/false,
5463 ICIS_NoInit);
5464 Field->setAccess(AS_public);
5465 VaListTagDecl->addDecl(Field);
5466 }
5467 VaListTagDecl->completeDefinition();
5468 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005469 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005470
5471 // } __va_list_tag;
5472 TypedefDecl *VaListTagTypedefDecl
5473 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5474 Context->getTranslationUnitDecl(),
5475 SourceLocation(), SourceLocation(),
5476 &Context->Idents.get("__va_list_tag"),
5477 Context->getTrivialTypeSourceInfo(VaListTagType));
5478 QualType VaListTagTypedefType =
5479 Context->getTypedefType(VaListTagTypedefDecl);
5480
5481 // typedef __va_list_tag __builtin_va_list[1];
5482 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5483 QualType VaListTagArrayType
5484 = Context->getConstantArrayType(VaListTagTypedefType,
5485 Size, ArrayType::Normal, 0);
5486 TypeSourceInfo *TInfo
5487 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5488 TypedefDecl *VaListTypedefDecl
5489 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5490 Context->getTranslationUnitDecl(),
5491 SourceLocation(), SourceLocation(),
5492 &Context->Idents.get("__builtin_va_list"),
5493 TInfo);
5494
5495 return VaListTypedefDecl;
5496}
5497
5498static TypedefDecl *
5499CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5500 // typedef struct __va_list_tag {
5501 RecordDecl *VaListTagDecl;
5502 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5503 Context->getTranslationUnitDecl(),
5504 &Context->Idents.get("__va_list_tag"));
5505 VaListTagDecl->startDefinition();
5506
5507 const size_t NumFields = 4;
5508 QualType FieldTypes[NumFields];
5509 const char *FieldNames[NumFields];
5510
5511 // unsigned gp_offset;
5512 FieldTypes[0] = Context->UnsignedIntTy;
5513 FieldNames[0] = "gp_offset";
5514
5515 // unsigned fp_offset;
5516 FieldTypes[1] = Context->UnsignedIntTy;
5517 FieldNames[1] = "fp_offset";
5518
5519 // void* overflow_arg_area;
5520 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5521 FieldNames[2] = "overflow_arg_area";
5522
5523 // void* reg_save_area;
5524 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5525 FieldNames[3] = "reg_save_area";
5526
5527 // Create fields
5528 for (unsigned i = 0; i < NumFields; ++i) {
5529 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5530 VaListTagDecl,
5531 SourceLocation(),
5532 SourceLocation(),
5533 &Context->Idents.get(FieldNames[i]),
5534 FieldTypes[i], /*TInfo=*/0,
5535 /*BitWidth=*/0,
5536 /*Mutable=*/false,
5537 ICIS_NoInit);
5538 Field->setAccess(AS_public);
5539 VaListTagDecl->addDecl(Field);
5540 }
5541 VaListTagDecl->completeDefinition();
5542 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005543 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005544
5545 // } __va_list_tag;
5546 TypedefDecl *VaListTagTypedefDecl
5547 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5548 Context->getTranslationUnitDecl(),
5549 SourceLocation(), SourceLocation(),
5550 &Context->Idents.get("__va_list_tag"),
5551 Context->getTrivialTypeSourceInfo(VaListTagType));
5552 QualType VaListTagTypedefType =
5553 Context->getTypedefType(VaListTagTypedefDecl);
5554
5555 // typedef __va_list_tag __builtin_va_list[1];
5556 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5557 QualType VaListTagArrayType
5558 = Context->getConstantArrayType(VaListTagTypedefType,
5559 Size, ArrayType::Normal,0);
5560 TypeSourceInfo *TInfo
5561 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5562 TypedefDecl *VaListTypedefDecl
5563 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5564 Context->getTranslationUnitDecl(),
5565 SourceLocation(), SourceLocation(),
5566 &Context->Idents.get("__builtin_va_list"),
5567 TInfo);
5568
5569 return VaListTypedefDecl;
5570}
5571
5572static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5573 // typedef int __builtin_va_list[4];
5574 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5575 QualType IntArrayType
5576 = Context->getConstantArrayType(Context->IntTy,
5577 Size, ArrayType::Normal, 0);
5578 TypedefDecl *VaListTypedefDecl
5579 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5580 Context->getTranslationUnitDecl(),
5581 SourceLocation(), SourceLocation(),
5582 &Context->Idents.get("__builtin_va_list"),
5583 Context->getTrivialTypeSourceInfo(IntArrayType));
5584
5585 return VaListTypedefDecl;
5586}
5587
Logan Chien57086ce2012-10-10 06:56:20 +00005588static TypedefDecl *
5589CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
5590 RecordDecl *VaListDecl;
5591 if (Context->getLangOpts().CPlusPlus) {
5592 // namespace std { struct __va_list {
5593 NamespaceDecl *NS;
5594 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5595 Context->getTranslationUnitDecl(),
5596 /*Inline*/false, SourceLocation(),
5597 SourceLocation(), &Context->Idents.get("std"),
5598 /*PrevDecl*/0);
5599
5600 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5601 Context->getTranslationUnitDecl(),
5602 SourceLocation(), SourceLocation(),
5603 &Context->Idents.get("__va_list"));
5604
5605 VaListDecl->setDeclContext(NS);
5606
5607 } else {
5608 // struct __va_list {
5609 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
5610 Context->getTranslationUnitDecl(),
5611 &Context->Idents.get("__va_list"));
5612 }
5613
5614 VaListDecl->startDefinition();
5615
5616 // void * __ap;
5617 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5618 VaListDecl,
5619 SourceLocation(),
5620 SourceLocation(),
5621 &Context->Idents.get("__ap"),
5622 Context->getPointerType(Context->VoidTy),
5623 /*TInfo=*/0,
5624 /*BitWidth=*/0,
5625 /*Mutable=*/false,
5626 ICIS_NoInit);
5627 Field->setAccess(AS_public);
5628 VaListDecl->addDecl(Field);
5629
5630 // };
5631 VaListDecl->completeDefinition();
5632
5633 // typedef struct __va_list __builtin_va_list;
5634 TypeSourceInfo *TInfo
5635 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
5636
5637 TypedefDecl *VaListTypeDecl
5638 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5639 Context->getTranslationUnitDecl(),
5640 SourceLocation(), SourceLocation(),
5641 &Context->Idents.get("__builtin_va_list"),
5642 TInfo);
5643
5644 return VaListTypeDecl;
5645}
5646
Meador Inge5d3fb222012-06-16 03:34:49 +00005647static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5648 TargetInfo::BuiltinVaListKind Kind) {
5649 switch (Kind) {
5650 case TargetInfo::CharPtrBuiltinVaList:
5651 return CreateCharPtrBuiltinVaListDecl(Context);
5652 case TargetInfo::VoidPtrBuiltinVaList:
5653 return CreateVoidPtrBuiltinVaListDecl(Context);
5654 case TargetInfo::PowerABIBuiltinVaList:
5655 return CreatePowerABIBuiltinVaListDecl(Context);
5656 case TargetInfo::X86_64ABIBuiltinVaList:
5657 return CreateX86_64ABIBuiltinVaListDecl(Context);
5658 case TargetInfo::PNaClABIBuiltinVaList:
5659 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00005660 case TargetInfo::AAPCSABIBuiltinVaList:
5661 return CreateAAPCSABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00005662 }
5663
5664 llvm_unreachable("Unhandled __builtin_va_list type kind");
5665}
5666
5667TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5668 if (!BuiltinVaListDecl)
5669 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5670
5671 return BuiltinVaListDecl;
5672}
5673
Meador Ingecfb60902012-07-01 15:57:25 +00005674QualType ASTContext::getVaListTagType() const {
5675 // Force the creation of VaListTagTy by building the __builtin_va_list
5676 // declaration.
5677 if (VaListTagTy.isNull())
5678 (void) getBuiltinVaListDecl();
5679
5680 return VaListTagTy;
5681}
5682
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005683void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00005684 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00005685 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00005686
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005687 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00005688}
5689
John McCalld28ae272009-12-02 08:04:21 +00005690/// \brief Retrieve the template name that corresponds to a non-empty
5691/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00005692TemplateName
5693ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5694 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00005695 unsigned size = End - Begin;
5696 assert(size > 1 && "set is not overloaded!");
5697
5698 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5699 size * sizeof(FunctionTemplateDecl*));
5700 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5701
5702 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00005703 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00005704 NamedDecl *D = *I;
5705 assert(isa<FunctionTemplateDecl>(D) ||
5706 (isa<UsingShadowDecl>(D) &&
5707 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5708 *Storage++ = D;
5709 }
5710
5711 return TemplateName(OT);
5712}
5713
Douglas Gregordc572a32009-03-30 22:58:21 +00005714/// \brief Retrieve the template name that represents a qualified
5715/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00005716TemplateName
5717ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5718 bool TemplateKeyword,
5719 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00005720 assert(NNS && "Missing nested-name-specifier in qualified template name");
5721
Douglas Gregorc42075a2010-02-04 18:10:26 +00005722 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00005723 llvm::FoldingSetNodeID ID;
5724 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5725
5726 void *InsertPos = 0;
5727 QualifiedTemplateName *QTN =
5728 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5729 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00005730 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
5731 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00005732 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5733 }
5734
5735 return TemplateName(QTN);
5736}
5737
5738/// \brief Retrieve the template name that represents a dependent
5739/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00005740TemplateName
5741ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5742 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00005743 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00005744 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00005745
5746 llvm::FoldingSetNodeID ID;
5747 DependentTemplateName::Profile(ID, NNS, Name);
5748
5749 void *InsertPos = 0;
5750 DependentTemplateName *QTN =
5751 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5752
5753 if (QTN)
5754 return TemplateName(QTN);
5755
5756 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5757 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00005758 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5759 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00005760 } else {
5761 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00005762 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5763 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005764 DependentTemplateName *CheckQTN =
5765 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5766 assert(!CheckQTN && "Dependent type name canonicalization broken");
5767 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00005768 }
5769
5770 DependentTemplateNames.InsertNode(QTN, InsertPos);
5771 return TemplateName(QTN);
5772}
5773
Douglas Gregor71395fa2009-11-04 00:56:37 +00005774/// \brief Retrieve the template name that represents a dependent
5775/// template name such as \c MetaFun::template operator+.
5776TemplateName
5777ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00005778 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00005779 assert((!NNS || NNS->isDependent()) &&
5780 "Nested name specifier must be dependent");
5781
5782 llvm::FoldingSetNodeID ID;
5783 DependentTemplateName::Profile(ID, NNS, Operator);
5784
5785 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00005786 DependentTemplateName *QTN
5787 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005788
5789 if (QTN)
5790 return TemplateName(QTN);
5791
5792 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5793 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00005794 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5795 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005796 } else {
5797 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00005798 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5799 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005800
5801 DependentTemplateName *CheckQTN
5802 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5803 assert(!CheckQTN && "Dependent template name canonicalization broken");
5804 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00005805 }
5806
5807 DependentTemplateNames.InsertNode(QTN, InsertPos);
5808 return TemplateName(QTN);
5809}
5810
Douglas Gregor5590be02011-01-15 06:45:20 +00005811TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00005812ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5813 TemplateName replacement) const {
5814 llvm::FoldingSetNodeID ID;
5815 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5816
5817 void *insertPos = 0;
5818 SubstTemplateTemplateParmStorage *subst
5819 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5820
5821 if (!subst) {
5822 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5823 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5824 }
5825
5826 return TemplateName(subst);
5827}
5828
5829TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00005830ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5831 const TemplateArgument &ArgPack) const {
5832 ASTContext &Self = const_cast<ASTContext &>(*this);
5833 llvm::FoldingSetNodeID ID;
5834 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5835
5836 void *InsertPos = 0;
5837 SubstTemplateTemplateParmPackStorage *Subst
5838 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5839
5840 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00005841 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00005842 ArgPack.pack_size(),
5843 ArgPack.pack_begin());
5844 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5845 }
5846
5847 return TemplateName(Subst);
5848}
5849
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005850/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00005851/// TargetInfo, produce the corresponding type. The unsigned @p Type
5852/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00005853CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005854 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00005855 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005856 case TargetInfo::SignedShort: return ShortTy;
5857 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5858 case TargetInfo::SignedInt: return IntTy;
5859 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5860 case TargetInfo::SignedLong: return LongTy;
5861 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5862 case TargetInfo::SignedLongLong: return LongLongTy;
5863 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5864 }
5865
David Blaikie83d382b2011-09-23 05:06:16 +00005866 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005867}
Ted Kremenek77c51b22008-07-24 23:58:27 +00005868
5869//===----------------------------------------------------------------------===//
5870// Type Predicates.
5871//===----------------------------------------------------------------------===//
5872
Fariborz Jahanian96207692009-02-18 21:49:28 +00005873/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5874/// garbage collection attribute.
5875///
John McCall553d45a2011-01-12 00:34:59 +00005876Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005877 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00005878 return Qualifiers::GCNone;
5879
David Blaikiebbafb8a2012-03-11 07:00:24 +00005880 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00005881 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5882
5883 // Default behaviour under objective-C's gc is for ObjC pointers
5884 // (or pointers to them) be treated as though they were declared
5885 // as __strong.
5886 if (GCAttrs == Qualifiers::GCNone) {
5887 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5888 return Qualifiers::Strong;
5889 else if (Ty->isPointerType())
5890 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5891 } else {
5892 // It's not valid to set GC attributes on anything that isn't a
5893 // pointer.
5894#ifndef NDEBUG
5895 QualType CT = Ty->getCanonicalTypeInternal();
5896 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5897 CT = AT->getElementType();
5898 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5899#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00005900 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00005901 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00005902}
5903
Chris Lattner49af6a42008-04-07 06:51:04 +00005904//===----------------------------------------------------------------------===//
5905// Type Compatibility Testing
5906//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00005907
Mike Stump11289f42009-09-09 15:08:12 +00005908/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005909/// compatible.
5910static bool areCompatVectorTypes(const VectorType *LHS,
5911 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00005912 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00005913 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00005914 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00005915}
5916
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005917bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5918 QualType SecondVec) {
5919 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5920 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5921
5922 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5923 return true;
5924
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005925 // Treat Neon vector types and most AltiVec vector types as if they are the
5926 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005927 const VectorType *First = FirstVec->getAs<VectorType>();
5928 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005929 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005930 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005931 First->getVectorKind() != VectorType::AltiVecPixel &&
5932 First->getVectorKind() != VectorType::AltiVecBool &&
5933 Second->getVectorKind() != VectorType::AltiVecPixel &&
5934 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005935 return true;
5936
5937 return false;
5938}
5939
Steve Naroff8e6aee52009-07-23 01:01:38 +00005940//===----------------------------------------------------------------------===//
5941// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5942//===----------------------------------------------------------------------===//
5943
5944/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5945/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00005946bool
5947ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5948 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00005949 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005950 return true;
5951 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5952 E = rProto->protocol_end(); PI != E; ++PI)
5953 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5954 return true;
5955 return false;
5956}
5957
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00005958/// QualifiedIdConformsQualifiedId - compare id<pr,...> with id<pr1,...>
Steve Naroff8e6aee52009-07-23 01:01:38 +00005959/// return true if lhs's protocols conform to rhs's protocol; false
5960/// otherwise.
5961bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5962 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5963 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5964 return false;
5965}
5966
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00005967/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
5968/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005969bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5970 QualType rhs) {
5971 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5972 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5973 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5974
5975 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5976 E = lhsQID->qual_end(); I != E; ++I) {
5977 bool match = false;
5978 ObjCProtocolDecl *lhsProto = *I;
5979 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5980 E = rhsOPT->qual_end(); J != E; ++J) {
5981 ObjCProtocolDecl *rhsProto = *J;
5982 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5983 match = true;
5984 break;
5985 }
5986 }
5987 if (!match)
5988 return false;
5989 }
5990 return true;
5991}
5992
Steve Naroff8e6aee52009-07-23 01:01:38 +00005993/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5994/// ObjCQualifiedIDType.
5995bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5996 bool compare) {
5997 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00005998 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005999 lhs->isObjCIdType() || lhs->isObjCClassType())
6000 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006001 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006002 rhs->isObjCIdType() || rhs->isObjCClassType())
6003 return true;
6004
6005 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006006 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006007
Steve Naroff8e6aee52009-07-23 01:01:38 +00006008 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006009
Steve Naroff8e6aee52009-07-23 01:01:38 +00006010 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006011 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006012 // make sure we check the class hierarchy.
6013 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6014 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6015 E = lhsQID->qual_end(); I != E; ++I) {
6016 // when comparing an id<P> on lhs with a static type on rhs,
6017 // see if static class implements all of id's protocols, directly or
6018 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006019 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006020 return false;
6021 }
6022 }
6023 // If there are no qualifiers and no interface, we have an 'id'.
6024 return true;
6025 }
Mike Stump11289f42009-09-09 15:08:12 +00006026 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006027 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6028 E = lhsQID->qual_end(); I != E; ++I) {
6029 ObjCProtocolDecl *lhsProto = *I;
6030 bool match = false;
6031
6032 // when comparing an id<P> on lhs with a static type on rhs,
6033 // see if static class implements all of id's protocols, directly or
6034 // through its super class and categories.
6035 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6036 E = rhsOPT->qual_end(); J != E; ++J) {
6037 ObjCProtocolDecl *rhsProto = *J;
6038 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6039 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6040 match = true;
6041 break;
6042 }
6043 }
Mike Stump11289f42009-09-09 15:08:12 +00006044 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006045 // make sure we check the class hierarchy.
6046 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6047 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6048 E = lhsQID->qual_end(); I != E; ++I) {
6049 // when comparing an id<P> on lhs with a static type on rhs,
6050 // see if static class implements all of id's protocols, directly or
6051 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006052 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006053 match = true;
6054 break;
6055 }
6056 }
6057 }
6058 if (!match)
6059 return false;
6060 }
Mike Stump11289f42009-09-09 15:08:12 +00006061
Steve Naroff8e6aee52009-07-23 01:01:38 +00006062 return true;
6063 }
Mike Stump11289f42009-09-09 15:08:12 +00006064
Steve Naroff8e6aee52009-07-23 01:01:38 +00006065 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6066 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6067
Mike Stump11289f42009-09-09 15:08:12 +00006068 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006069 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006070 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006071 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6072 E = lhsOPT->qual_end(); I != E; ++I) {
6073 ObjCProtocolDecl *lhsProto = *I;
6074 bool match = false;
6075
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006076 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006077 // see if static class implements all of id's protocols, directly or
6078 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006079 // First, lhs protocols in the qualifier list must be found, direct
6080 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006081 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6082 E = rhsQID->qual_end(); J != E; ++J) {
6083 ObjCProtocolDecl *rhsProto = *J;
6084 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6085 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6086 match = true;
6087 break;
6088 }
6089 }
6090 if (!match)
6091 return false;
6092 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006093
6094 // Static class's protocols, or its super class or category protocols
6095 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6096 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6097 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6098 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6099 // This is rather dubious but matches gcc's behavior. If lhs has
6100 // no type qualifier and its class has no static protocol(s)
6101 // assume that it is mismatch.
6102 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6103 return false;
6104 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6105 LHSInheritedProtocols.begin(),
6106 E = LHSInheritedProtocols.end(); I != E; ++I) {
6107 bool match = false;
6108 ObjCProtocolDecl *lhsProto = (*I);
6109 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6110 E = rhsQID->qual_end(); J != E; ++J) {
6111 ObjCProtocolDecl *rhsProto = *J;
6112 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6113 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6114 match = true;
6115 break;
6116 }
6117 }
6118 if (!match)
6119 return false;
6120 }
6121 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006122 return true;
6123 }
6124 return false;
6125}
6126
Eli Friedman47f77112008-08-22 00:56:42 +00006127/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006128/// compatible for assignment from RHS to LHS. This handles validation of any
6129/// protocol qualifiers on the LHS or RHS.
6130///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006131bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6132 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006133 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6134 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6135
Steve Naroff1329fa02009-07-15 18:40:39 +00006136 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006137 if (LHS->isObjCUnqualifiedIdOrClass() ||
6138 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006139 return true;
6140
John McCall8b07ec22010-05-15 11:32:37 +00006141 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006142 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6143 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006144 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006145
6146 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6147 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6148 QualType(RHSOPT,0));
6149
John McCall8b07ec22010-05-15 11:32:37 +00006150 // If we have 2 user-defined types, fall into that path.
6151 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006152 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006153
Steve Naroff8e6aee52009-07-23 01:01:38 +00006154 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006155}
6156
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006157/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006158/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006159/// arguments in block literals. When passed as arguments, passing 'A*' where
6160/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6161/// not OK. For the return type, the opposite is not OK.
6162bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6163 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006164 const ObjCObjectPointerType *RHSOPT,
6165 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006166 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006167 return true;
6168
6169 if (LHSOPT->isObjCBuiltinType()) {
6170 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6171 }
6172
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006173 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006174 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6175 QualType(RHSOPT,0),
6176 false);
6177
6178 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6179 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6180 if (LHS && RHS) { // We have 2 user-defined types.
6181 if (LHS != RHS) {
6182 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006183 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006184 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006185 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006186 }
6187 else
6188 return true;
6189 }
6190 return false;
6191}
6192
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006193/// getIntersectionOfProtocols - This routine finds the intersection of set
6194/// of protocols inherited from two distinct objective-c pointer objects.
6195/// It is used to build composite qualifier list of the composite type of
6196/// the conditional expression involving two objective-c pointer objects.
6197static
6198void getIntersectionOfProtocols(ASTContext &Context,
6199 const ObjCObjectPointerType *LHSOPT,
6200 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006201 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006202
John McCall8b07ec22010-05-15 11:32:37 +00006203 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6204 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6205 assert(LHS->getInterface() && "LHS must have an interface base");
6206 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006207
6208 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6209 unsigned LHSNumProtocols = LHS->getNumProtocols();
6210 if (LHSNumProtocols > 0)
6211 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6212 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006213 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006214 Context.CollectInheritedProtocols(LHS->getInterface(),
6215 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006216 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6217 LHSInheritedProtocols.end());
6218 }
6219
6220 unsigned RHSNumProtocols = RHS->getNumProtocols();
6221 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006222 ObjCProtocolDecl **RHSProtocols =
6223 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006224 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6225 if (InheritedProtocolSet.count(RHSProtocols[i]))
6226 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006227 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006228 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006229 Context.CollectInheritedProtocols(RHS->getInterface(),
6230 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006231 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6232 RHSInheritedProtocols.begin(),
6233 E = RHSInheritedProtocols.end(); I != E; ++I)
6234 if (InheritedProtocolSet.count((*I)))
6235 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006236 }
6237}
6238
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006239/// areCommonBaseCompatible - Returns common base class of the two classes if
6240/// one found. Note that this is O'2 algorithm. But it will be called as the
6241/// last type comparison in a ?-exp of ObjC pointer types before a
6242/// warning is issued. So, its invokation is extremely rare.
6243QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006244 const ObjCObjectPointerType *Lptr,
6245 const ObjCObjectPointerType *Rptr) {
6246 const ObjCObjectType *LHS = Lptr->getObjectType();
6247 const ObjCObjectType *RHS = Rptr->getObjectType();
6248 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6249 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006250 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006251 return QualType();
6252
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006253 do {
John McCall8b07ec22010-05-15 11:32:37 +00006254 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006255 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006256 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006257 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6258
6259 QualType Result = QualType(LHS, 0);
6260 if (!Protocols.empty())
6261 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6262 Result = getObjCObjectPointerType(Result);
6263 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006264 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006265 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006266
6267 return QualType();
6268}
6269
John McCall8b07ec22010-05-15 11:32:37 +00006270bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6271 const ObjCObjectType *RHS) {
6272 assert(LHS->getInterface() && "LHS is not an interface type");
6273 assert(RHS->getInterface() && "RHS is not an interface type");
6274
Chris Lattner49af6a42008-04-07 06:51:04 +00006275 // Verify that the base decls are compatible: the RHS must be a subclass of
6276 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006277 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006278 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006279
Chris Lattner49af6a42008-04-07 06:51:04 +00006280 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6281 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006282 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006283 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006284
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006285 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6286 // more detailed analysis is required.
6287 if (RHS->getNumProtocols() == 0) {
6288 // OK, if LHS is a superclass of RHS *and*
6289 // this superclass is assignment compatible with LHS.
6290 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006291 bool IsSuperClass =
6292 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6293 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006294 // OK if conversion of LHS to SuperClass results in narrowing of types
6295 // ; i.e., SuperClass may implement at least one of the protocols
6296 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6297 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6298 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006299 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006300 // If super class has no protocols, it is not a match.
6301 if (SuperClassInheritedProtocols.empty())
6302 return false;
6303
6304 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6305 LHSPE = LHS->qual_end();
6306 LHSPI != LHSPE; LHSPI++) {
6307 bool SuperImplementsProtocol = false;
6308 ObjCProtocolDecl *LHSProto = (*LHSPI);
6309
6310 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6311 SuperClassInheritedProtocols.begin(),
6312 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6313 ObjCProtocolDecl *SuperClassProto = (*I);
6314 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6315 SuperImplementsProtocol = true;
6316 break;
6317 }
6318 }
6319 if (!SuperImplementsProtocol)
6320 return false;
6321 }
6322 return true;
6323 }
6324 return false;
6325 }
Mike Stump11289f42009-09-09 15:08:12 +00006326
John McCall8b07ec22010-05-15 11:32:37 +00006327 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6328 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00006329 LHSPI != LHSPE; LHSPI++) {
6330 bool RHSImplementsProtocol = false;
6331
6332 // If the RHS doesn't implement the protocol on the left, the types
6333 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00006334 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6335 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00006336 RHSPI != RHSPE; RHSPI++) {
6337 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006338 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00006339 break;
6340 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006341 }
6342 // FIXME: For better diagnostics, consider passing back the protocol name.
6343 if (!RHSImplementsProtocol)
6344 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006345 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006346 // The RHS implements all protocols listed on the LHS.
6347 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006348}
6349
Steve Naroffb7605152009-02-12 17:52:19 +00006350bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6351 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006352 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6353 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006354
Steve Naroff7cae42b2009-07-10 23:34:53 +00006355 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006356 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006357
6358 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6359 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006360}
6361
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006362bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6363 return canAssignObjCInterfaces(
6364 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6365 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6366}
6367
Mike Stump11289f42009-09-09 15:08:12 +00006368/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006369/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006370/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006371/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006372bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6373 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006374 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006375 return hasSameType(LHS, RHS);
6376
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006377 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006378}
6379
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006380bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006381 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006382}
6383
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006384bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6385 return !mergeTypes(LHS, RHS, true).isNull();
6386}
6387
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006388/// mergeTransparentUnionType - if T is a transparent union type and a member
6389/// of T is compatible with SubType, return the merged type, else return
6390/// QualType()
6391QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6392 bool OfBlockPointer,
6393 bool Unqualified) {
6394 if (const RecordType *UT = T->getAsUnionType()) {
6395 RecordDecl *UD = UT->getDecl();
6396 if (UD->hasAttr<TransparentUnionAttr>()) {
6397 for (RecordDecl::field_iterator it = UD->field_begin(),
6398 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00006399 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006400 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6401 if (!MT.isNull())
6402 return MT;
6403 }
6404 }
6405 }
6406
6407 return QualType();
6408}
6409
6410/// mergeFunctionArgumentTypes - merge two types which appear as function
6411/// argument types
6412QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6413 bool OfBlockPointer,
6414 bool Unqualified) {
6415 // GNU extension: two types are compatible if they appear as a function
6416 // argument, one of the types is a transparent union type and the other
6417 // type is compatible with a union member
6418 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6419 Unqualified);
6420 if (!lmerge.isNull())
6421 return lmerge;
6422
6423 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6424 Unqualified);
6425 if (!rmerge.isNull())
6426 return rmerge;
6427
6428 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6429}
6430
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006431QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006432 bool OfBlockPointer,
6433 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006434 const FunctionType *lbase = lhs->getAs<FunctionType>();
6435 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006436 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6437 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006438 bool allLTypes = true;
6439 bool allRTypes = true;
6440
6441 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006442 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006443 if (OfBlockPointer) {
6444 QualType RHS = rbase->getResultType();
6445 QualType LHS = lbase->getResultType();
6446 bool UnqualifiedResult = Unqualified;
6447 if (!UnqualifiedResult)
6448 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006449 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006450 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006451 else
John McCall8c6b56f2010-12-15 01:06:38 +00006452 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6453 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006454 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006455
6456 if (Unqualified)
6457 retType = retType.getUnqualifiedType();
6458
6459 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6460 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6461 if (Unqualified) {
6462 LRetType = LRetType.getUnqualifiedType();
6463 RRetType = RRetType.getUnqualifiedType();
6464 }
6465
6466 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006467 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006468 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006469 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006470
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006471 // FIXME: double check this
6472 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6473 // rbase->getRegParmAttr() != 0 &&
6474 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006475 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6476 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006477
Douglas Gregor8c940862010-01-18 17:14:39 +00006478 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00006479 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00006480 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006481
John McCall8c6b56f2010-12-15 01:06:38 +00006482 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006483 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6484 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006485 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6486 return QualType();
6487
John McCall31168b02011-06-15 23:02:42 +00006488 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6489 return QualType();
6490
John McCall8c6b56f2010-12-15 01:06:38 +00006491 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6492 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006493
Rafael Espindola8778c282012-11-29 16:09:03 +00006494 if (lbaseInfo.getNoReturn() != NoReturn)
6495 allLTypes = false;
6496 if (rbaseInfo.getNoReturn() != NoReturn)
6497 allRTypes = false;
6498
John McCall31168b02011-06-15 23:02:42 +00006499 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006500
Eli Friedman47f77112008-08-22 00:56:42 +00006501 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006502 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6503 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006504 unsigned lproto_nargs = lproto->getNumArgs();
6505 unsigned rproto_nargs = rproto->getNumArgs();
6506
6507 // Compatible functions must have the same number of arguments
6508 if (lproto_nargs != rproto_nargs)
6509 return QualType();
6510
6511 // Variadic and non-variadic functions aren't compatible
6512 if (lproto->isVariadic() != rproto->isVariadic())
6513 return QualType();
6514
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006515 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6516 return QualType();
6517
Fariborz Jahanian97676972011-09-28 21:52:05 +00006518 if (LangOpts.ObjCAutoRefCount &&
6519 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6520 return QualType();
6521
Eli Friedman47f77112008-08-22 00:56:42 +00006522 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006523 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00006524 for (unsigned i = 0; i < lproto_nargs; i++) {
6525 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6526 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006527 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6528 OfBlockPointer,
6529 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006530 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006531
6532 if (Unqualified)
6533 argtype = argtype.getUnqualifiedType();
6534
Eli Friedman47f77112008-08-22 00:56:42 +00006535 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006536 if (Unqualified) {
6537 largtype = largtype.getUnqualifiedType();
6538 rargtype = rargtype.getUnqualifiedType();
6539 }
6540
Chris Lattner465fa322008-10-05 17:34:18 +00006541 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6542 allLTypes = false;
6543 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6544 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006545 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006546
Eli Friedman47f77112008-08-22 00:56:42 +00006547 if (allLTypes) return lhs;
6548 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006549
6550 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6551 EPI.ExtInfo = einfo;
6552 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006553 }
6554
6555 if (lproto) allRTypes = false;
6556 if (rproto) allLTypes = false;
6557
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006558 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006559 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006560 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006561 if (proto->isVariadic()) return QualType();
6562 // Check that the types are compatible with the types that
6563 // would result from default argument promotions (C99 6.7.5.3p15).
6564 // The only types actually affected are promotable integer
6565 // types and floats, which would be passed as a different
6566 // type depending on whether the prototype is visible.
6567 unsigned proto_nargs = proto->getNumArgs();
6568 for (unsigned i = 0; i < proto_nargs; ++i) {
6569 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00006570
Eli Friedman448ce402012-08-30 00:44:15 +00006571 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00006572 // to pass enum values.
Eli Friedman448ce402012-08-30 00:44:15 +00006573 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
6574 argTy = Enum->getDecl()->getIntegerType();
6575 if (argTy.isNull())
6576 return QualType();
6577 }
Douglas Gregor2973d402010-02-03 19:27:29 +00006578
Eli Friedman47f77112008-08-22 00:56:42 +00006579 if (argTy->isPromotableIntegerType() ||
6580 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6581 return QualType();
6582 }
6583
6584 if (allLTypes) return lhs;
6585 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006586
6587 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6588 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00006589 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006590 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006591 }
6592
6593 if (allLTypes) return lhs;
6594 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00006595 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00006596}
6597
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006598QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006599 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006600 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00006601 // C++ [expr]: If an expression initially has the type "reference to T", the
6602 // type is adjusted to "T" prior to any further analysis, the expression
6603 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006604 // expression is an lvalue unless the reference is an rvalue reference and
6605 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00006606 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6607 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006608
6609 if (Unqualified) {
6610 LHS = LHS.getUnqualifiedType();
6611 RHS = RHS.getUnqualifiedType();
6612 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00006613
Eli Friedman47f77112008-08-22 00:56:42 +00006614 QualType LHSCan = getCanonicalType(LHS),
6615 RHSCan = getCanonicalType(RHS);
6616
6617 // If two types are identical, they are compatible.
6618 if (LHSCan == RHSCan)
6619 return LHS;
6620
John McCall8ccfcb52009-09-24 19:53:00 +00006621 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006622 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6623 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00006624 if (LQuals != RQuals) {
6625 // If any of these qualifiers are different, we have a type
6626 // mismatch.
6627 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00006628 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6629 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00006630 return QualType();
6631
6632 // Exactly one GC qualifier difference is allowed: __strong is
6633 // okay if the other type has no GC qualifier but is an Objective
6634 // C object pointer (i.e. implicitly strong by default). We fix
6635 // this by pretending that the unqualified type was actually
6636 // qualified __strong.
6637 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6638 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6639 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6640
6641 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6642 return QualType();
6643
6644 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6645 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6646 }
6647 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6648 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6649 }
Eli Friedman47f77112008-08-22 00:56:42 +00006650 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00006651 }
6652
6653 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00006654
Eli Friedmandcca6332009-06-01 01:22:52 +00006655 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6656 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00006657
Chris Lattnerfd652912008-01-14 05:45:46 +00006658 // We want to consider the two function types to be the same for these
6659 // comparisons, just force one to the other.
6660 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6661 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00006662
6663 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00006664 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6665 LHSClass = Type::ConstantArray;
6666 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6667 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00006668
John McCall8b07ec22010-05-15 11:32:37 +00006669 // ObjCInterfaces are just specialized ObjCObjects.
6670 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6671 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6672
Nate Begemance4d7fc2008-04-18 23:10:10 +00006673 // Canonicalize ExtVector -> Vector.
6674 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6675 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00006676
Chris Lattner95554662008-04-07 05:43:21 +00006677 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006678 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00006679 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00006680 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00006681 // Compatibility is based on the underlying type, not the promotion
6682 // type.
John McCall9dd450b2009-09-21 23:43:11 +00006683 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006684 QualType TINT = ETy->getDecl()->getIntegerType();
6685 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006686 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006687 }
John McCall9dd450b2009-09-21 23:43:11 +00006688 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006689 QualType TINT = ETy->getDecl()->getIntegerType();
6690 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006691 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006692 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006693 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00006694 if (OfBlockPointer && !BlockReturnType) {
6695 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6696 return LHS;
6697 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6698 return RHS;
6699 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006700
Eli Friedman47f77112008-08-22 00:56:42 +00006701 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00006702 }
Eli Friedman47f77112008-08-22 00:56:42 +00006703
Steve Naroffc6edcbd2008-01-09 22:43:08 +00006704 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006705 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006706#define TYPE(Class, Base)
6707#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00006708#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006709#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6710#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6711#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00006712 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006713
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006714 case Type::LValueReference:
6715 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006716 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00006717 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006718
John McCall8b07ec22010-05-15 11:32:37 +00006719 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006720 case Type::IncompleteArray:
6721 case Type::VariableArray:
6722 case Type::FunctionProto:
6723 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00006724 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006725
Chris Lattnerfd652912008-01-14 05:45:46 +00006726 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00006727 {
6728 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006729 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6730 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006731 if (Unqualified) {
6732 LHSPointee = LHSPointee.getUnqualifiedType();
6733 RHSPointee = RHSPointee.getUnqualifiedType();
6734 }
6735 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6736 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006737 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00006738 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006739 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00006740 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006741 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006742 return getPointerType(ResultType);
6743 }
Steve Naroff68e167d2008-12-10 17:49:55 +00006744 case Type::BlockPointer:
6745 {
6746 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006747 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6748 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006749 if (Unqualified) {
6750 LHSPointee = LHSPointee.getUnqualifiedType();
6751 RHSPointee = RHSPointee.getUnqualifiedType();
6752 }
6753 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6754 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00006755 if (ResultType.isNull()) return QualType();
6756 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6757 return LHS;
6758 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6759 return RHS;
6760 return getBlockPointerType(ResultType);
6761 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00006762 case Type::Atomic:
6763 {
6764 // Merge two pointer types, while trying to preserve typedef info
6765 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6766 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6767 if (Unqualified) {
6768 LHSValue = LHSValue.getUnqualifiedType();
6769 RHSValue = RHSValue.getUnqualifiedType();
6770 }
6771 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6772 Unqualified);
6773 if (ResultType.isNull()) return QualType();
6774 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6775 return LHS;
6776 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6777 return RHS;
6778 return getAtomicType(ResultType);
6779 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006780 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00006781 {
6782 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6783 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6784 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6785 return QualType();
6786
6787 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6788 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006789 if (Unqualified) {
6790 LHSElem = LHSElem.getUnqualifiedType();
6791 RHSElem = RHSElem.getUnqualifiedType();
6792 }
6793
6794 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006795 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00006796 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6797 return LHS;
6798 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6799 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00006800 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6801 ArrayType::ArraySizeModifier(), 0);
6802 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6803 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006804 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6805 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00006806 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6807 return LHS;
6808 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6809 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006810 if (LVAT) {
6811 // FIXME: This isn't correct! But tricky to implement because
6812 // the array's size has to be the size of LHS, but the type
6813 // has to be different.
6814 return LHS;
6815 }
6816 if (RVAT) {
6817 // FIXME: This isn't correct! But tricky to implement because
6818 // the array's size has to be the size of RHS, but the type
6819 // has to be different.
6820 return RHS;
6821 }
Eli Friedman3e62c212008-08-22 01:48:21 +00006822 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6823 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00006824 return getIncompleteArrayType(ResultType,
6825 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006826 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006827 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006828 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006829 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006830 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00006831 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00006832 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006833 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00006834 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00006835 case Type::Complex:
6836 // Distinct complex types are incompatible.
6837 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006838 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00006839 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00006840 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6841 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00006842 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00006843 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00006844 case Type::ObjCObject: {
6845 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00006846 // FIXME: This should be type compatibility, e.g. whether
6847 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00006848 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6849 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6850 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00006851 return LHS;
6852
Eli Friedman47f77112008-08-22 00:56:42 +00006853 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00006854 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006855 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006856 if (OfBlockPointer) {
6857 if (canAssignObjCInterfacesInBlockPointer(
6858 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006859 RHS->getAs<ObjCObjectPointerType>(),
6860 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00006861 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006862 return QualType();
6863 }
John McCall9dd450b2009-09-21 23:43:11 +00006864 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6865 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006866 return LHS;
6867
Steve Naroffc68cfcf2008-12-10 22:14:21 +00006868 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00006869 }
Steve Naroff32e44c02007-10-15 20:41:53 +00006870 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006871
David Blaikie8a40f702012-01-17 06:56:22 +00006872 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00006873}
Ted Kremenekfc581a92007-10-31 17:10:13 +00006874
Fariborz Jahanian97676972011-09-28 21:52:05 +00006875bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6876 const FunctionProtoType *FromFunctionType,
6877 const FunctionProtoType *ToFunctionType) {
6878 if (FromFunctionType->hasAnyConsumedArgs() !=
6879 ToFunctionType->hasAnyConsumedArgs())
6880 return false;
6881 FunctionProtoType::ExtProtoInfo FromEPI =
6882 FromFunctionType->getExtProtoInfo();
6883 FunctionProtoType::ExtProtoInfo ToEPI =
6884 ToFunctionType->getExtProtoInfo();
6885 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6886 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6887 ArgIdx != NumArgs; ++ArgIdx) {
6888 if (FromEPI.ConsumedArguments[ArgIdx] !=
6889 ToEPI.ConsumedArguments[ArgIdx])
6890 return false;
6891 }
6892 return true;
6893}
6894
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006895/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6896/// 'RHS' attributes and returns the merged version; including for function
6897/// return types.
6898QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6899 QualType LHSCan = getCanonicalType(LHS),
6900 RHSCan = getCanonicalType(RHS);
6901 // If two types are identical, they are compatible.
6902 if (LHSCan == RHSCan)
6903 return LHS;
6904 if (RHSCan->isFunctionType()) {
6905 if (!LHSCan->isFunctionType())
6906 return QualType();
6907 QualType OldReturnType =
6908 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6909 QualType NewReturnType =
6910 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6911 QualType ResReturnType =
6912 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6913 if (ResReturnType.isNull())
6914 return QualType();
6915 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6916 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6917 // In either case, use OldReturnType to build the new function type.
6918 const FunctionType *F = LHS->getAs<FunctionType>();
6919 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00006920 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6921 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006922 QualType ResultType
6923 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006924 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006925 return ResultType;
6926 }
6927 }
6928 return QualType();
6929 }
6930
6931 // If the qualifiers are different, the types can still be merged.
6932 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6933 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6934 if (LQuals != RQuals) {
6935 // If any of these qualifiers are different, we have a type mismatch.
6936 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6937 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6938 return QualType();
6939
6940 // Exactly one GC qualifier difference is allowed: __strong is
6941 // okay if the other type has no GC qualifier but is an Objective
6942 // C object pointer (i.e. implicitly strong by default). We fix
6943 // this by pretending that the unqualified type was actually
6944 // qualified __strong.
6945 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6946 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6947 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6948
6949 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6950 return QualType();
6951
6952 if (GC_L == Qualifiers::Strong)
6953 return LHS;
6954 if (GC_R == Qualifiers::Strong)
6955 return RHS;
6956 return QualType();
6957 }
6958
6959 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6960 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6961 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6962 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6963 if (ResQT == LHSBaseQT)
6964 return LHS;
6965 if (ResQT == RHSBaseQT)
6966 return RHS;
6967 }
6968 return QualType();
6969}
6970
Chris Lattner4ba0cef2008-04-07 07:01:58 +00006971//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006972// Integer Predicates
6973//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00006974
Jay Foad39c79802011-01-12 09:06:06 +00006975unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00006976 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00006977 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00006978 if (T->isBooleanType())
6979 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00006980 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006981 return (unsigned)getTypeSize(T);
6982}
6983
Abramo Bagnara13640492012-09-09 10:21:24 +00006984QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006985 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00006986
6987 // Turn <4 x signed int> -> <4 x unsigned int>
6988 if (const VectorType *VTy = T->getAs<VectorType>())
6989 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00006990 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00006991
6992 // For enums, we return the unsigned version of the base type.
6993 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006994 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00006995
6996 const BuiltinType *BTy = T->getAs<BuiltinType>();
6997 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006998 switch (BTy->getKind()) {
6999 case BuiltinType::Char_S:
7000 case BuiltinType::SChar:
7001 return UnsignedCharTy;
7002 case BuiltinType::Short:
7003 return UnsignedShortTy;
7004 case BuiltinType::Int:
7005 return UnsignedIntTy;
7006 case BuiltinType::Long:
7007 return UnsignedLongTy;
7008 case BuiltinType::LongLong:
7009 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007010 case BuiltinType::Int128:
7011 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007012 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007013 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007014 }
7015}
7016
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007017ASTMutationListener::~ASTMutationListener() { }
7018
Chris Lattnerecd79c62009-06-14 00:45:47 +00007019
7020//===----------------------------------------------------------------------===//
7021// Builtin Type Computation
7022//===----------------------------------------------------------------------===//
7023
7024/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007025/// pointer over the consumed characters. This returns the resultant type. If
7026/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7027/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7028/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007029///
7030/// RequiresICE is filled in on return to indicate whether the value is required
7031/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007032static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007033 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007034 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007035 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007036 // Modifiers.
7037 int HowLong = 0;
7038 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007039 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007040
Chris Lattnerdc226c22010-10-01 22:42:38 +00007041 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007042 bool Done = false;
7043 while (!Done) {
7044 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007045 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007046 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007047 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007048 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007049 case 'S':
7050 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7051 assert(!Signed && "Can't use 'S' modifier multiple times!");
7052 Signed = true;
7053 break;
7054 case 'U':
7055 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7056 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7057 Unsigned = true;
7058 break;
7059 case 'L':
7060 assert(HowLong <= 2 && "Can't have LLLL modifier");
7061 ++HowLong;
7062 break;
7063 }
7064 }
7065
7066 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007067
Chris Lattnerecd79c62009-06-14 00:45:47 +00007068 // Read the base type.
7069 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007070 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007071 case 'v':
7072 assert(HowLong == 0 && !Signed && !Unsigned &&
7073 "Bad modifiers used with 'v'!");
7074 Type = Context.VoidTy;
7075 break;
7076 case 'f':
7077 assert(HowLong == 0 && !Signed && !Unsigned &&
7078 "Bad modifiers used with 'f'!");
7079 Type = Context.FloatTy;
7080 break;
7081 case 'd':
7082 assert(HowLong < 2 && !Signed && !Unsigned &&
7083 "Bad modifiers used with 'd'!");
7084 if (HowLong)
7085 Type = Context.LongDoubleTy;
7086 else
7087 Type = Context.DoubleTy;
7088 break;
7089 case 's':
7090 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7091 if (Unsigned)
7092 Type = Context.UnsignedShortTy;
7093 else
7094 Type = Context.ShortTy;
7095 break;
7096 case 'i':
7097 if (HowLong == 3)
7098 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7099 else if (HowLong == 2)
7100 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7101 else if (HowLong == 1)
7102 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7103 else
7104 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7105 break;
7106 case 'c':
7107 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7108 if (Signed)
7109 Type = Context.SignedCharTy;
7110 else if (Unsigned)
7111 Type = Context.UnsignedCharTy;
7112 else
7113 Type = Context.CharTy;
7114 break;
7115 case 'b': // boolean
7116 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7117 Type = Context.BoolTy;
7118 break;
7119 case 'z': // size_t.
7120 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7121 Type = Context.getSizeType();
7122 break;
7123 case 'F':
7124 Type = Context.getCFConstantStringType();
7125 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007126 case 'G':
7127 Type = Context.getObjCIdType();
7128 break;
7129 case 'H':
7130 Type = Context.getObjCSelType();
7131 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007132 case 'a':
7133 Type = Context.getBuiltinVaListType();
7134 assert(!Type.isNull() && "builtin va list type not initialized!");
7135 break;
7136 case 'A':
7137 // This is a "reference" to a va_list; however, what exactly
7138 // this means depends on how va_list is defined. There are two
7139 // different kinds of va_list: ones passed by value, and ones
7140 // passed by reference. An example of a by-value va_list is
7141 // x86, where va_list is a char*. An example of by-ref va_list
7142 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7143 // we want this argument to be a char*&; for x86-64, we want
7144 // it to be a __va_list_tag*.
7145 Type = Context.getBuiltinVaListType();
7146 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007147 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007148 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007149 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007150 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007151 break;
7152 case 'V': {
7153 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007154 unsigned NumElements = strtoul(Str, &End, 10);
7155 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007156 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007157
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007158 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7159 RequiresICE, false);
7160 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007161
7162 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007163 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007164 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007165 break;
7166 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007167 case 'E': {
7168 char *End;
7169
7170 unsigned NumElements = strtoul(Str, &End, 10);
7171 assert(End != Str && "Missing vector size");
7172
7173 Str = End;
7174
7175 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7176 false);
7177 Type = Context.getExtVectorType(ElementType, NumElements);
7178 break;
7179 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007180 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007181 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7182 false);
7183 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007184 Type = Context.getComplexType(ElementType);
7185 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007186 }
7187 case 'Y' : {
7188 Type = Context.getPointerDiffType();
7189 break;
7190 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007191 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007192 Type = Context.getFILEType();
7193 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007194 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007195 return QualType();
7196 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007197 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007198 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007199 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007200 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007201 else
7202 Type = Context.getjmp_bufType();
7203
Mike Stump2adb4da2009-07-28 23:47:15 +00007204 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007205 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007206 return QualType();
7207 }
7208 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007209 case 'K':
7210 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7211 Type = Context.getucontext_tType();
7212
7213 if (Type.isNull()) {
7214 Error = ASTContext::GE_Missing_ucontext;
7215 return QualType();
7216 }
7217 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00007218 case 'p':
7219 Type = Context.getProcessIDType();
7220 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007221 }
Mike Stump11289f42009-09-09 15:08:12 +00007222
Chris Lattnerdc226c22010-10-01 22:42:38 +00007223 // If there are modifiers and if we're allowed to parse them, go for it.
7224 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007225 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007226 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007227 default: Done = true; --Str; break;
7228 case '*':
7229 case '&': {
7230 // Both pointers and references can have their pointee types
7231 // qualified with an address space.
7232 char *End;
7233 unsigned AddrSpace = strtoul(Str, &End, 10);
7234 if (End != Str && AddrSpace != 0) {
7235 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7236 Str = End;
7237 }
7238 if (c == '*')
7239 Type = Context.getPointerType(Type);
7240 else
7241 Type = Context.getLValueReferenceType(Type);
7242 break;
7243 }
7244 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7245 case 'C':
7246 Type = Type.withConst();
7247 break;
7248 case 'D':
7249 Type = Context.getVolatileType(Type);
7250 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007251 case 'R':
7252 Type = Type.withRestrict();
7253 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007254 }
7255 }
Chris Lattner84733392010-10-01 07:13:18 +00007256
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007257 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007258 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007259
Chris Lattnerecd79c62009-06-14 00:45:47 +00007260 return Type;
7261}
7262
7263/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007264QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007265 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007266 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007267 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007268
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007269 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007270
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007271 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007272 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007273 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7274 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007275 if (Error != GE_None)
7276 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007277
7278 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7279
Chris Lattnerecd79c62009-06-14 00:45:47 +00007280 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007281 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007282 if (Error != GE_None)
7283 return QualType();
7284
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007285 // If this argument is required to be an IntegerConstantExpression and the
7286 // caller cares, fill in the bitmask we return.
7287 if (RequiresICE && IntegerConstantArgs)
7288 *IntegerConstantArgs |= 1 << ArgTypes.size();
7289
Chris Lattnerecd79c62009-06-14 00:45:47 +00007290 // Do array -> pointer decay. The builtin should use the decayed type.
7291 if (Ty->isArrayType())
7292 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007293
Chris Lattnerecd79c62009-06-14 00:45:47 +00007294 ArgTypes.push_back(Ty);
7295 }
7296
7297 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7298 "'.' should only occur at end of builtin type list!");
7299
John McCall991eb4b2010-12-21 00:44:39 +00007300 FunctionType::ExtInfo EI;
7301 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7302
7303 bool Variadic = (TypeStr[0] == '.');
7304
7305 // We really shouldn't be making a no-proto type here, especially in C++.
7306 if (ArgTypes.empty() && Variadic)
7307 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007308
John McCalldb40c7f2010-12-14 08:05:40 +00007309 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007310 EPI.ExtInfo = EI;
7311 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007312
7313 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007314}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007315
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007316GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
7317 GVALinkage External = GVA_StrongExternal;
7318
7319 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007320 switch (L) {
7321 case NoLinkage:
7322 case InternalLinkage:
7323 case UniqueExternalLinkage:
7324 return GVA_Internal;
7325
7326 case ExternalLinkage:
7327 switch (FD->getTemplateSpecializationKind()) {
7328 case TSK_Undeclared:
7329 case TSK_ExplicitSpecialization:
7330 External = GVA_StrongExternal;
7331 break;
7332
7333 case TSK_ExplicitInstantiationDefinition:
7334 return GVA_ExplicitTemplateInstantiation;
7335
7336 case TSK_ExplicitInstantiationDeclaration:
7337 case TSK_ImplicitInstantiation:
7338 External = GVA_TemplateInstantiation;
7339 break;
7340 }
7341 }
7342
7343 if (!FD->isInlined())
7344 return External;
7345
David Blaikiebbafb8a2012-03-11 07:00:24 +00007346 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007347 // GNU or C99 inline semantics. Determine whether this symbol should be
7348 // externally visible.
7349 if (FD->isInlineDefinitionExternallyVisible())
7350 return External;
7351
7352 // C99 inline semantics, where the symbol is not externally visible.
7353 return GVA_C99Inline;
7354 }
7355
7356 // C++0x [temp.explicit]p9:
7357 // [ Note: The intent is that an inline function that is the subject of
7358 // an explicit instantiation declaration will still be implicitly
7359 // instantiated when used so that the body can be considered for
7360 // inlining, but that no out-of-line copy of the inline function would be
7361 // generated in the translation unit. -- end note ]
7362 if (FD->getTemplateSpecializationKind()
7363 == TSK_ExplicitInstantiationDeclaration)
7364 return GVA_C99Inline;
7365
7366 return GVA_CXXInline;
7367}
7368
7369GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7370 // If this is a static data member, compute the kind of template
7371 // specialization. Otherwise, this variable is not part of a
7372 // template.
7373 TemplateSpecializationKind TSK = TSK_Undeclared;
7374 if (VD->isStaticDataMember())
7375 TSK = VD->getTemplateSpecializationKind();
7376
7377 Linkage L = VD->getLinkage();
David Blaikiebbafb8a2012-03-11 07:00:24 +00007378 if (L == ExternalLinkage && getLangOpts().CPlusPlus &&
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007379 VD->getType()->getLinkage() == UniqueExternalLinkage)
7380 L = UniqueExternalLinkage;
7381
7382 switch (L) {
7383 case NoLinkage:
7384 case InternalLinkage:
7385 case UniqueExternalLinkage:
7386 return GVA_Internal;
7387
7388 case ExternalLinkage:
7389 switch (TSK) {
7390 case TSK_Undeclared:
7391 case TSK_ExplicitSpecialization:
7392 return GVA_StrongExternal;
7393
7394 case TSK_ExplicitInstantiationDeclaration:
7395 llvm_unreachable("Variable should not be instantiated");
7396 // Fall through to treat this like any other instantiation.
7397
7398 case TSK_ExplicitInstantiationDefinition:
7399 return GVA_ExplicitTemplateInstantiation;
7400
7401 case TSK_ImplicitInstantiation:
7402 return GVA_TemplateInstantiation;
7403 }
7404 }
7405
David Blaikie8a40f702012-01-17 06:56:22 +00007406 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007407}
7408
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007409bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007410 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7411 if (!VD->isFileVarDecl())
7412 return false;
Argyrios Kyrtzidisa98e8612011-09-13 21:35:00 +00007413 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007414 return false;
7415
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007416 // Weak references don't produce any output by themselves.
7417 if (D->hasAttr<WeakRefAttr>())
7418 return false;
7419
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007420 // Aliases and used decls are required.
7421 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7422 return true;
7423
7424 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7425 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007426 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007427 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007428
7429 // Constructors and destructors are required.
7430 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7431 return true;
7432
7433 // The key function for a class is required.
7434 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7435 const CXXRecordDecl *RD = MD->getParent();
7436 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7437 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
7438 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7439 return true;
7440 }
7441 }
7442
7443 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7444
7445 // static, static inline, always_inline, and extern inline functions can
7446 // always be deferred. Normal inline functions can be deferred in C99/C++.
7447 // Implicit template instantiations can also be deferred in C++.
7448 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007449 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007450 return false;
7451 return true;
7452 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007453
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007454 const VarDecl *VD = cast<VarDecl>(D);
7455 assert(VD->isFileVarDecl() && "Expected file scoped var");
7456
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007457 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7458 return false;
7459
Richard Smitha0e5e542012-11-12 21:38:00 +00007460 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007461 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smitha0e5e542012-11-12 21:38:00 +00007462 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7463 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007464
Richard Smitha0e5e542012-11-12 21:38:00 +00007465 // Variables that have destruction with side-effects are required.
7466 if (VD->getType().isDestructedType())
7467 return true;
7468
7469 // Variables that have initialization with side-effects are required.
7470 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7471 return true;
7472
7473 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007474}
Charles Davis53c59df2010-08-16 03:33:14 +00007475
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007476CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davis99202b32010-11-09 18:04:24 +00007477 // Pass through to the C++ ABI object
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007478 return ABI->getDefaultMethodCallConv(isVariadic);
7479}
7480
7481CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
7482 if (CC == CC_C && !LangOpts.MRTD && getTargetInfo().getCXXABI() != CXXABI_Microsoft)
7483 return CC_Default;
7484 return CC;
Charles Davis99202b32010-11-09 18:04:24 +00007485}
7486
Jay Foad39c79802011-01-12 09:06:06 +00007487bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007488 // Pass through to the C++ ABI object
7489 return ABI->isNearlyEmpty(RD);
7490}
7491
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007492MangleContext *ASTContext::createMangleContext() {
Douglas Gregore8bbc122011-09-02 00:18:52 +00007493 switch (Target->getCXXABI()) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007494 case CXXABI_ARM:
7495 case CXXABI_Itanium:
7496 return createItaniumMangleContext(*this, getDiagnostics());
7497 case CXXABI_Microsoft:
7498 return createMicrosoftMangleContext(*this, getDiagnostics());
7499 }
David Blaikie83d382b2011-09-23 05:06:16 +00007500 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007501}
7502
Charles Davis53c59df2010-08-16 03:33:14 +00007503CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007504
7505size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00007506 return ASTRecordLayouts.getMemorySize()
7507 + llvm::capacity_in_bytes(ObjCLayouts)
7508 + llvm::capacity_in_bytes(KeyFunctions)
7509 + llvm::capacity_in_bytes(ObjCImpls)
7510 + llvm::capacity_in_bytes(BlockVarCopyInits)
7511 + llvm::capacity_in_bytes(DeclAttrs)
7512 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7513 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7514 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7515 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7516 + llvm::capacity_in_bytes(OverriddenMethods)
7517 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007518 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00007519 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007520}
Ted Kremenek540017e2011-10-06 05:00:56 +00007521
David Blaikie095deba2012-11-14 01:52:05 +00007522void ASTContext::addUnnamedTag(const TagDecl *Tag) {
7523 // FIXME: This mangling should be applied to function local classes too
7524 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl() ||
7525 !isa<CXXRecordDecl>(Tag->getParent()) || Tag->getLinkage() != ExternalLinkage)
7526 return;
7527
7528 std::pair<llvm::DenseMap<const DeclContext *, unsigned>::iterator, bool> P =
7529 UnnamedMangleContexts.insert(std::make_pair(Tag->getParent(), 0));
7530 UnnamedMangleNumbers.insert(std::make_pair(Tag, P.first->second++));
7531}
7532
7533int ASTContext::getUnnamedTagManglingNumber(const TagDecl *Tag) const {
7534 llvm::DenseMap<const TagDecl *, unsigned>::const_iterator I =
7535 UnnamedMangleNumbers.find(Tag);
7536 return I != UnnamedMangleNumbers.end() ? I->second : -1;
7537}
7538
Douglas Gregor63798542012-02-20 19:44:39 +00007539unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7540 CXXRecordDecl *Lambda = CallOperator->getParent();
7541 return LambdaMangleContexts[Lambda->getDeclContext()]
7542 .getManglingNumber(CallOperator);
7543}
7544
7545
Ted Kremenek540017e2011-10-06 05:00:56 +00007546void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7547 ParamIndices[D] = index;
7548}
7549
7550unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7551 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7552 assert(I != ParamIndices.end() &&
7553 "ParmIndices lacks entry set by ParmVarDecl");
7554 return I->second;
7555}