blob: df64237f704877a071389b72ad992253858da841 [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CXXABI.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000016#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/Attr.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000018#include "clang/AST/CharUnits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000019#include "clang/AST/Comment.h"
Dmitri Gribenkoca7f80a2012-08-09 00:03:17 +000020#include "clang/AST/CommentCommandTraits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000021#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000022#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000023#include "clang/AST/DeclTemplate.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000024#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000026#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000027#include "clang/AST/Mangle.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000028#include "clang/AST/RecordLayout.h"
29#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000030#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000031#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000032#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000033#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000034#include "llvm/ADT/StringExtras.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000035#include "llvm/Support/Capacity.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000036#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000037#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000038#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000039
Chris Lattnerddc135e2006-11-10 06:34:16 +000040using namespace clang;
41
Douglas Gregor9672f922010-07-03 00:47:00 +000042unsigned ASTContext::NumImplicitDefaultConstructors;
43unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000044unsigned ASTContext::NumImplicitCopyConstructors;
45unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000046unsigned ASTContext::NumImplicitMoveConstructors;
47unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000048unsigned ASTContext::NumImplicitCopyAssignmentOperators;
49unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000050unsigned ASTContext::NumImplicitMoveAssignmentOperators;
51unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000052unsigned ASTContext::NumImplicitDestructors;
53unsigned ASTContext::NumImplicitDestructorsDeclared;
54
Steve Naroff0af91202007-04-27 21:51:21 +000055enum FloatingRank {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000056 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Steve Naroff0af91202007-04-27 21:51:21 +000057};
58
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000059RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000060 if (!CommentsLoaded && ExternalSource) {
61 ExternalSource->ReadComments();
62 CommentsLoaded = true;
63 }
64
65 assert(D);
66
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000067 // User can not attach documentation to implicit declarations.
68 if (D->isImplicit())
69 return NULL;
70
Dmitri Gribenkob2610882012-08-14 17:17:18 +000071 // User can not attach documentation to implicit instantiations.
72 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
73 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
74 return NULL;
75 }
76
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000077 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
78 if (VD->isStaticDataMember() &&
79 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
80 return NULL;
81 }
82
83 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
84 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
85 return NULL;
86 }
87
88 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
89 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
90 return NULL;
91 }
92
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000093 // TODO: handle comments for function parameters properly.
94 if (isa<ParmVarDecl>(D))
95 return NULL;
96
Dmitri Gribenko34df2202012-07-31 22:37:06 +000097 // TODO: we could look up template parameter documentation in the template
98 // documentation.
99 if (isa<TemplateTypeParmDecl>(D) ||
100 isa<NonTypeTemplateParmDecl>(D) ||
101 isa<TemplateTemplateParmDecl>(D))
102 return NULL;
103
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000104 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000105
106 // If there are no comments anywhere, we won't find anything.
107 if (RawComments.empty())
108 return NULL;
109
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000110 // Find declaration location.
111 // For Objective-C declarations we generally don't expect to have multiple
112 // declarators, thus use declaration starting location as the "declaration
113 // location".
114 // For all other declarations multiple declarators are used quite frequently,
115 // so we use the location of the identifier as the "declaration location".
116 SourceLocation DeclLoc;
117 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000118 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000119 isa<RedeclarableTemplateDecl>(D) ||
120 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000121 DeclLoc = D->getLocStart();
122 else
123 DeclLoc = D->getLocation();
124
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000125 // If the declaration doesn't map directly to a location in a file, we
126 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000127 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
128 return NULL;
129
130 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000131 ArrayRef<RawComment *>::iterator Comment;
132 {
133 // When searching for comments during parsing, the comment we are looking
134 // for is usually among the last two comments we parsed -- check them
135 // first.
136 RawComment CommentAtDeclLoc(SourceMgr, SourceRange(DeclLoc));
137 BeforeThanCompare<RawComment> Compare(SourceMgr);
138 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
139 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
140 if (!Found && RawComments.size() >= 2) {
141 MaybeBeforeDecl--;
142 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
143 }
144
145 if (Found) {
146 Comment = MaybeBeforeDecl + 1;
147 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
148 &CommentAtDeclLoc, Compare));
149 } else {
150 // Slow path.
151 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
152 &CommentAtDeclLoc, Compare);
153 }
154 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000155
156 // Decompose the location for the declaration and find the beginning of the
157 // file buffer.
158 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
159
160 // First check whether we have a trailing comment.
161 if (Comment != RawComments.end() &&
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000162 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Dmitri Gribenko44cd7e62012-07-06 23:27:33 +0000163 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000164 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000165 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000166 // Check that Doxygen trailing comment comes after the declaration, starts
167 // on the same line and in the same file as the declaration.
168 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
169 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
170 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
171 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000172 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000173 }
174 }
175
176 // The comment just after the declaration was not a trailing comment.
177 // Let's look at the previous comment.
178 if (Comment == RawComments.begin())
179 return NULL;
180 --Comment;
181
182 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000183 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000184 return NULL;
185
186 // Decompose the end of the comment.
187 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000188 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000189
190 // If the comment and the declaration aren't in the same file, then they
191 // aren't related.
192 if (DeclLocDecomp.first != CommentEndDecomp.first)
193 return NULL;
194
195 // Get the corresponding buffer.
196 bool Invalid = false;
197 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
198 &Invalid).data();
199 if (Invalid)
200 return NULL;
201
202 // Extract text between the comment and declaration.
203 StringRef Text(Buffer + CommentEndDecomp.second,
204 DeclLocDecomp.second - CommentEndDecomp.second);
205
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000206 // There should be no other declarations or preprocessor directives between
207 // comment and declaration.
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000208 if (Text.find_first_of(",;{}#@") != StringRef::npos)
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000209 return NULL;
210
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000211 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000212}
213
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000214namespace {
215/// If we have a 'templated' declaration for a template, adjust 'D' to
216/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000217/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000218const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregor35ceb272012-08-13 16:37:30 +0000219 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000220 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000221 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000222 return FTD;
223
224 // Nothing to do if function is not an implicit instantiation.
225 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
226 return D;
227
228 // Function is an implicit instantiation of a function template?
229 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
230 return FTD;
231
232 // Function is instantiated from a member definition of a class template?
233 if (const FunctionDecl *MemberDecl =
234 FD->getInstantiatedFromMemberFunction())
235 return MemberDecl;
236
237 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000238 }
Dmitri Gribenko90631802012-08-22 17:44:32 +0000239 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
240 // Static data member is instantiated from a member definition of a class
241 // template?
242 if (VD->isStaticDataMember())
243 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
244 return MemberDecl;
245
246 return D;
247 }
248 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
249 // Is this class declaration part of a class template?
250 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
251 return CTD;
252
253 // Class is an implicit instantiation of a class template or partial
254 // specialization?
255 if (const ClassTemplateSpecializationDecl *CTSD =
256 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
257 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
258 return D;
259 llvm::PointerUnion<ClassTemplateDecl *,
260 ClassTemplatePartialSpecializationDecl *>
261 PU = CTSD->getSpecializedTemplateOrPartial();
262 return PU.is<ClassTemplateDecl*>() ?
263 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
264 static_cast<const Decl*>(
265 PU.get<ClassTemplatePartialSpecializationDecl *>());
266 }
267
268 // Class is instantiated from a member definition of a class template?
269 if (const MemberSpecializationInfo *Info =
270 CRD->getMemberSpecializationInfo())
271 return Info->getInstantiatedFrom();
272
273 return D;
274 }
275 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
276 // Enum is instantiated from a member definition of a class template?
277 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
278 return MemberDecl;
279
280 return D;
281 }
282 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000283 return D;
284}
285} // unnamed namespace
286
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000287const RawComment *ASTContext::getRawCommentForAnyRedecl(
288 const Decl *D,
289 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000290 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000291
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000292 // Check whether we have cached a comment for this declaration already.
293 {
294 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
295 RedeclComments.find(D);
296 if (Pos != RedeclComments.end()) {
297 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000298 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
299 if (OriginalDecl)
300 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000301 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000302 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000303 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000304 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000305
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000306 // Search for comments attached to declarations in the redeclaration chain.
307 const RawComment *RC = NULL;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000308 const Decl *OriginalDeclForRC = NULL;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000309 for (Decl::redecl_iterator I = D->redecls_begin(),
310 E = D->redecls_end();
311 I != E; ++I) {
312 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
313 RedeclComments.find(*I);
314 if (Pos != RedeclComments.end()) {
315 const RawCommentAndCacheFlags &Raw = Pos->second;
316 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
317 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000318 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000319 break;
320 }
321 } else {
322 RC = getRawCommentForDeclNoCache(*I);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000323 OriginalDeclForRC = *I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000324 RawCommentAndCacheFlags Raw;
325 if (RC) {
326 Raw.setRaw(RC);
327 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
328 } else
329 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000330 Raw.setOriginalDecl(*I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000331 RedeclComments[*I] = Raw;
332 if (RC)
333 break;
334 }
335 }
336
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000337 // If we found a comment, it should be a documentation comment.
338 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000339
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000340 if (OriginalDecl)
341 *OriginalDecl = OriginalDeclForRC;
342
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000343 // Update cache for every declaration in the redeclaration chain.
344 RawCommentAndCacheFlags Raw;
345 Raw.setRaw(RC);
346 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000347 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000348
349 for (Decl::redecl_iterator I = D->redecls_begin(),
350 E = D->redecls_end();
351 I != E; ++I) {
352 RawCommentAndCacheFlags &R = RedeclComments[*I];
353 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
354 R = Raw;
355 }
356
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000357 return RC;
358}
359
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000360static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
361 SmallVectorImpl<const NamedDecl *> &Redeclared) {
362 const DeclContext *DC = ObjCMethod->getDeclContext();
363 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
364 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
365 if (!ID)
366 return;
367 // Add redeclared method here.
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000368 for (ObjCInterfaceDecl::known_extensions_iterator
369 Ext = ID->known_extensions_begin(),
370 ExtEnd = ID->known_extensions_end();
371 Ext != ExtEnd; ++Ext) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000372 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000373 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000374 ObjCMethod->isInstanceMethod()))
375 Redeclared.push_back(RedeclaredMethod);
376 }
377 }
378}
379
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000380comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
381 const Decl *D) const {
382 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
383 ThisDeclInfo->CommentDecl = D;
384 ThisDeclInfo->IsFilled = false;
385 ThisDeclInfo->fill();
386 ThisDeclInfo->CommentDecl = FC->getDecl();
387 comments::FullComment *CFC =
388 new (*this) comments::FullComment(FC->getBlocks(),
389 ThisDeclInfo);
390 return CFC;
391
392}
393
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000394comments::FullComment *ASTContext::getCommentForDecl(
395 const Decl *D,
396 const Preprocessor *PP) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000397 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000398
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000399 const Decl *Canonical = D->getCanonicalDecl();
400 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
401 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000402
403 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000404 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000405 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000406 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000407 return CFC;
408 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000409 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000410 }
411
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000412 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000413
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000414 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000415 if (!RC) {
416 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000417 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000418 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
419 if (OMD && OMD->isPropertyAccessor()) {
420 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl()) {
421 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP)) {
422 comments::FullComment *CFC = cloneFullComment(FC, D);
423 return CFC;
424 }
425 }
426 }
427 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000428 addRedeclaredMethods(OMD, Overridden);
429 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
430 for (unsigned i = 0, e = Overridden.size(); i < e; i++) {
431 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP)) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000432 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000433 return CFC;
434 }
435 }
436 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000437 return NULL;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000438 }
439
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000440 // If the RawComment was attached to other redeclaration of this Decl, we
441 // should parse the comment in context of that other Decl. This is important
442 // because comments can contain references to parameter names which can be
443 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000444 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000445 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000446
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000447 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000448 ParsedComments[Canonical] = FC;
449 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000450}
451
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000452void
453ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
454 TemplateTemplateParmDecl *Parm) {
455 ID.AddInteger(Parm->getDepth());
456 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000457 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000458
459 TemplateParameterList *Params = Parm->getTemplateParameters();
460 ID.AddInteger(Params->size());
461 for (TemplateParameterList::const_iterator P = Params->begin(),
462 PEnd = Params->end();
463 P != PEnd; ++P) {
464 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
465 ID.AddInteger(0);
466 ID.AddBoolean(TTP->isParameterPack());
467 continue;
468 }
469
470 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
471 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000472 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000473 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000474 if (NTTP->isExpandedParameterPack()) {
475 ID.AddBoolean(true);
476 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000477 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
478 QualType T = NTTP->getExpansionType(I);
479 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
480 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000481 } else
482 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000483 continue;
484 }
485
486 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
487 ID.AddInteger(2);
488 Profile(ID, TTP);
489 }
490}
491
492TemplateTemplateParmDecl *
493ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000494 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000495 // Check if we already have a canonical template template parameter.
496 llvm::FoldingSetNodeID ID;
497 CanonicalTemplateTemplateParm::Profile(ID, TTP);
498 void *InsertPos = 0;
499 CanonicalTemplateTemplateParm *Canonical
500 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
501 if (Canonical)
502 return Canonical->getParam();
503
504 // Build a canonical template parameter list.
505 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000506 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000507 CanonParams.reserve(Params->size());
508 for (TemplateParameterList::const_iterator P = Params->begin(),
509 PEnd = Params->end();
510 P != PEnd; ++P) {
511 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
512 CanonParams.push_back(
513 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000514 SourceLocation(),
515 SourceLocation(),
516 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000517 TTP->getIndex(), 0, false,
518 TTP->isParameterPack()));
519 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000520 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
521 QualType T = getCanonicalType(NTTP->getType());
522 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
523 NonTypeTemplateParmDecl *Param;
524 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000525 SmallVector<QualType, 2> ExpandedTypes;
526 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000527 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
528 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
529 ExpandedTInfos.push_back(
530 getTrivialTypeSourceInfo(ExpandedTypes.back()));
531 }
532
533 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000534 SourceLocation(),
535 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000536 NTTP->getDepth(),
537 NTTP->getPosition(), 0,
538 T,
539 TInfo,
540 ExpandedTypes.data(),
541 ExpandedTypes.size(),
542 ExpandedTInfos.data());
543 } else {
544 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000545 SourceLocation(),
546 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000547 NTTP->getDepth(),
548 NTTP->getPosition(), 0,
549 T,
550 NTTP->isParameterPack(),
551 TInfo);
552 }
553 CanonParams.push_back(Param);
554
555 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000556 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
557 cast<TemplateTemplateParmDecl>(*P)));
558 }
559
560 TemplateTemplateParmDecl *CanonTTP
561 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
562 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000563 TTP->getPosition(),
564 TTP->isParameterPack(),
565 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000566 TemplateParameterList::Create(*this, SourceLocation(),
567 SourceLocation(),
568 CanonParams.data(),
569 CanonParams.size(),
570 SourceLocation()));
571
572 // Get the new insert position for the node we care about.
573 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
574 assert(Canonical == 0 && "Shouldn't be in the map!");
575 (void)Canonical;
576
577 // Create the canonical template template parameter entry.
578 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
579 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
580 return CanonTTP;
581}
582
Charles Davis53c59df2010-08-16 03:33:14 +0000583CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000584 if (!LangOpts.CPlusPlus) return 0;
585
Charles Davis6bcb07a2010-08-19 02:18:14 +0000586 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000587 case CXXABI_ARM:
588 return CreateARMCXXABI(*this);
589 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000590 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000591 case CXXABI_Microsoft:
592 return CreateMicrosoftCXXABI(*this);
593 }
David Blaikie8a40f702012-01-17 06:56:22 +0000594 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000595}
596
Douglas Gregore8bbc122011-09-02 00:18:52 +0000597static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000598 const LangOptions &LOpts) {
599 if (LOpts.FakeAddressSpaceMap) {
600 // The fake address space map must have a distinct entry for each
601 // language-specific address space.
602 static const unsigned FakeAddrSpaceMap[] = {
603 1, // opencl_global
604 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000605 3, // opencl_constant
606 4, // cuda_device
607 5, // cuda_constant
608 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000609 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000610 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000611 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000612 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000613 }
614}
615
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000616ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000617 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000618 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000619 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000620 unsigned size_reserve,
621 bool DelayInitialization)
622 : FunctionProtoTypes(this_()),
623 TemplateSpecializationTypes(this_()),
624 DependentTemplateSpecializationTypes(this_()),
625 SubstTemplateTemplateParmPacks(this_()),
626 GlobalNestedNameSpecifier(0),
627 Int128Decl(0), UInt128Decl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000628 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000629 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanianf2578572012-08-30 18:49:41 +0000630 BOOLDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000631 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000632 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000633 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
634 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
635 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000636 NullTypeSourceInfo(QualType()),
637 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000638 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000639 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000640 Idents(idents), Selectors(sels),
641 BuiltinInfo(builtins),
642 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000643 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000644 Comments(SM), CommentsLoaded(false),
Dmitri Gribenko7acbf002012-09-10 20:32:42 +0000645 CommentCommandTraits(BumpAlloc),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000646 LastSDM(0, 0),
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +0000647 UniqueBlockByRefTypeID(0)
Douglas Gregore8bbc122011-09-02 00:18:52 +0000648{
Mike Stump11289f42009-09-09 15:08:12 +0000649 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000650 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000651
652 if (!DelayInitialization) {
653 assert(t && "No target supplied for ASTContext initialization");
654 InitBuiltinTypes(*t);
655 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000656}
657
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000658ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000659 // Release the DenseMaps associated with DeclContext objects.
660 // FIXME: Is this the ideal solution?
661 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000662
Douglas Gregor5b11d492010-07-25 17:53:33 +0000663 // Call all of the deallocation functions.
664 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
665 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000666
Ted Kremenek076baeb2010-06-08 23:00:58 +0000667 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000668 // because they can contain DenseMaps.
669 for (llvm::DenseMap<const ObjCContainerDecl*,
670 const ASTRecordLayout*>::iterator
671 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
672 // Increment in loop to prevent using deallocated memory.
673 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
674 R->Destroy(*this);
675
Ted Kremenek076baeb2010-06-08 23:00:58 +0000676 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
677 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
678 // Increment in loop to prevent using deallocated memory.
679 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
680 R->Destroy(*this);
681 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000682
683 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
684 AEnd = DeclAttrs.end();
685 A != AEnd; ++A)
686 A->second->~AttrVec();
687}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000688
Douglas Gregor1a809332010-05-23 18:26:36 +0000689void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
690 Deallocations.push_back(std::make_pair(Callback, Data));
691}
692
Mike Stump11289f42009-09-09 15:08:12 +0000693void
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000694ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000695 ExternalSource.reset(Source.take());
696}
697
Chris Lattner4eb445d2007-01-26 01:27:23 +0000698void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000699 llvm::errs() << "\n*** AST Context Stats:\n";
700 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000701
Douglas Gregora30d0462009-05-26 14:40:08 +0000702 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000703#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000704#define ABSTRACT_TYPE(Name, Parent)
705#include "clang/AST/TypeNodes.def"
706 0 // Extra
707 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000708
Chris Lattner4eb445d2007-01-26 01:27:23 +0000709 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
710 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000711 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000712 }
713
Douglas Gregora30d0462009-05-26 14:40:08 +0000714 unsigned Idx = 0;
715 unsigned TotalBytes = 0;
716#define TYPE(Name, Parent) \
717 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000718 llvm::errs() << " " << counts[Idx] << " " << #Name \
719 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000720 TotalBytes += counts[Idx] * sizeof(Name##Type); \
721 ++Idx;
722#define ABSTRACT_TYPE(Name, Parent)
723#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000724
Chandler Carruth3c147a72011-07-04 05:32:14 +0000725 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
726
Douglas Gregor7454c562010-07-02 20:37:36 +0000727 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000728 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
729 << NumImplicitDefaultConstructors
730 << " implicit default constructors created\n";
731 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
732 << NumImplicitCopyConstructors
733 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000734 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000735 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
736 << NumImplicitMoveConstructors
737 << " implicit move constructors created\n";
738 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
739 << NumImplicitCopyAssignmentOperators
740 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000741 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000742 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
743 << NumImplicitMoveAssignmentOperators
744 << " implicit move assignment operators created\n";
745 llvm::errs() << NumImplicitDestructorsDeclared << "/"
746 << NumImplicitDestructors
747 << " implicit destructors created\n";
748
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000749 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000750 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000751 ExternalSource->PrintStats();
752 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000753
Douglas Gregor5b11d492010-07-25 17:53:33 +0000754 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000755}
756
Douglas Gregor801c99d2011-08-12 06:49:56 +0000757TypedefDecl *ASTContext::getInt128Decl() const {
758 if (!Int128Decl) {
759 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
760 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
761 getTranslationUnitDecl(),
762 SourceLocation(),
763 SourceLocation(),
764 &Idents.get("__int128_t"),
765 TInfo);
766 }
767
768 return Int128Decl;
769}
770
771TypedefDecl *ASTContext::getUInt128Decl() const {
772 if (!UInt128Decl) {
773 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
774 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
775 getTranslationUnitDecl(),
776 SourceLocation(),
777 SourceLocation(),
778 &Idents.get("__uint128_t"),
779 TInfo);
780 }
781
782 return UInt128Decl;
783}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000784
John McCall48f2d582009-10-23 23:03:21 +0000785void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000786 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000787 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000788 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000789}
790
Douglas Gregore8bbc122011-09-02 00:18:52 +0000791void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
792 assert((!this->Target || this->Target == &Target) &&
793 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000794 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000795
Douglas Gregore8bbc122011-09-02 00:18:52 +0000796 this->Target = &Target;
797
798 ABI.reset(createCXXABI(Target));
799 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
800
Chris Lattner970e54e2006-11-12 00:37:36 +0000801 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000802 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000803
Chris Lattner970e54e2006-11-12 00:37:36 +0000804 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000805 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000806 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000807 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000808 InitBuiltinType(CharTy, BuiltinType::Char_S);
809 else
810 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000811 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000812 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
813 InitBuiltinType(ShortTy, BuiltinType::Short);
814 InitBuiltinType(IntTy, BuiltinType::Int);
815 InitBuiltinType(LongTy, BuiltinType::Long);
816 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000817
Chris Lattner970e54e2006-11-12 00:37:36 +0000818 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000819 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
820 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
821 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
822 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
823 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000824
Chris Lattner970e54e2006-11-12 00:37:36 +0000825 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000826 InitBuiltinType(FloatTy, BuiltinType::Float);
827 InitBuiltinType(DoubleTy, BuiltinType::Double);
828 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000829
Chris Lattnerf122cef2009-04-30 02:43:43 +0000830 // GNU extension, 128-bit integers.
831 InitBuiltinType(Int128Ty, BuiltinType::Int128);
832 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
833
Abramo Bagnara06782942012-09-09 10:13:32 +0000834 if (LangOpts.CPlusPlus && LangOpts.WChar) { // C++ 3.9.1p5
Eli Friedman786d0872011-04-30 19:24:24 +0000835 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000836 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
837 else // -fshort-wchar makes wchar_t be unsigned.
838 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
Abramo Bagnara06782942012-09-09 10:13:32 +0000839 } else // C99 (or C++ using -fno-wchar)
Chris Lattner007cb022009-02-26 23:43:47 +0000840 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000841
James Molloy36365542012-05-04 10:55:22 +0000842 WIntTy = getFromTargetType(Target.getWIntType());
843
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000844 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
845 InitBuiltinType(Char16Ty, BuiltinType::Char16);
846 else // C99
847 Char16Ty = getFromTargetType(Target.getChar16Type());
848
849 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
850 InitBuiltinType(Char32Ty, BuiltinType::Char32);
851 else // C99
852 Char32Ty = getFromTargetType(Target.getChar32Type());
853
Douglas Gregor4619e432008-12-05 23:32:09 +0000854 // Placeholder type for type-dependent expressions whose type is
855 // completely unknown. No code should ever check a type against
856 // DependentTy and users should never see it; however, it is here to
857 // help diagnose failures to properly check for type-dependent
858 // expressions.
859 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000860
John McCall36e7fe32010-10-12 00:20:44 +0000861 // Placeholder type for functions.
862 InitBuiltinType(OverloadTy, BuiltinType::Overload);
863
John McCall0009fcc2011-04-26 20:42:42 +0000864 // Placeholder type for bound members.
865 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
866
John McCall526ab472011-10-25 17:37:35 +0000867 // Placeholder type for pseudo-objects.
868 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
869
John McCall31996342011-04-07 08:22:57 +0000870 // "any" type; useful for debugger-like clients.
871 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
872
John McCall8a6b59a2011-10-17 18:09:15 +0000873 // Placeholder type for unbridged ARC casts.
874 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
875
Eli Friedman34866c72012-08-31 00:14:07 +0000876 // Placeholder type for builtin functions.
877 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
878
Chris Lattner970e54e2006-11-12 00:37:36 +0000879 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000880 FloatComplexTy = getComplexType(FloatTy);
881 DoubleComplexTy = getComplexType(DoubleTy);
882 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000883
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000884 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000885 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
886 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000887 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000888
889 if (LangOpts.OpenCL) {
890 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
891 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
892 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
893 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
894 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
895 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
896 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000897
898 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +0000899 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
900 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000901
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000902 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +0000903
904 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000905
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000906 // void * type
907 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000908
909 // nullptr type (C++0x 2.14.7)
910 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000911
912 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
913 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +0000914
915 // Builtin type used to help define __builtin_va_list.
916 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +0000917}
918
David Blaikie9c902b52011-09-25 23:23:43 +0000919DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000920 return SourceMgr.getDiagnostics();
921}
922
Douglas Gregor561eceb2010-08-30 16:49:28 +0000923AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
924 AttrVec *&Result = DeclAttrs[D];
925 if (!Result) {
926 void *Mem = Allocate(sizeof(AttrVec));
927 Result = new (Mem) AttrVec;
928 }
929
930 return *Result;
931}
932
933/// \brief Erase the attributes corresponding to the given declaration.
934void ASTContext::eraseDeclAttrs(const Decl *D) {
935 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
936 if (Pos != DeclAttrs.end()) {
937 Pos->second->~AttrVec();
938 DeclAttrs.erase(Pos);
939 }
940}
941
Douglas Gregor86d142a2009-10-08 07:24:58 +0000942MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000943ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000944 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000945 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000946 = InstantiatedFromStaticDataMember.find(Var);
947 if (Pos == InstantiatedFromStaticDataMember.end())
948 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000949
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000950 return Pos->second;
951}
952
Mike Stump11289f42009-09-09 15:08:12 +0000953void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000954ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000955 TemplateSpecializationKind TSK,
956 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000957 assert(Inst->isStaticDataMember() && "Not a static data member");
958 assert(Tmpl->isStaticDataMember() && "Not a static data member");
959 assert(!InstantiatedFromStaticDataMember[Inst] &&
960 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000961 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000962 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000963}
964
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000965FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
966 const FunctionDecl *FD){
967 assert(FD && "Specialization is 0");
968 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +0000969 = ClassScopeSpecializationPattern.find(FD);
970 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000971 return 0;
972
973 return Pos->second;
974}
975
976void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
977 FunctionDecl *Pattern) {
978 assert(FD && "Specialization is 0");
979 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +0000980 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000981}
982
John McCalle61f2ba2009-11-18 02:36:19 +0000983NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000984ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000985 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000986 = InstantiatedFromUsingDecl.find(UUD);
987 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000988 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000989
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000990 return Pos->second;
991}
992
993void
John McCallb96ec562009-12-04 22:46:56 +0000994ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
995 assert((isa<UsingDecl>(Pattern) ||
996 isa<UnresolvedUsingValueDecl>(Pattern) ||
997 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
998 "pattern decl is not a using decl");
999 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1000 InstantiatedFromUsingDecl[Inst] = Pattern;
1001}
1002
1003UsingShadowDecl *
1004ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1005 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1006 = InstantiatedFromUsingShadowDecl.find(Inst);
1007 if (Pos == InstantiatedFromUsingShadowDecl.end())
1008 return 0;
1009
1010 return Pos->second;
1011}
1012
1013void
1014ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1015 UsingShadowDecl *Pattern) {
1016 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1017 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001018}
1019
Anders Carlsson5da84842009-09-01 04:26:58 +00001020FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1021 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1022 = InstantiatedFromUnnamedFieldDecl.find(Field);
1023 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1024 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001025
Anders Carlsson5da84842009-09-01 04:26:58 +00001026 return Pos->second;
1027}
1028
1029void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1030 FieldDecl *Tmpl) {
1031 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1032 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1033 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1034 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001035
Anders Carlsson5da84842009-09-01 04:26:58 +00001036 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1037}
1038
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +00001039bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
1040 const FieldDecl *LastFD) const {
1041 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001042 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +00001043}
1044
Fariborz Jahanianeb397412011-05-02 17:20:56 +00001045bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
1046 const FieldDecl *LastFD) const {
1047 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001048 FD->getBitWidthValue(*this) == 0 &&
1049 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +00001050}
1051
Fariborz Jahanian84335f72011-05-04 18:51:37 +00001052bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
1053 const FieldDecl *LastFD) const {
1054 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001055 FD->getBitWidthValue(*this) &&
1056 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +00001057}
1058
Chad Rosierf01a7dd2011-08-04 23:34:15 +00001059bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001060 const FieldDecl *LastFD) const {
1061 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001062 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001063}
1064
Chad Rosierf01a7dd2011-08-04 23:34:15 +00001065bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001066 const FieldDecl *LastFD) const {
1067 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001068 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001069}
1070
Douglas Gregor832940b2010-03-02 23:58:15 +00001071ASTContext::overridden_cxx_method_iterator
1072ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1073 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001074 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001075 if (Pos == OverriddenMethods.end())
1076 return 0;
1077
1078 return Pos->second.begin();
1079}
1080
1081ASTContext::overridden_cxx_method_iterator
1082ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1083 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001084 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001085 if (Pos == OverriddenMethods.end())
1086 return 0;
1087
1088 return Pos->second.end();
1089}
1090
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001091unsigned
1092ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1093 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001094 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001095 if (Pos == OverriddenMethods.end())
1096 return 0;
1097
1098 return Pos->second.size();
1099}
1100
Douglas Gregor832940b2010-03-02 23:58:15 +00001101void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1102 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001103 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001104 OverriddenMethods[Method].push_back(Overridden);
1105}
1106
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001107void ASTContext::getOverriddenMethods(
1108 const NamedDecl *D,
1109 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001110 assert(D);
1111
1112 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001113 Overridden.append(CXXMethod->begin_overridden_methods(),
1114 CXXMethod->end_overridden_methods());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001115 return;
1116 }
1117
1118 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1119 if (!Method)
1120 return;
1121
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001122 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1123 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001124 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001125}
1126
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001127void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1128 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1129 assert(!Import->isFromASTFile() && "Non-local import declaration");
1130 if (!FirstLocalImport) {
1131 FirstLocalImport = Import;
1132 LastLocalImport = Import;
1133 return;
1134 }
1135
1136 LastLocalImport->NextLocalImport = Import;
1137 LastLocalImport = Import;
1138}
1139
Chris Lattner53cfe802007-07-18 17:52:12 +00001140//===----------------------------------------------------------------------===//
1141// Type Sizing and Analysis
1142//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001143
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001144/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1145/// scalar floating point type.
1146const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001147 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001148 assert(BT && "Not a floating point type!");
1149 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001150 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001151 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001152 case BuiltinType::Float: return Target->getFloatFormat();
1153 case BuiltinType::Double: return Target->getDoubleFormat();
1154 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001155 }
1156}
1157
Ken Dyck160146e2010-01-27 17:10:57 +00001158/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +00001159/// specified decl. Note that bitfields do not have a valid alignment, so
1160/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001161/// If @p RefAsPointee, references are treated like their underlying type
1162/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +00001163CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001164 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001165
John McCall94268702010-10-08 18:24:19 +00001166 bool UseAlignAttrOnly = false;
1167 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1168 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001169
John McCall94268702010-10-08 18:24:19 +00001170 // __attribute__((aligned)) can increase or decrease alignment
1171 // *except* on a struct or struct member, where it only increases
1172 // alignment unless 'packed' is also specified.
1173 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001174 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001175 // ignore that possibility; Sema should diagnose it.
1176 if (isa<FieldDecl>(D)) {
1177 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1178 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1179 } else {
1180 UseAlignAttrOnly = true;
1181 }
1182 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001183 else if (isa<FieldDecl>(D))
1184 UseAlignAttrOnly =
1185 D->hasAttr<PackedAttr>() ||
1186 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001187
John McCall4e819612011-01-20 07:57:12 +00001188 // If we're using the align attribute only, just ignore everything
1189 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001190 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001191 // do nothing
1192
John McCall94268702010-10-08 18:24:19 +00001193 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001194 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001195 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001196 if (RefAsPointee)
1197 T = RT->getPointeeType();
1198 else
1199 T = getPointerType(RT->getPointeeType());
1200 }
1201 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001202 // Adjust alignments of declarations with array type by the
1203 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +00001204 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +00001205 const ArrayType *arrayType;
1206 if (MinWidth && (arrayType = getAsArrayType(T))) {
1207 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001208 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +00001209 else if (isa<ConstantArrayType>(arrayType) &&
1210 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001211 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +00001212
John McCall33ddac02011-01-19 10:06:00 +00001213 // Walk through any array types while we're at it.
1214 T = getBaseElementType(arrayType);
1215 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001216 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +00001217 }
John McCall4e819612011-01-20 07:57:12 +00001218
1219 // Fields can be subject to extra alignment constraints, like if
1220 // the field is packed, the struct is packed, or the struct has a
1221 // a max-field-alignment constraint (#pragma pack). So calculate
1222 // the actual alignment of the field within the struct, and then
1223 // (as we're expected to) constrain that by the alignment of the type.
1224 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
1225 // So calculate the alignment of the field.
1226 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
1227
1228 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +00001229 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001230
1231 // Use the GCD of that and the offset within the record.
1232 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
1233 if (offset > 0) {
1234 // Alignment is always a power of 2, so the GCD will be a power of 2,
1235 // which means we get to do this crazy thing instead of Euclid's.
1236 uint64_t lowBitOfOffset = offset & (~offset + 1);
1237 if (lowBitOfOffset < fieldAlign)
1238 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
1239 }
1240
1241 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +00001242 }
Chris Lattner68061312009-01-24 21:53:27 +00001243 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001244
Ken Dyckcc56c542011-01-15 18:38:59 +00001245 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001246}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001247
John McCallf1249922012-08-21 04:10:00 +00001248// getTypeInfoDataSizeInChars - Return the size of a type, in
1249// chars. If the type is a record, its data size is returned. This is
1250// the size of the memcpy that's performed when assigning this type
1251// using a trivial copy/move assignment operator.
1252std::pair<CharUnits, CharUnits>
1253ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1254 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1255
1256 // In C++, objects can sometimes be allocated into the tail padding
1257 // of a base-class subobject. We decide whether that's possible
1258 // during class layout, so here we can just trust the layout results.
1259 if (getLangOpts().CPlusPlus) {
1260 if (const RecordType *RT = T->getAs<RecordType>()) {
1261 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1262 sizeAndAlign.first = layout.getDataSize();
1263 }
1264 }
1265
1266 return sizeAndAlign;
1267}
1268
John McCall87fe5d52010-05-20 01:18:31 +00001269std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001270ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001271 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +00001272 return std::make_pair(toCharUnitsFromBits(Info.first),
1273 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +00001274}
1275
1276std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001277ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001278 return getTypeInfoInChars(T.getTypePtr());
1279}
1280
Daniel Dunbarc6475872012-03-09 04:12:54 +00001281std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1282 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1283 if (it != MemoizedTypeInfo.end())
1284 return it->second;
1285
1286 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1287 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1288 return Info;
1289}
1290
1291/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1292/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001293///
1294/// FIXME: Pointers into different addr spaces could have different sizes and
1295/// alignment requirements: getPointerInfo should take an AddrSpace, this
1296/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +00001297std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +00001298ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +00001299 uint64_t Width=0;
1300 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001301 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001302#define TYPE(Class, Base)
1303#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001304#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001305#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1306#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001307 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001308
Chris Lattner355332d2007-07-13 22:27:08 +00001309 case Type::FunctionNoProto:
1310 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001311 // GCC extension: alignof(function) = 32 bits
1312 Width = 0;
1313 Align = 32;
1314 break;
1315
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001316 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001317 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001318 Width = 0;
1319 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1320 break;
1321
Steve Naroff5c131802007-08-30 01:06:46 +00001322 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001323 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001324
Chris Lattner37e05872008-03-05 18:54:05 +00001325 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001326 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +00001327 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1328 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001329 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001330 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +00001331 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001332 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001333 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001334 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001335 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001336 const VectorType *VT = cast<VectorType>(T);
1337 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1338 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001339 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001340 // If the alignment is not a power of 2, round up to the next power of 2.
1341 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001342 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001343 Align = llvm::NextPowerOf2(Align);
1344 Width = llvm::RoundUpToAlignment(Width, Align);
1345 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001346 // Adjust the alignment based on the target max.
1347 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1348 if (TargetVectorAlign && TargetVectorAlign < Align)
1349 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001350 break;
1351 }
Chris Lattner647fb222007-07-18 18:26:58 +00001352
Chris Lattner7570e9c2008-03-08 08:52:55 +00001353 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001354 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001355 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001356 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001357 // GCC extension: alignof(void) = 8 bits.
1358 Width = 0;
1359 Align = 8;
1360 break;
1361
Chris Lattner6a4f7452007-12-19 19:23:28 +00001362 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001363 Width = Target->getBoolWidth();
1364 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001365 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001366 case BuiltinType::Char_S:
1367 case BuiltinType::Char_U:
1368 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001369 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001370 Width = Target->getCharWidth();
1371 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001372 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001373 case BuiltinType::WChar_S:
1374 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001375 Width = Target->getWCharWidth();
1376 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001377 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001378 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001379 Width = Target->getChar16Width();
1380 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001381 break;
1382 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001383 Width = Target->getChar32Width();
1384 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001385 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001386 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001387 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001388 Width = Target->getShortWidth();
1389 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001390 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001391 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001392 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001393 Width = Target->getIntWidth();
1394 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001395 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001396 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001397 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001398 Width = Target->getLongWidth();
1399 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001400 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001401 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001402 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001403 Width = Target->getLongLongWidth();
1404 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001405 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001406 case BuiltinType::Int128:
1407 case BuiltinType::UInt128:
1408 Width = 128;
1409 Align = 128; // int128_t is 128-bit aligned on all targets.
1410 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001411 case BuiltinType::Half:
1412 Width = Target->getHalfWidth();
1413 Align = Target->getHalfAlign();
1414 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001415 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001416 Width = Target->getFloatWidth();
1417 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001418 break;
1419 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001420 Width = Target->getDoubleWidth();
1421 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001422 break;
1423 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001424 Width = Target->getLongDoubleWidth();
1425 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001426 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001427 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001428 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1429 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001430 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001431 case BuiltinType::ObjCId:
1432 case BuiltinType::ObjCClass:
1433 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001434 Width = Target->getPointerWidth(0);
1435 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001436 break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001437 case BuiltinType::OCLImage1d:
1438 case BuiltinType::OCLImage1dArray:
1439 case BuiltinType::OCLImage1dBuffer:
1440 case BuiltinType::OCLImage2d:
1441 case BuiltinType::OCLImage2dArray:
1442 case BuiltinType::OCLImage3d:
1443 // Currently these types are pointers to opaque types.
1444 Width = Target->getPointerWidth(0);
1445 Align = Target->getPointerAlign(0);
1446 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001447 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001448 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001449 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001450 Width = Target->getPointerWidth(0);
1451 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001452 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001453 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001454 unsigned AS = getTargetAddressSpace(
1455 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001456 Width = Target->getPointerWidth(AS);
1457 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001458 break;
1459 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001460 case Type::LValueReference:
1461 case Type::RValueReference: {
1462 // alignof and sizeof should never enter this code path here, so we go
1463 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001464 unsigned AS = getTargetAddressSpace(
1465 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001466 Width = Target->getPointerWidth(AS);
1467 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001468 break;
1469 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001470 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001471 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001472 Width = Target->getPointerWidth(AS);
1473 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001474 break;
1475 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001476 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001477 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001478 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +00001479 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +00001480 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001481 Align = PtrDiffInfo.second;
1482 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001483 }
Chris Lattner647fb222007-07-18 18:26:58 +00001484 case Type::Complex: {
1485 // Complex types have the same alignment as their elements, but twice the
1486 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001487 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001488 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001489 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001490 Align = EltInfo.second;
1491 break;
1492 }
John McCall8b07ec22010-05-15 11:32:37 +00001493 case Type::ObjCObject:
1494 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001495 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001496 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001497 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001498 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001499 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001500 break;
1501 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001502 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001503 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001504 const TagType *TT = cast<TagType>(T);
1505
1506 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001507 Width = 8;
1508 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001509 break;
1510 }
Mike Stump11289f42009-09-09 15:08:12 +00001511
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001512 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001513 return getTypeInfo(ET->getDecl()->getIntegerType());
1514
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001515 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001516 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001517 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001518 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001519 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001520 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001521
Chris Lattner63d2b362009-10-22 05:17:15 +00001522 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001523 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1524 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001525
Richard Smith30482bc2011-02-20 03:19:35 +00001526 case Type::Auto: {
1527 const AutoType *A = cast<AutoType>(T);
1528 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001529 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001530 }
1531
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001532 case Type::Paren:
1533 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1534
Douglas Gregoref462e62009-04-30 17:32:17 +00001535 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001536 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001537 std::pair<uint64_t, unsigned> Info
1538 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001539 // If the typedef has an aligned attribute on it, it overrides any computed
1540 // alignment we have. This violates the GCC documentation (which says that
1541 // attribute(aligned) can only round up) but matches its implementation.
1542 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1543 Align = AttrAlign;
1544 else
1545 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001546 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001547 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001548 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001549
1550 case Type::TypeOfExpr:
1551 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1552 .getTypePtr());
1553
1554 case Type::TypeOf:
1555 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1556
Anders Carlsson81df7b82009-06-24 19:06:50 +00001557 case Type::Decltype:
1558 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1559 .getTypePtr());
1560
Alexis Hunte852b102011-05-24 22:41:36 +00001561 case Type::UnaryTransform:
1562 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1563
Abramo Bagnara6150c882010-05-11 21:36:43 +00001564 case Type::Elaborated:
1565 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001566
John McCall81904512011-01-06 01:58:22 +00001567 case Type::Attributed:
1568 return getTypeInfo(
1569 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1570
Richard Smith3f1b5d02011-05-05 21:57:07 +00001571 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001572 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001573 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001574 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1575 // A type alias template specialization may refer to a typedef with the
1576 // aligned attribute on it.
1577 if (TST->isTypeAlias())
1578 return getTypeInfo(TST->getAliasedType().getTypePtr());
1579 else
1580 return getTypeInfo(getCanonicalType(T));
1581 }
1582
Eli Friedman0dfb8892011-10-06 23:00:33 +00001583 case Type::Atomic: {
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001584 std::pair<uint64_t, unsigned> Info
1585 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1586 Width = Info.first;
1587 Align = Info.second;
1588 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1589 llvm::isPowerOf2_64(Width)) {
1590 // We can potentially perform lock-free atomic operations for this
1591 // type; promote the alignment appropriately.
1592 // FIXME: We could potentially promote the width here as well...
1593 // is that worthwhile? (Non-struct atomic types generally have
1594 // power-of-two size anyway, but structs might not. Requires a bit
1595 // of implementation work to make sure we zero out the extra bits.)
1596 Align = static_cast<unsigned>(Width);
1597 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001598 }
1599
Douglas Gregoref462e62009-04-30 17:32:17 +00001600 }
Mike Stump11289f42009-09-09 15:08:12 +00001601
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001602 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001603 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001604}
1605
Ken Dyckcc56c542011-01-15 18:38:59 +00001606/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1607CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1608 return CharUnits::fromQuantity(BitSize / getCharWidth());
1609}
1610
Ken Dyckb0fcc592011-02-11 01:54:29 +00001611/// toBits - Convert a size in characters to a size in characters.
1612int64_t ASTContext::toBits(CharUnits CharSize) const {
1613 return CharSize.getQuantity() * getCharWidth();
1614}
1615
Ken Dyck8c89d592009-12-22 14:23:30 +00001616/// getTypeSizeInChars - Return the size of the specified type, in characters.
1617/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001618CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001619 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001620}
Jay Foad39c79802011-01-12 09:06:06 +00001621CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001622 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001623}
1624
Ken Dycka6046ab2010-01-26 17:25:18 +00001625/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001626/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001627CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001628 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001629}
Jay Foad39c79802011-01-12 09:06:06 +00001630CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001631 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001632}
1633
Chris Lattnera3402cd2009-01-27 18:08:34 +00001634/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1635/// type for the current target in bits. This can be different than the ABI
1636/// alignment in cases where it is beneficial for performance to overalign
1637/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001638unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001639 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001640
1641 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001642 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001643 T = CT->getElementType().getTypePtr();
1644 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001645 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1646 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001647 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1648
Chris Lattnera3402cd2009-01-27 18:08:34 +00001649 return ABIAlign;
1650}
1651
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001652/// DeepCollectObjCIvars -
1653/// This routine first collects all declared, but not synthesized, ivars in
1654/// super class and then collects all ivars, including those synthesized for
1655/// current class. This routine is used for implementation of current class
1656/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001657///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001658void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1659 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001660 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001661 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1662 DeepCollectObjCIvars(SuperClass, false, Ivars);
1663 if (!leafClass) {
1664 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1665 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001666 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001667 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001668 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001669 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001670 Iv= Iv->getNextIvar())
1671 Ivars.push_back(Iv);
1672 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001673}
1674
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001675/// CollectInheritedProtocols - Collect all protocols in current class and
1676/// those inherited by it.
1677void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001678 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001679 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001680 // We can use protocol_iterator here instead of
1681 // all_referenced_protocol_iterator since we are walking all categories.
1682 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1683 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001684 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001685 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001686 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001687 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001688 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001689 CollectInheritedProtocols(*P, Protocols);
1690 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001691 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001692
1693 // Categories of this Interface.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001694 for (ObjCInterfaceDecl::visible_categories_iterator
1695 Cat = OI->visible_categories_begin(),
1696 CatEnd = OI->visible_categories_end();
1697 Cat != CatEnd; ++Cat) {
1698 CollectInheritedProtocols(*Cat, Protocols);
1699 }
1700
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001701 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1702 while (SD) {
1703 CollectInheritedProtocols(SD, Protocols);
1704 SD = SD->getSuperClass();
1705 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001706 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001707 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001708 PE = OC->protocol_end(); P != PE; ++P) {
1709 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001710 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001711 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1712 PE = Proto->protocol_end(); P != PE; ++P)
1713 CollectInheritedProtocols(*P, Protocols);
1714 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001715 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001716 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1717 PE = OP->protocol_end(); P != PE; ++P) {
1718 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001719 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001720 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1721 PE = Proto->protocol_end(); P != PE; ++P)
1722 CollectInheritedProtocols(*P, Protocols);
1723 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001724 }
1725}
1726
Jay Foad39c79802011-01-12 09:06:06 +00001727unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001728 unsigned count = 0;
1729 // Count ivars declared in class extension.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001730 for (ObjCInterfaceDecl::known_extensions_iterator
1731 Ext = OI->known_extensions_begin(),
1732 ExtEnd = OI->known_extensions_end();
1733 Ext != ExtEnd; ++Ext) {
1734 count += Ext->ivar_size();
1735 }
1736
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001737 // Count ivar defined in this class's implementation. This
1738 // includes synthesized ivars.
1739 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001740 count += ImplDecl->ivar_size();
1741
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001742 return count;
1743}
1744
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001745bool ASTContext::isSentinelNullExpr(const Expr *E) {
1746 if (!E)
1747 return false;
1748
1749 // nullptr_t is always treated as null.
1750 if (E->getType()->isNullPtrType()) return true;
1751
1752 if (E->getType()->isAnyPointerType() &&
1753 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1754 Expr::NPC_ValueDependentIsNull))
1755 return true;
1756
1757 // Unfortunately, __null has type 'int'.
1758 if (isa<GNUNullExpr>(E)) return true;
1759
1760 return false;
1761}
1762
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001763/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1764ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1765 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1766 I = ObjCImpls.find(D);
1767 if (I != ObjCImpls.end())
1768 return cast<ObjCImplementationDecl>(I->second);
1769 return 0;
1770}
1771/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1772ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1773 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1774 I = ObjCImpls.find(D);
1775 if (I != ObjCImpls.end())
1776 return cast<ObjCCategoryImplDecl>(I->second);
1777 return 0;
1778}
1779
1780/// \brief Set the implementation of ObjCInterfaceDecl.
1781void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1782 ObjCImplementationDecl *ImplD) {
1783 assert(IFaceD && ImplD && "Passed null params");
1784 ObjCImpls[IFaceD] = ImplD;
1785}
1786/// \brief Set the implementation of ObjCCategoryDecl.
1787void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1788 ObjCCategoryImplDecl *ImplD) {
1789 assert(CatD && ImplD && "Passed null params");
1790 ObjCImpls[CatD] = ImplD;
1791}
1792
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001793ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1794 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1795 return ID;
1796 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1797 return CD->getClassInterface();
1798 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1799 return IMD->getClassInterface();
1800
1801 return 0;
1802}
1803
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001804/// \brief Get the copy initialization expression of VarDecl,or NULL if
1805/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001806Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001807 assert(VD && "Passed null params");
1808 assert(VD->hasAttr<BlocksAttr>() &&
1809 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001810 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001811 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001812 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1813}
1814
1815/// \brief Set the copy inialization expression of a block var decl.
1816void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1817 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001818 assert(VD->hasAttr<BlocksAttr>() &&
1819 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001820 BlockVarCopyInits[VD] = Init;
1821}
1822
John McCallbcd03502009-12-07 02:54:59 +00001823TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001824 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001825 if (!DataSize)
1826 DataSize = TypeLoc::getFullDataSizeForType(T);
1827 else
1828 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001829 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001830
John McCallbcd03502009-12-07 02:54:59 +00001831 TypeSourceInfo *TInfo =
1832 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1833 new (TInfo) TypeSourceInfo(T);
1834 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001835}
1836
John McCallbcd03502009-12-07 02:54:59 +00001837TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001838 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001839 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001840 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001841 return DI;
1842}
1843
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001844const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001845ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001846 return getObjCLayout(D, 0);
1847}
1848
1849const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001850ASTContext::getASTObjCImplementationLayout(
1851 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001852 return getObjCLayout(D->getClassInterface(), D);
1853}
1854
Chris Lattner983a8bb2007-07-13 22:13:22 +00001855//===----------------------------------------------------------------------===//
1856// Type creation/memoization methods
1857//===----------------------------------------------------------------------===//
1858
Jay Foad39c79802011-01-12 09:06:06 +00001859QualType
John McCall33ddac02011-01-19 10:06:00 +00001860ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1861 unsigned fastQuals = quals.getFastQualifiers();
1862 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001863
1864 // Check if we've already instantiated this type.
1865 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001866 ExtQuals::Profile(ID, baseType, quals);
1867 void *insertPos = 0;
1868 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1869 assert(eq->getQualifiers() == quals);
1870 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001871 }
1872
John McCall33ddac02011-01-19 10:06:00 +00001873 // If the base type is not canonical, make the appropriate canonical type.
1874 QualType canon;
1875 if (!baseType->isCanonicalUnqualified()) {
1876 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00001877 canonSplit.Quals.addConsistentQualifiers(quals);
1878 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001879
1880 // Re-find the insert position.
1881 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1882 }
1883
1884 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1885 ExtQualNodes.InsertNode(eq, insertPos);
1886 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001887}
1888
Jay Foad39c79802011-01-12 09:06:06 +00001889QualType
1890ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001891 QualType CanT = getCanonicalType(T);
1892 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001893 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001894
John McCall8ccfcb52009-09-24 19:53:00 +00001895 // If we are composing extended qualifiers together, merge together
1896 // into one ExtQuals node.
1897 QualifierCollector Quals;
1898 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001899
John McCall8ccfcb52009-09-24 19:53:00 +00001900 // If this type already has an address space specified, it cannot get
1901 // another one.
1902 assert(!Quals.hasAddressSpace() &&
1903 "Type cannot be in multiple addr spaces!");
1904 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001905
John McCall8ccfcb52009-09-24 19:53:00 +00001906 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001907}
1908
Chris Lattnerd60183d2009-02-18 22:53:11 +00001909QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001910 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001911 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001912 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001913 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001914
John McCall53fa7142010-12-24 02:08:15 +00001915 if (const PointerType *ptr = T->getAs<PointerType>()) {
1916 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001917 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001918 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1919 return getPointerType(ResultType);
1920 }
1921 }
Mike Stump11289f42009-09-09 15:08:12 +00001922
John McCall8ccfcb52009-09-24 19:53:00 +00001923 // If we are composing extended qualifiers together, merge together
1924 // into one ExtQuals node.
1925 QualifierCollector Quals;
1926 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001927
John McCall8ccfcb52009-09-24 19:53:00 +00001928 // If this type already has an ObjCGC specified, it cannot get
1929 // another one.
1930 assert(!Quals.hasObjCGCAttr() &&
1931 "Type cannot have multiple ObjCGCs!");
1932 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001933
John McCall8ccfcb52009-09-24 19:53:00 +00001934 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001935}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001936
John McCall4f5019e2010-12-19 02:44:49 +00001937const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1938 FunctionType::ExtInfo Info) {
1939 if (T->getExtInfo() == Info)
1940 return T;
1941
1942 QualType Result;
1943 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1944 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1945 } else {
1946 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1947 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1948 EPI.ExtInfo = Info;
1949 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1950 FPT->getNumArgs(), EPI);
1951 }
1952
1953 return cast<FunctionType>(Result.getTypePtr());
1954}
1955
Chris Lattnerc6395932007-06-22 20:56:16 +00001956/// getComplexType - Return the uniqued reference to the type for a complex
1957/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001958QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001959 // Unique pointers, to guarantee there is only one pointer of a particular
1960 // structure.
1961 llvm::FoldingSetNodeID ID;
1962 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001963
Chris Lattnerc6395932007-06-22 20:56:16 +00001964 void *InsertPos = 0;
1965 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1966 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001967
Chris Lattnerc6395932007-06-22 20:56:16 +00001968 // If the pointee type isn't canonical, this won't be a canonical type either,
1969 // so fill in the canonical type field.
1970 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001971 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001972 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001973
Chris Lattnerc6395932007-06-22 20:56:16 +00001974 // Get the new insert position for the node we care about.
1975 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001976 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001977 }
John McCall90d1c2d2009-09-24 23:30:46 +00001978 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001979 Types.push_back(New);
1980 ComplexTypes.InsertNode(New, InsertPos);
1981 return QualType(New, 0);
1982}
1983
Chris Lattner970e54e2006-11-12 00:37:36 +00001984/// getPointerType - Return the uniqued reference to the type for a pointer to
1985/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001986QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001987 // Unique pointers, to guarantee there is only one pointer of a particular
1988 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001989 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001990 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001991
Chris Lattner67521df2007-01-27 01:29:36 +00001992 void *InsertPos = 0;
1993 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001994 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001995
Chris Lattner7ccecb92006-11-12 08:50:50 +00001996 // If the pointee type isn't canonical, this won't be a canonical type either,
1997 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001998 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001999 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002000 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002001
Chris Lattner67521df2007-01-27 01:29:36 +00002002 // Get the new insert position for the node we care about.
2003 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002004 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00002005 }
John McCall90d1c2d2009-09-24 23:30:46 +00002006 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002007 Types.push_back(New);
2008 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002009 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002010}
2011
Mike Stump11289f42009-09-09 15:08:12 +00002012/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002013/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002014QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002015 assert(T->isFunctionType() && "block of function types only");
2016 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002017 // structure.
2018 llvm::FoldingSetNodeID ID;
2019 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002020
Steve Naroffec33ed92008-08-27 16:04:49 +00002021 void *InsertPos = 0;
2022 if (BlockPointerType *PT =
2023 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2024 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002025
2026 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002027 // type either so fill in the canonical type field.
2028 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002029 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002030 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002031
Steve Naroffec33ed92008-08-27 16:04:49 +00002032 // Get the new insert position for the node we care about.
2033 BlockPointerType *NewIP =
2034 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002035 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002036 }
John McCall90d1c2d2009-09-24 23:30:46 +00002037 BlockPointerType *New
2038 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002039 Types.push_back(New);
2040 BlockPointerTypes.InsertNode(New, InsertPos);
2041 return QualType(New, 0);
2042}
2043
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002044/// getLValueReferenceType - Return the uniqued reference to the type for an
2045/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002046QualType
2047ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002048 assert(getCanonicalType(T) != OverloadTy &&
2049 "Unresolved overloaded function type");
2050
Bill Wendling3708c182007-05-27 10:15:43 +00002051 // Unique pointers, to guarantee there is only one pointer of a particular
2052 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002053 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002054 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002055
2056 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002057 if (LValueReferenceType *RT =
2058 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002059 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002060
John McCallfc93cf92009-10-22 22:37:11 +00002061 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2062
Bill Wendling3708c182007-05-27 10:15:43 +00002063 // If the referencee type isn't canonical, this won't be a canonical type
2064 // either, so fill in the canonical type field.
2065 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002066 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2067 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2068 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002069
Bill Wendling3708c182007-05-27 10:15:43 +00002070 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002071 LValueReferenceType *NewIP =
2072 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002073 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002074 }
2075
John McCall90d1c2d2009-09-24 23:30:46 +00002076 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002077 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2078 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002079 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002080 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002081
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002082 return QualType(New, 0);
2083}
2084
2085/// getRValueReferenceType - Return the uniqued reference to the type for an
2086/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002087QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002088 // Unique pointers, to guarantee there is only one pointer of a particular
2089 // structure.
2090 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002091 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002092
2093 void *InsertPos = 0;
2094 if (RValueReferenceType *RT =
2095 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2096 return QualType(RT, 0);
2097
John McCallfc93cf92009-10-22 22:37:11 +00002098 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2099
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002100 // If the referencee type isn't canonical, this won't be a canonical type
2101 // either, so fill in the canonical type field.
2102 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002103 if (InnerRef || !T.isCanonical()) {
2104 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2105 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002106
2107 // Get the new insert position for the node we care about.
2108 RValueReferenceType *NewIP =
2109 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002110 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002111 }
2112
John McCall90d1c2d2009-09-24 23:30:46 +00002113 RValueReferenceType *New
2114 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002115 Types.push_back(New);
2116 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002117 return QualType(New, 0);
2118}
2119
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002120/// getMemberPointerType - Return the uniqued reference to the type for a
2121/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002122QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002123 // Unique pointers, to guarantee there is only one pointer of a particular
2124 // structure.
2125 llvm::FoldingSetNodeID ID;
2126 MemberPointerType::Profile(ID, T, Cls);
2127
2128 void *InsertPos = 0;
2129 if (MemberPointerType *PT =
2130 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2131 return QualType(PT, 0);
2132
2133 // If the pointee or class type isn't canonical, this won't be a canonical
2134 // type either, so fill in the canonical type field.
2135 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002136 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002137 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2138
2139 // Get the new insert position for the node we care about.
2140 MemberPointerType *NewIP =
2141 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002142 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002143 }
John McCall90d1c2d2009-09-24 23:30:46 +00002144 MemberPointerType *New
2145 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002146 Types.push_back(New);
2147 MemberPointerTypes.InsertNode(New, InsertPos);
2148 return QualType(New, 0);
2149}
2150
Mike Stump11289f42009-09-09 15:08:12 +00002151/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002152/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002153QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002154 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002155 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002156 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002157 assert((EltTy->isDependentType() ||
2158 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002159 "Constant array of VLAs is illegal!");
2160
Chris Lattnere2df3f92009-05-13 04:12:56 +00002161 // Convert the array size into a canonical width matching the pointer size for
2162 // the target.
2163 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002164 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002165 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002166
Chris Lattner23b7eb62007-06-15 23:05:46 +00002167 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002168 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002169
Chris Lattner36f8e652007-01-27 08:31:04 +00002170 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002171 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002172 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002173 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002174
John McCall33ddac02011-01-19 10:06:00 +00002175 // If the element type isn't canonical or has qualifiers, this won't
2176 // be a canonical type either, so fill in the canonical type field.
2177 QualType Canon;
2178 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2179 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002180 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002181 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002182 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002183
Chris Lattner36f8e652007-01-27 08:31:04 +00002184 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002185 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002186 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002187 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002188 }
Mike Stump11289f42009-09-09 15:08:12 +00002189
John McCall90d1c2d2009-09-24 23:30:46 +00002190 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002191 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002192 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002193 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002194 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002195}
2196
John McCall06549462011-01-18 08:40:38 +00002197/// getVariableArrayDecayedType - Turns the given type, which may be
2198/// variably-modified, into the corresponding type with all the known
2199/// sizes replaced with [*].
2200QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2201 // Vastly most common case.
2202 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002203
John McCall06549462011-01-18 08:40:38 +00002204 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002205
John McCall06549462011-01-18 08:40:38 +00002206 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002207 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002208 switch (ty->getTypeClass()) {
2209#define TYPE(Class, Base)
2210#define ABSTRACT_TYPE(Class, Base)
2211#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2212#include "clang/AST/TypeNodes.def"
2213 llvm_unreachable("didn't desugar past all non-canonical types?");
2214
2215 // These types should never be variably-modified.
2216 case Type::Builtin:
2217 case Type::Complex:
2218 case Type::Vector:
2219 case Type::ExtVector:
2220 case Type::DependentSizedExtVector:
2221 case Type::ObjCObject:
2222 case Type::ObjCInterface:
2223 case Type::ObjCObjectPointer:
2224 case Type::Record:
2225 case Type::Enum:
2226 case Type::UnresolvedUsing:
2227 case Type::TypeOfExpr:
2228 case Type::TypeOf:
2229 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002230 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002231 case Type::DependentName:
2232 case Type::InjectedClassName:
2233 case Type::TemplateSpecialization:
2234 case Type::DependentTemplateSpecialization:
2235 case Type::TemplateTypeParm:
2236 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002237 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002238 case Type::PackExpansion:
2239 llvm_unreachable("type should never be variably-modified");
2240
2241 // These types can be variably-modified but should never need to
2242 // further decay.
2243 case Type::FunctionNoProto:
2244 case Type::FunctionProto:
2245 case Type::BlockPointer:
2246 case Type::MemberPointer:
2247 return type;
2248
2249 // These types can be variably-modified. All these modifications
2250 // preserve structure except as noted by comments.
2251 // TODO: if we ever care about optimizing VLAs, there are no-op
2252 // optimizations available here.
2253 case Type::Pointer:
2254 result = getPointerType(getVariableArrayDecayedType(
2255 cast<PointerType>(ty)->getPointeeType()));
2256 break;
2257
2258 case Type::LValueReference: {
2259 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2260 result = getLValueReferenceType(
2261 getVariableArrayDecayedType(lv->getPointeeType()),
2262 lv->isSpelledAsLValue());
2263 break;
2264 }
2265
2266 case Type::RValueReference: {
2267 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2268 result = getRValueReferenceType(
2269 getVariableArrayDecayedType(lv->getPointeeType()));
2270 break;
2271 }
2272
Eli Friedman0dfb8892011-10-06 23:00:33 +00002273 case Type::Atomic: {
2274 const AtomicType *at = cast<AtomicType>(ty);
2275 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2276 break;
2277 }
2278
John McCall06549462011-01-18 08:40:38 +00002279 case Type::ConstantArray: {
2280 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2281 result = getConstantArrayType(
2282 getVariableArrayDecayedType(cat->getElementType()),
2283 cat->getSize(),
2284 cat->getSizeModifier(),
2285 cat->getIndexTypeCVRQualifiers());
2286 break;
2287 }
2288
2289 case Type::DependentSizedArray: {
2290 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2291 result = getDependentSizedArrayType(
2292 getVariableArrayDecayedType(dat->getElementType()),
2293 dat->getSizeExpr(),
2294 dat->getSizeModifier(),
2295 dat->getIndexTypeCVRQualifiers(),
2296 dat->getBracketsRange());
2297 break;
2298 }
2299
2300 // Turn incomplete types into [*] types.
2301 case Type::IncompleteArray: {
2302 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2303 result = getVariableArrayType(
2304 getVariableArrayDecayedType(iat->getElementType()),
2305 /*size*/ 0,
2306 ArrayType::Normal,
2307 iat->getIndexTypeCVRQualifiers(),
2308 SourceRange());
2309 break;
2310 }
2311
2312 // Turn VLA types into [*] types.
2313 case Type::VariableArray: {
2314 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2315 result = getVariableArrayType(
2316 getVariableArrayDecayedType(vat->getElementType()),
2317 /*size*/ 0,
2318 ArrayType::Star,
2319 vat->getIndexTypeCVRQualifiers(),
2320 vat->getBracketsRange());
2321 break;
2322 }
2323 }
2324
2325 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002326 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002327}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002328
Steve Naroffcadebd02007-08-30 18:14:25 +00002329/// getVariableArrayType - Returns a non-unique reference to the type for a
2330/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002331QualType ASTContext::getVariableArrayType(QualType EltTy,
2332 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002333 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002334 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002335 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002336 // Since we don't unique expressions, it isn't possible to unique VLA's
2337 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002338 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002339
John McCall33ddac02011-01-19 10:06:00 +00002340 // Be sure to pull qualifiers off the element type.
2341 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2342 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002343 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002344 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002345 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002346 }
2347
John McCall90d1c2d2009-09-24 23:30:46 +00002348 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002349 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002350
2351 VariableArrayTypes.push_back(New);
2352 Types.push_back(New);
2353 return QualType(New, 0);
2354}
2355
Douglas Gregor4619e432008-12-05 23:32:09 +00002356/// getDependentSizedArrayType - Returns a non-unique reference to
2357/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002358/// type.
John McCall33ddac02011-01-19 10:06:00 +00002359QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2360 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002361 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002362 unsigned elementTypeQuals,
2363 SourceRange brackets) const {
2364 assert((!numElements || numElements->isTypeDependent() ||
2365 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002366 "Size must be type- or value-dependent!");
2367
John McCall33ddac02011-01-19 10:06:00 +00002368 // Dependently-sized array types that do not have a specified number
2369 // of elements will have their sizes deduced from a dependent
2370 // initializer. We do no canonicalization here at all, which is okay
2371 // because they can't be used in most locations.
2372 if (!numElements) {
2373 DependentSizedArrayType *newType
2374 = new (*this, TypeAlignment)
2375 DependentSizedArrayType(*this, elementType, QualType(),
2376 numElements, ASM, elementTypeQuals,
2377 brackets);
2378 Types.push_back(newType);
2379 return QualType(newType, 0);
2380 }
2381
2382 // Otherwise, we actually build a new type every time, but we
2383 // also build a canonical type.
2384
2385 SplitQualType canonElementType = getCanonicalType(elementType).split();
2386
2387 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002388 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002389 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002390 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002391 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002392
John McCall33ddac02011-01-19 10:06:00 +00002393 // Look for an existing type with these properties.
2394 DependentSizedArrayType *canonTy =
2395 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002396
John McCall33ddac02011-01-19 10:06:00 +00002397 // If we don't have one, build one.
2398 if (!canonTy) {
2399 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002400 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002401 QualType(), numElements, ASM, elementTypeQuals,
2402 brackets);
2403 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2404 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002405 }
2406
John McCall33ddac02011-01-19 10:06:00 +00002407 // Apply qualifiers from the element type to the array.
2408 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002409 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002410
John McCall33ddac02011-01-19 10:06:00 +00002411 // If we didn't need extra canonicalization for the element type,
2412 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002413 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002414 return canon;
2415
2416 // Otherwise, we need to build a type which follows the spelling
2417 // of the element type.
2418 DependentSizedArrayType *sugaredType
2419 = new (*this, TypeAlignment)
2420 DependentSizedArrayType(*this, elementType, canon, numElements,
2421 ASM, elementTypeQuals, brackets);
2422 Types.push_back(sugaredType);
2423 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002424}
2425
John McCall33ddac02011-01-19 10:06:00 +00002426QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002427 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002428 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002429 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002430 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002431
John McCall33ddac02011-01-19 10:06:00 +00002432 void *insertPos = 0;
2433 if (IncompleteArrayType *iat =
2434 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2435 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002436
2437 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002438 // either, so fill in the canonical type field. We also have to pull
2439 // qualifiers off the element type.
2440 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002441
John McCall33ddac02011-01-19 10:06:00 +00002442 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2443 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002444 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002445 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002446 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002447
2448 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002449 IncompleteArrayType *existing =
2450 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2451 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002452 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002453
John McCall33ddac02011-01-19 10:06:00 +00002454 IncompleteArrayType *newType = new (*this, TypeAlignment)
2455 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002456
John McCall33ddac02011-01-19 10:06:00 +00002457 IncompleteArrayTypes.InsertNode(newType, insertPos);
2458 Types.push_back(newType);
2459 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002460}
2461
Steve Naroff91fcddb2007-07-18 18:00:27 +00002462/// getVectorType - Return the unique reference to a vector type of
2463/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002464QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002465 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002466 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002467
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002468 // Check if we've already instantiated a vector of this type.
2469 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002470 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002471
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002472 void *InsertPos = 0;
2473 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2474 return QualType(VTP, 0);
2475
2476 // If the element type isn't canonical, this won't be a canonical type either,
2477 // so fill in the canonical type field.
2478 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002479 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002480 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002481
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002482 // Get the new insert position for the node we care about.
2483 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002484 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002485 }
John McCall90d1c2d2009-09-24 23:30:46 +00002486 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002487 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002488 VectorTypes.InsertNode(New, InsertPos);
2489 Types.push_back(New);
2490 return QualType(New, 0);
2491}
2492
Nate Begemance4d7fc2008-04-18 23:10:10 +00002493/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002494/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002495QualType
2496ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002497 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002498
Steve Naroff91fcddb2007-07-18 18:00:27 +00002499 // Check if we've already instantiated a vector of this type.
2500 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002501 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002502 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002503 void *InsertPos = 0;
2504 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2505 return QualType(VTP, 0);
2506
2507 // If the element type isn't canonical, this won't be a canonical type either,
2508 // so fill in the canonical type field.
2509 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002510 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002511 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002512
Steve Naroff91fcddb2007-07-18 18:00:27 +00002513 // Get the new insert position for the node we care about.
2514 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002515 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002516 }
John McCall90d1c2d2009-09-24 23:30:46 +00002517 ExtVectorType *New = new (*this, TypeAlignment)
2518 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002519 VectorTypes.InsertNode(New, InsertPos);
2520 Types.push_back(New);
2521 return QualType(New, 0);
2522}
2523
Jay Foad39c79802011-01-12 09:06:06 +00002524QualType
2525ASTContext::getDependentSizedExtVectorType(QualType vecType,
2526 Expr *SizeExpr,
2527 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002528 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002529 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002530 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002531
Douglas Gregor352169a2009-07-31 03:54:25 +00002532 void *InsertPos = 0;
2533 DependentSizedExtVectorType *Canon
2534 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2535 DependentSizedExtVectorType *New;
2536 if (Canon) {
2537 // We already have a canonical version of this array type; use it as
2538 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002539 New = new (*this, TypeAlignment)
2540 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2541 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002542 } else {
2543 QualType CanonVecTy = getCanonicalType(vecType);
2544 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002545 New = new (*this, TypeAlignment)
2546 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2547 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002548
2549 DependentSizedExtVectorType *CanonCheck
2550 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2551 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2552 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002553 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2554 } else {
2555 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2556 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002557 New = new (*this, TypeAlignment)
2558 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002559 }
2560 }
Mike Stump11289f42009-09-09 15:08:12 +00002561
Douglas Gregor758a8692009-06-17 21:51:59 +00002562 Types.push_back(New);
2563 return QualType(New, 0);
2564}
2565
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002566/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002567///
Jay Foad39c79802011-01-12 09:06:06 +00002568QualType
2569ASTContext::getFunctionNoProtoType(QualType ResultTy,
2570 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002571 const CallingConv DefaultCC = Info.getCC();
2572 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2573 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002574 // Unique functions, to guarantee there is only one function of a particular
2575 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002576 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002577 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002578
Chris Lattner47955de2007-01-27 08:37:20 +00002579 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002580 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002581 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002582 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002583
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002584 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002585 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002586 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002587 Canonical =
2588 getFunctionNoProtoType(getCanonicalType(ResultTy),
2589 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002590
Chris Lattner47955de2007-01-27 08:37:20 +00002591 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002592 FunctionNoProtoType *NewIP =
2593 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002594 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002595 }
Mike Stump11289f42009-09-09 15:08:12 +00002596
Roman Divacky65b88cd2011-03-01 17:40:53 +00002597 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002598 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002599 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002600 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002601 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002602 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002603}
2604
2605/// getFunctionType - Return a normal function type with a typed argument
2606/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002607QualType
2608ASTContext::getFunctionType(QualType ResultTy,
2609 const QualType *ArgArray, unsigned NumArgs,
2610 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002611 // Unique functions, to guarantee there is only one function of a particular
2612 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002613 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002614 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002615
2616 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002617 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002618 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002619 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002620
2621 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002622 bool isCanonical =
2623 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2624 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002625 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002626 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002627 isCanonical = false;
2628
Roman Divacky65b88cd2011-03-01 17:40:53 +00002629 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2630 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2631 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002632
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002633 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002634 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002635 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002636 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002637 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002638 CanonicalArgs.reserve(NumArgs);
2639 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002640 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002641
John McCalldb40c7f2010-12-14 08:05:40 +00002642 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002643 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002644 CanonicalEPI.ExceptionSpecType = EST_None;
2645 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002646 CanonicalEPI.ExtInfo
2647 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2648
Chris Lattner76a00cf2008-04-06 22:59:24 +00002649 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002650 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002651 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002652
Chris Lattnerfd4de792007-01-27 01:15:32 +00002653 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002654 FunctionProtoType *NewIP =
2655 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002656 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002657 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002658
John McCall31168b02011-06-15 23:02:42 +00002659 // FunctionProtoType objects are allocated with extra bytes after
2660 // them for three variable size arrays at the end:
2661 // - parameter types
2662 // - exception types
2663 // - consumed-arguments flags
2664 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002665 // expression, or information used to resolve the exception
2666 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002667 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002668 NumArgs * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002669 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002670 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002671 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002672 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002673 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002674 Size += 2 * sizeof(FunctionDecl*);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002675 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2676 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002677 }
John McCall31168b02011-06-15 23:02:42 +00002678 if (EPI.ConsumedArguments)
2679 Size += NumArgs * sizeof(bool);
2680
John McCalldb40c7f2010-12-14 08:05:40 +00002681 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002682 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2683 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002684 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002685 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002686 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002687 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002688}
Chris Lattneref51c202006-11-10 07:17:23 +00002689
John McCalle78aac42010-03-10 03:28:59 +00002690#ifndef NDEBUG
2691static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2692 if (!isa<CXXRecordDecl>(D)) return false;
2693 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2694 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2695 return true;
2696 if (RD->getDescribedClassTemplate() &&
2697 !isa<ClassTemplateSpecializationDecl>(RD))
2698 return true;
2699 return false;
2700}
2701#endif
2702
2703/// getInjectedClassNameType - Return the unique reference to the
2704/// injected class name type for the specified templated declaration.
2705QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002706 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002707 assert(NeedsInjectedClassNameType(Decl));
2708 if (Decl->TypeForDecl) {
2709 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002710 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002711 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2712 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2713 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2714 } else {
John McCall424cec92011-01-19 06:33:43 +00002715 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002716 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002717 Decl->TypeForDecl = newType;
2718 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002719 }
2720 return QualType(Decl->TypeForDecl, 0);
2721}
2722
Douglas Gregor83a586e2008-04-13 21:07:44 +00002723/// getTypeDeclType - Return the unique reference to the type for the
2724/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002725QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002726 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002727 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002728
Richard Smithdda56e42011-04-15 14:24:37 +00002729 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002730 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002731
John McCall96f0b5f2010-03-10 06:48:02 +00002732 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2733 "Template type parameter types are always available.");
2734
John McCall81e38502010-02-16 03:57:14 +00002735 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002736 assert(!Record->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002737 "struct/union has previous declaration");
2738 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002739 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002740 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002741 assert(!Enum->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002742 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002743 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002744 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002745 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002746 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2747 Decl->TypeForDecl = newType;
2748 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002749 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002750 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002751
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002752 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002753}
2754
Chris Lattner32d920b2007-01-26 02:01:53 +00002755/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002756/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002757QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002758ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2759 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002760 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002761
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002762 if (Canonical.isNull())
2763 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002764 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002765 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002766 Decl->TypeForDecl = newType;
2767 Types.push_back(newType);
2768 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002769}
2770
Jay Foad39c79802011-01-12 09:06:06 +00002771QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002772 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2773
Douglas Gregorec9fd132012-01-14 16:38:05 +00002774 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002775 if (PrevDecl->TypeForDecl)
2776 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2777
John McCall424cec92011-01-19 06:33:43 +00002778 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2779 Decl->TypeForDecl = newType;
2780 Types.push_back(newType);
2781 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002782}
2783
Jay Foad39c79802011-01-12 09:06:06 +00002784QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002785 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2786
Douglas Gregorec9fd132012-01-14 16:38:05 +00002787 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002788 if (PrevDecl->TypeForDecl)
2789 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2790
John McCall424cec92011-01-19 06:33:43 +00002791 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2792 Decl->TypeForDecl = newType;
2793 Types.push_back(newType);
2794 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002795}
2796
John McCall81904512011-01-06 01:58:22 +00002797QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2798 QualType modifiedType,
2799 QualType equivalentType) {
2800 llvm::FoldingSetNodeID id;
2801 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2802
2803 void *insertPos = 0;
2804 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2805 if (type) return QualType(type, 0);
2806
2807 QualType canon = getCanonicalType(equivalentType);
2808 type = new (*this, TypeAlignment)
2809 AttributedType(canon, attrKind, modifiedType, equivalentType);
2810
2811 Types.push_back(type);
2812 AttributedTypes.InsertNode(type, insertPos);
2813
2814 return QualType(type, 0);
2815}
2816
2817
John McCallcebee162009-10-18 09:09:24 +00002818/// \brief Retrieve a substitution-result type.
2819QualType
2820ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002821 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002822 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002823 && "replacement types must always be canonical");
2824
2825 llvm::FoldingSetNodeID ID;
2826 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2827 void *InsertPos = 0;
2828 SubstTemplateTypeParmType *SubstParm
2829 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2830
2831 if (!SubstParm) {
2832 SubstParm = new (*this, TypeAlignment)
2833 SubstTemplateTypeParmType(Parm, Replacement);
2834 Types.push_back(SubstParm);
2835 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2836 }
2837
2838 return QualType(SubstParm, 0);
2839}
2840
Douglas Gregorada4b792011-01-14 02:55:32 +00002841/// \brief Retrieve a
2842QualType ASTContext::getSubstTemplateTypeParmPackType(
2843 const TemplateTypeParmType *Parm,
2844 const TemplateArgument &ArgPack) {
2845#ifndef NDEBUG
2846 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2847 PEnd = ArgPack.pack_end();
2848 P != PEnd; ++P) {
2849 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2850 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2851 }
2852#endif
2853
2854 llvm::FoldingSetNodeID ID;
2855 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2856 void *InsertPos = 0;
2857 if (SubstTemplateTypeParmPackType *SubstParm
2858 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2859 return QualType(SubstParm, 0);
2860
2861 QualType Canon;
2862 if (!Parm->isCanonicalUnqualified()) {
2863 Canon = getCanonicalType(QualType(Parm, 0));
2864 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2865 ArgPack);
2866 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2867 }
2868
2869 SubstTemplateTypeParmPackType *SubstParm
2870 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2871 ArgPack);
2872 Types.push_back(SubstParm);
2873 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2874 return QualType(SubstParm, 0);
2875}
2876
Douglas Gregoreff93e02009-02-05 23:33:38 +00002877/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002878/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002879/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002880QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002881 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002882 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002883 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002884 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002885 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002886 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002887 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2888
2889 if (TypeParm)
2890 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002891
Chandler Carruth08836322011-05-01 00:51:33 +00002892 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002893 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002894 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002895
2896 TemplateTypeParmType *TypeCheck
2897 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2898 assert(!TypeCheck && "Template type parameter canonical type broken");
2899 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002900 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002901 TypeParm = new (*this, TypeAlignment)
2902 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002903
2904 Types.push_back(TypeParm);
2905 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2906
2907 return QualType(TypeParm, 0);
2908}
2909
John McCalle78aac42010-03-10 03:28:59 +00002910TypeSourceInfo *
2911ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2912 SourceLocation NameLoc,
2913 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002914 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002915 assert(!Name.getAsDependentTemplateName() &&
2916 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002917 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002918
2919 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2920 TemplateSpecializationTypeLoc TL
2921 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002922 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00002923 TL.setTemplateNameLoc(NameLoc);
2924 TL.setLAngleLoc(Args.getLAngleLoc());
2925 TL.setRAngleLoc(Args.getRAngleLoc());
2926 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2927 TL.setArgLocInfo(i, Args[i].getLocInfo());
2928 return DI;
2929}
2930
Mike Stump11289f42009-09-09 15:08:12 +00002931QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002932ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002933 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002934 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002935 assert(!Template.getAsDependentTemplateName() &&
2936 "No dependent template names here!");
2937
John McCall6b51f282009-11-23 01:53:49 +00002938 unsigned NumArgs = Args.size();
2939
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002940 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002941 ArgVec.reserve(NumArgs);
2942 for (unsigned i = 0; i != NumArgs; ++i)
2943 ArgVec.push_back(Args[i].getArgument());
2944
John McCall2408e322010-04-27 00:57:59 +00002945 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002946 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002947}
2948
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002949#ifndef NDEBUG
2950static bool hasAnyPackExpansions(const TemplateArgument *Args,
2951 unsigned NumArgs) {
2952 for (unsigned I = 0; I != NumArgs; ++I)
2953 if (Args[I].isPackExpansion())
2954 return true;
2955
2956 return true;
2957}
2958#endif
2959
John McCall0ad16662009-10-29 08:12:44 +00002960QualType
2961ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002962 const TemplateArgument *Args,
2963 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002964 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002965 assert(!Template.getAsDependentTemplateName() &&
2966 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002967 // Look through qualified template names.
2968 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2969 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002970
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002971 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00002972 Template.getAsTemplateDecl() &&
2973 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00002974 QualType CanonType;
2975 if (!Underlying.isNull())
2976 CanonType = getCanonicalType(Underlying);
2977 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002978 // We can get here with an alias template when the specialization contains
2979 // a pack expansion that does not match up with a parameter pack.
2980 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2981 "Caller must compute aliased type");
2982 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00002983 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2984 NumArgs);
2985 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002986
Douglas Gregora8e02e72009-07-28 23:00:59 +00002987 // Allocate the (non-canonical) template specialization type, but don't
2988 // try to unique it: these types typically have location information that
2989 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002990 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2991 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002992 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002993 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002994 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002995 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2996 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002997
Douglas Gregor8bf42052009-02-09 18:46:07 +00002998 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002999 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003000}
3001
Mike Stump11289f42009-09-09 15:08:12 +00003002QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003003ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3004 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003005 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003006 assert(!Template.getAsDependentTemplateName() &&
3007 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003008
Douglas Gregore29139c2011-03-03 17:04:51 +00003009 // Look through qualified template names.
3010 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3011 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003012
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003013 // Build the canonical template specialization type.
3014 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003015 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003016 CanonArgs.reserve(NumArgs);
3017 for (unsigned I = 0; I != NumArgs; ++I)
3018 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3019
3020 // Determine whether this canonical template specialization type already
3021 // exists.
3022 llvm::FoldingSetNodeID ID;
3023 TemplateSpecializationType::Profile(ID, CanonTemplate,
3024 CanonArgs.data(), NumArgs, *this);
3025
3026 void *InsertPos = 0;
3027 TemplateSpecializationType *Spec
3028 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3029
3030 if (!Spec) {
3031 // Allocate a new canonical template specialization type.
3032 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3033 sizeof(TemplateArgument) * NumArgs),
3034 TypeAlignment);
3035 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3036 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003037 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003038 Types.push_back(Spec);
3039 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3040 }
3041
3042 assert(Spec->isDependentType() &&
3043 "Non-dependent template-id type must have a canonical type");
3044 return QualType(Spec, 0);
3045}
3046
3047QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003048ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3049 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003050 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003051 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003052 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003053
3054 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003055 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003056 if (T)
3057 return QualType(T, 0);
3058
Douglas Gregorc42075a2010-02-04 18:10:26 +00003059 QualType Canon = NamedType;
3060 if (!Canon.isCanonical()) {
3061 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003062 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3063 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003064 (void)CheckT;
3065 }
3066
Abramo Bagnara6150c882010-05-11 21:36:43 +00003067 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003068 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003069 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003070 return QualType(T, 0);
3071}
3072
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003073QualType
Jay Foad39c79802011-01-12 09:06:06 +00003074ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003075 llvm::FoldingSetNodeID ID;
3076 ParenType::Profile(ID, InnerType);
3077
3078 void *InsertPos = 0;
3079 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3080 if (T)
3081 return QualType(T, 0);
3082
3083 QualType Canon = InnerType;
3084 if (!Canon.isCanonical()) {
3085 Canon = getCanonicalType(InnerType);
3086 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3087 assert(!CheckT && "Paren canonical type broken");
3088 (void)CheckT;
3089 }
3090
3091 T = new (*this) ParenType(InnerType, Canon);
3092 Types.push_back(T);
3093 ParenTypes.InsertNode(T, InsertPos);
3094 return QualType(T, 0);
3095}
3096
Douglas Gregor02085352010-03-31 20:19:30 +00003097QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3098 NestedNameSpecifier *NNS,
3099 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003100 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003101 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3102
3103 if (Canon.isNull()) {
3104 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003105 ElaboratedTypeKeyword CanonKeyword = Keyword;
3106 if (Keyword == ETK_None)
3107 CanonKeyword = ETK_Typename;
3108
3109 if (CanonNNS != NNS || CanonKeyword != Keyword)
3110 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003111 }
3112
3113 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003114 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003115
3116 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003117 DependentNameType *T
3118 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003119 if (T)
3120 return QualType(T, 0);
3121
Douglas Gregor02085352010-03-31 20:19:30 +00003122 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003123 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003124 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003125 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003126}
3127
Mike Stump11289f42009-09-09 15:08:12 +00003128QualType
John McCallc392f372010-06-11 00:33:02 +00003129ASTContext::getDependentTemplateSpecializationType(
3130 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003131 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003132 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003133 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003134 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003135 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003136 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3137 ArgCopy.push_back(Args[I].getArgument());
3138 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3139 ArgCopy.size(),
3140 ArgCopy.data());
3141}
3142
3143QualType
3144ASTContext::getDependentTemplateSpecializationType(
3145 ElaboratedTypeKeyword Keyword,
3146 NestedNameSpecifier *NNS,
3147 const IdentifierInfo *Name,
3148 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003149 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003150 assert((!NNS || NNS->isDependent()) &&
3151 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003152
Douglas Gregorc42075a2010-02-04 18:10:26 +00003153 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003154 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3155 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003156
3157 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00003158 DependentTemplateSpecializationType *T
3159 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003160 if (T)
3161 return QualType(T, 0);
3162
John McCallc392f372010-06-11 00:33:02 +00003163 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003164
John McCallc392f372010-06-11 00:33:02 +00003165 ElaboratedTypeKeyword CanonKeyword = Keyword;
3166 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3167
3168 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003169 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003170 for (unsigned I = 0; I != NumArgs; ++I) {
3171 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3172 if (!CanonArgs[I].structurallyEquals(Args[I]))
3173 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003174 }
3175
John McCallc392f372010-06-11 00:33:02 +00003176 QualType Canon;
3177 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3178 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3179 Name, NumArgs,
3180 CanonArgs.data());
3181
3182 // Find the insert position again.
3183 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3184 }
3185
3186 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3187 sizeof(TemplateArgument) * NumArgs),
3188 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003189 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003190 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003191 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003192 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003193 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003194}
3195
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003196QualType ASTContext::getPackExpansionType(QualType Pattern,
3197 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003198 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003199 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003200
3201 assert(Pattern->containsUnexpandedParameterPack() &&
3202 "Pack expansions must expand one or more parameter packs");
3203 void *InsertPos = 0;
3204 PackExpansionType *T
3205 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3206 if (T)
3207 return QualType(T, 0);
3208
3209 QualType Canon;
3210 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003211 Canon = getCanonicalType(Pattern);
3212 // The canonical type might not contain an unexpanded parameter pack, if it
3213 // contains an alias template specialization which ignores one of its
3214 // parameters.
3215 if (Canon->containsUnexpandedParameterPack()) {
3216 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003217
Richard Smith68eea502012-07-16 00:20:35 +00003218 // Find the insert position again, in case we inserted an element into
3219 // PackExpansionTypes and invalidated our insert position.
3220 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3221 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003222 }
3223
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003224 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003225 Types.push_back(T);
3226 PackExpansionTypes.InsertNode(T, InsertPos);
3227 return QualType(T, 0);
3228}
3229
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003230/// CmpProtocolNames - Comparison predicate for sorting protocols
3231/// alphabetically.
3232static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3233 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003234 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003235}
3236
John McCall8b07ec22010-05-15 11:32:37 +00003237static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003238 unsigned NumProtocols) {
3239 if (NumProtocols == 0) return true;
3240
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003241 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3242 return false;
3243
John McCallfc93cf92009-10-22 22:37:11 +00003244 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003245 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3246 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003247 return false;
3248 return true;
3249}
3250
3251static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003252 unsigned &NumProtocols) {
3253 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003254
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003255 // Sort protocols, keyed by name.
3256 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3257
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003258 // Canonicalize.
3259 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3260 Protocols[I] = Protocols[I]->getCanonicalDecl();
3261
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003262 // Remove duplicates.
3263 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3264 NumProtocols = ProtocolsEnd-Protocols;
3265}
3266
John McCall8b07ec22010-05-15 11:32:37 +00003267QualType ASTContext::getObjCObjectType(QualType BaseType,
3268 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003269 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003270 // If the base type is an interface and there aren't any protocols
3271 // to add, then the interface type will do just fine.
3272 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3273 return BaseType;
3274
3275 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003276 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003277 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00003278 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00003279 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3280 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003281
John McCall8b07ec22010-05-15 11:32:37 +00003282 // Build the canonical type, which has the canonical base type and
3283 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003284 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003285 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3286 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3287 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003288 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003289 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003290 unsigned UniqueCount = NumProtocols;
3291
John McCallfc93cf92009-10-22 22:37:11 +00003292 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003293 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3294 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003295 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003296 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3297 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003298 }
3299
3300 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003301 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3302 }
3303
3304 unsigned Size = sizeof(ObjCObjectTypeImpl);
3305 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3306 void *Mem = Allocate(Size, TypeAlignment);
3307 ObjCObjectTypeImpl *T =
3308 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3309
3310 Types.push_back(T);
3311 ObjCObjectTypes.InsertNode(T, InsertPos);
3312 return QualType(T, 0);
3313}
3314
3315/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3316/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003317QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003318 llvm::FoldingSetNodeID ID;
3319 ObjCObjectPointerType::Profile(ID, ObjectT);
3320
3321 void *InsertPos = 0;
3322 if (ObjCObjectPointerType *QT =
3323 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3324 return QualType(QT, 0);
3325
3326 // Find the canonical object type.
3327 QualType Canonical;
3328 if (!ObjectT.isCanonical()) {
3329 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3330
3331 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003332 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3333 }
3334
Douglas Gregorf85bee62010-02-08 22:59:26 +00003335 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003336 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3337 ObjCObjectPointerType *QType =
3338 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003339
Steve Narofffb4330f2009-06-17 22:40:22 +00003340 Types.push_back(QType);
3341 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003342 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003343}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003344
Douglas Gregor1c283312010-08-11 12:19:30 +00003345/// getObjCInterfaceType - Return the unique reference to the type for the
3346/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003347QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3348 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003349 if (Decl->TypeForDecl)
3350 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003351
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003352 if (PrevDecl) {
3353 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3354 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3355 return QualType(PrevDecl->TypeForDecl, 0);
3356 }
3357
Douglas Gregor7671e532011-12-16 16:34:57 +00003358 // Prefer the definition, if there is one.
3359 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3360 Decl = Def;
3361
Douglas Gregor1c283312010-08-11 12:19:30 +00003362 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3363 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3364 Decl->TypeForDecl = T;
3365 Types.push_back(T);
3366 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003367}
3368
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003369/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3370/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003371/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003372/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003373/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003374QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003375 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003376 if (tofExpr->isTypeDependent()) {
3377 llvm::FoldingSetNodeID ID;
3378 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003379
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003380 void *InsertPos = 0;
3381 DependentTypeOfExprType *Canon
3382 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3383 if (Canon) {
3384 // We already have a "canonical" version of an identical, dependent
3385 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003386 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003387 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003388 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003389 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003390 Canon
3391 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003392 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3393 toe = Canon;
3394 }
3395 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003396 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003397 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003398 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003399 Types.push_back(toe);
3400 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003401}
3402
Steve Naroffa773cd52007-08-01 18:02:17 +00003403/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3404/// TypeOfType AST's. The only motivation to unique these nodes would be
3405/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003406/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003407/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003408QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003409 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003410 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003411 Types.push_back(tot);
3412 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003413}
3414
Anders Carlssonad6bd352009-06-24 21:24:56 +00003415
Anders Carlsson81df7b82009-06-24 19:06:50 +00003416/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3417/// DecltypeType AST's. The only motivation to unique these nodes would be
3418/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003419/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003420/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003421QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003422 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003423
3424 // C++0x [temp.type]p2:
3425 // If an expression e involves a template parameter, decltype(e) denotes a
3426 // unique dependent type. Two such decltype-specifiers refer to the same
3427 // type only if their expressions are equivalent (14.5.6.1).
3428 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003429 llvm::FoldingSetNodeID ID;
3430 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003431
Douglas Gregora21f6c32009-07-30 23:36:40 +00003432 void *InsertPos = 0;
3433 DependentDecltypeType *Canon
3434 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3435 if (Canon) {
3436 // We already have a "canonical" version of an equivalent, dependent
3437 // decltype type. Use that as our canonical type.
Richard Smithef8bf432012-08-13 20:08:14 +00003438 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003439 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003440 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003441 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003442 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003443 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3444 dt = Canon;
3445 }
3446 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003447 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3448 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003449 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003450 Types.push_back(dt);
3451 return QualType(dt, 0);
3452}
3453
Alexis Hunte852b102011-05-24 22:41:36 +00003454/// getUnaryTransformationType - We don't unique these, since the memory
3455/// savings are minimal and these are rare.
3456QualType ASTContext::getUnaryTransformType(QualType BaseType,
3457 QualType UnderlyingType,
3458 UnaryTransformType::UTTKind Kind)
3459 const {
3460 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003461 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3462 Kind,
3463 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003464 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003465 Types.push_back(Ty);
3466 return QualType(Ty, 0);
3467}
3468
Richard Smithb2bc2e62011-02-21 20:05:19 +00003469/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003470QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00003471 void *InsertPos = 0;
3472 if (!DeducedType.isNull()) {
3473 // Look in the folding set for an existing type.
3474 llvm::FoldingSetNodeID ID;
3475 AutoType::Profile(ID, DeducedType);
3476 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3477 return QualType(AT, 0);
3478 }
3479
3480 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3481 Types.push_back(AT);
3482 if (InsertPos)
3483 AutoTypes.InsertNode(AT, InsertPos);
3484 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003485}
3486
Eli Friedman0dfb8892011-10-06 23:00:33 +00003487/// getAtomicType - Return the uniqued reference to the atomic type for
3488/// the given value type.
3489QualType ASTContext::getAtomicType(QualType T) const {
3490 // Unique pointers, to guarantee there is only one pointer of a particular
3491 // structure.
3492 llvm::FoldingSetNodeID ID;
3493 AtomicType::Profile(ID, T);
3494
3495 void *InsertPos = 0;
3496 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3497 return QualType(AT, 0);
3498
3499 // If the atomic value type isn't canonical, this won't be a canonical type
3500 // either, so fill in the canonical type field.
3501 QualType Canonical;
3502 if (!T.isCanonical()) {
3503 Canonical = getAtomicType(getCanonicalType(T));
3504
3505 // Get the new insert position for the node we care about.
3506 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3507 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3508 }
3509 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3510 Types.push_back(New);
3511 AtomicTypes.InsertNode(New, InsertPos);
3512 return QualType(New, 0);
3513}
3514
Richard Smith02e85f32011-04-14 22:09:26 +00003515/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3516QualType ASTContext::getAutoDeductType() const {
3517 if (AutoDeductTy.isNull())
3518 AutoDeductTy = getAutoType(QualType());
3519 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3520 return AutoDeductTy;
3521}
3522
3523/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3524QualType ASTContext::getAutoRRefDeductType() const {
3525 if (AutoRRefDeductTy.isNull())
3526 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3527 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3528 return AutoRRefDeductTy;
3529}
3530
Chris Lattnerfb072462007-01-23 05:45:31 +00003531/// getTagDeclType - Return the unique reference to the type for the
3532/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003533QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003534 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003535 // FIXME: What is the design on getTagDeclType when it requires casting
3536 // away const? mutable?
3537 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003538}
3539
Mike Stump11289f42009-09-09 15:08:12 +00003540/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3541/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3542/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003543CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003544 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003545}
Chris Lattnerfb072462007-01-23 05:45:31 +00003546
Hans Wennborg27541db2011-10-27 08:29:09 +00003547/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3548CanQualType ASTContext::getIntMaxType() const {
3549 return getFromTargetType(Target->getIntMaxType());
3550}
3551
3552/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3553CanQualType ASTContext::getUIntMaxType() const {
3554 return getFromTargetType(Target->getUIntMaxType());
3555}
3556
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003557/// getSignedWCharType - Return the type of "signed wchar_t".
3558/// Used when in C++, as a GCC extension.
3559QualType ASTContext::getSignedWCharType() const {
3560 // FIXME: derive from "Target" ?
3561 return WCharTy;
3562}
3563
3564/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3565/// Used when in C++, as a GCC extension.
3566QualType ASTContext::getUnsignedWCharType() const {
3567 // FIXME: derive from "Target" ?
3568 return UnsignedIntTy;
3569}
3570
Hans Wennborg27541db2011-10-27 08:29:09 +00003571/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003572/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3573QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003574 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003575}
3576
Eli Friedman4e91899e2012-11-27 02:58:24 +00003577/// \brief Return the unique type for "pid_t" defined in
3578/// <sys/types.h>. We need this to compute the correct type for vfork().
3579QualType ASTContext::getProcessIDType() const {
3580 return getFromTargetType(Target->getProcessIDType());
3581}
3582
Chris Lattnera21ad802008-04-02 05:18:44 +00003583//===----------------------------------------------------------------------===//
3584// Type Operators
3585//===----------------------------------------------------------------------===//
3586
Jay Foad39c79802011-01-12 09:06:06 +00003587CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003588 // Push qualifiers into arrays, and then discard any remaining
3589 // qualifiers.
3590 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003591 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003592 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003593 QualType Result;
3594 if (isa<ArrayType>(Ty)) {
3595 Result = getArrayDecayedType(QualType(Ty,0));
3596 } else if (isa<FunctionType>(Ty)) {
3597 Result = getPointerType(QualType(Ty, 0));
3598 } else {
3599 Result = QualType(Ty, 0);
3600 }
3601
3602 return CanQualType::CreateUnsafe(Result);
3603}
3604
John McCall6c9dd522011-01-18 07:41:22 +00003605QualType ASTContext::getUnqualifiedArrayType(QualType type,
3606 Qualifiers &quals) {
3607 SplitQualType splitType = type.getSplitUnqualifiedType();
3608
3609 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3610 // the unqualified desugared type and then drops it on the floor.
3611 // We then have to strip that sugar back off with
3612 // getUnqualifiedDesugaredType(), which is silly.
3613 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003614 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003615
3616 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003617 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003618 quals = splitType.Quals;
3619 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003620 }
3621
John McCall6c9dd522011-01-18 07:41:22 +00003622 // Otherwise, recurse on the array's element type.
3623 QualType elementType = AT->getElementType();
3624 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3625
3626 // If that didn't change the element type, AT has no qualifiers, so we
3627 // can just use the results in splitType.
3628 if (elementType == unqualElementType) {
3629 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003630 quals = splitType.Quals;
3631 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003632 }
3633
3634 // Otherwise, add in the qualifiers from the outermost type, then
3635 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003636 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003637
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003638 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003639 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003640 CAT->getSizeModifier(), 0);
3641 }
3642
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003643 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003644 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003645 }
3646
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003647 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003648 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003649 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003650 VAT->getSizeModifier(),
3651 VAT->getIndexTypeCVRQualifiers(),
3652 VAT->getBracketsRange());
3653 }
3654
3655 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003656 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003657 DSAT->getSizeModifier(), 0,
3658 SourceRange());
3659}
3660
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003661/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3662/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3663/// they point to and return true. If T1 and T2 aren't pointer types
3664/// or pointer-to-member types, or if they are not similar at this
3665/// level, returns false and leaves T1 and T2 unchanged. Top-level
3666/// qualifiers on T1 and T2 are ignored. This function will typically
3667/// be called in a loop that successively "unwraps" pointer and
3668/// pointer-to-member types to compare them at each level.
3669bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3670 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3671 *T2PtrType = T2->getAs<PointerType>();
3672 if (T1PtrType && T2PtrType) {
3673 T1 = T1PtrType->getPointeeType();
3674 T2 = T2PtrType->getPointeeType();
3675 return true;
3676 }
3677
3678 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3679 *T2MPType = T2->getAs<MemberPointerType>();
3680 if (T1MPType && T2MPType &&
3681 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3682 QualType(T2MPType->getClass(), 0))) {
3683 T1 = T1MPType->getPointeeType();
3684 T2 = T2MPType->getPointeeType();
3685 return true;
3686 }
3687
David Blaikiebbafb8a2012-03-11 07:00:24 +00003688 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003689 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3690 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3691 if (T1OPType && T2OPType) {
3692 T1 = T1OPType->getPointeeType();
3693 T2 = T2OPType->getPointeeType();
3694 return true;
3695 }
3696 }
3697
3698 // FIXME: Block pointers, too?
3699
3700 return false;
3701}
3702
Jay Foad39c79802011-01-12 09:06:06 +00003703DeclarationNameInfo
3704ASTContext::getNameForTemplate(TemplateName Name,
3705 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003706 switch (Name.getKind()) {
3707 case TemplateName::QualifiedTemplate:
3708 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003709 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003710 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3711 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003712
John McCalld9dfe3a2011-06-30 08:33:18 +00003713 case TemplateName::OverloadedTemplate: {
3714 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3715 // DNInfo work in progress: CHECKME: what about DNLoc?
3716 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3717 }
3718
3719 case TemplateName::DependentTemplate: {
3720 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003721 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003722 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003723 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3724 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003725 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003726 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3727 // DNInfo work in progress: FIXME: source locations?
3728 DeclarationNameLoc DNLoc;
3729 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3730 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3731 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003732 }
3733 }
3734
John McCalld9dfe3a2011-06-30 08:33:18 +00003735 case TemplateName::SubstTemplateTemplateParm: {
3736 SubstTemplateTemplateParmStorage *subst
3737 = Name.getAsSubstTemplateTemplateParm();
3738 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3739 NameLoc);
3740 }
3741
3742 case TemplateName::SubstTemplateTemplateParmPack: {
3743 SubstTemplateTemplateParmPackStorage *subst
3744 = Name.getAsSubstTemplateTemplateParmPack();
3745 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3746 NameLoc);
3747 }
3748 }
3749
3750 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003751}
3752
Jay Foad39c79802011-01-12 09:06:06 +00003753TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003754 switch (Name.getKind()) {
3755 case TemplateName::QualifiedTemplate:
3756 case TemplateName::Template: {
3757 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003758 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003759 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003760 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3761
3762 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003763 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003764 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003765
John McCalld9dfe3a2011-06-30 08:33:18 +00003766 case TemplateName::OverloadedTemplate:
3767 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003768
John McCalld9dfe3a2011-06-30 08:33:18 +00003769 case TemplateName::DependentTemplate: {
3770 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3771 assert(DTN && "Non-dependent template names must refer to template decls.");
3772 return DTN->CanonicalTemplateName;
3773 }
3774
3775 case TemplateName::SubstTemplateTemplateParm: {
3776 SubstTemplateTemplateParmStorage *subst
3777 = Name.getAsSubstTemplateTemplateParm();
3778 return getCanonicalTemplateName(subst->getReplacement());
3779 }
3780
3781 case TemplateName::SubstTemplateTemplateParmPack: {
3782 SubstTemplateTemplateParmPackStorage *subst
3783 = Name.getAsSubstTemplateTemplateParmPack();
3784 TemplateTemplateParmDecl *canonParameter
3785 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3786 TemplateArgument canonArgPack
3787 = getCanonicalTemplateArgument(subst->getArgumentPack());
3788 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3789 }
3790 }
3791
3792 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003793}
3794
Douglas Gregoradee3e32009-11-11 23:06:43 +00003795bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3796 X = getCanonicalTemplateName(X);
3797 Y = getCanonicalTemplateName(Y);
3798 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3799}
3800
Mike Stump11289f42009-09-09 15:08:12 +00003801TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003802ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003803 switch (Arg.getKind()) {
3804 case TemplateArgument::Null:
3805 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003806
Douglas Gregora8e02e72009-07-28 23:00:59 +00003807 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003808 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003809
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003810 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00003811 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
3812 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003813 }
Mike Stump11289f42009-09-09 15:08:12 +00003814
Eli Friedmanb826a002012-09-26 02:36:12 +00003815 case TemplateArgument::NullPtr:
3816 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
3817 /*isNullPtr*/true);
3818
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003819 case TemplateArgument::Template:
3820 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003821
3822 case TemplateArgument::TemplateExpansion:
3823 return TemplateArgument(getCanonicalTemplateName(
3824 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003825 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003826
Douglas Gregora8e02e72009-07-28 23:00:59 +00003827 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00003828 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003829
Douglas Gregora8e02e72009-07-28 23:00:59 +00003830 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003831 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003832
Douglas Gregora8e02e72009-07-28 23:00:59 +00003833 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003834 if (Arg.pack_size() == 0)
3835 return Arg;
3836
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003837 TemplateArgument *CanonArgs
3838 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003839 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003840 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003841 AEnd = Arg.pack_end();
3842 A != AEnd; (void)++A, ++Idx)
3843 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003844
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003845 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003846 }
3847 }
3848
3849 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003850 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003851}
3852
Douglas Gregor333489b2009-03-27 23:10:48 +00003853NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003854ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003855 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003856 return 0;
3857
3858 switch (NNS->getKind()) {
3859 case NestedNameSpecifier::Identifier:
3860 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003861 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003862 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3863 NNS->getAsIdentifier());
3864
3865 case NestedNameSpecifier::Namespace:
3866 // A namespace is canonical; build a nested-name-specifier with
3867 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003868 return NestedNameSpecifier::Create(*this, 0,
3869 NNS->getAsNamespace()->getOriginalNamespace());
3870
3871 case NestedNameSpecifier::NamespaceAlias:
3872 // A namespace is canonical; build a nested-name-specifier with
3873 // this namespace and no prefix.
3874 return NestedNameSpecifier::Create(*this, 0,
3875 NNS->getAsNamespaceAlias()->getNamespace()
3876 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003877
3878 case NestedNameSpecifier::TypeSpec:
3879 case NestedNameSpecifier::TypeSpecWithTemplate: {
3880 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003881
3882 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3883 // break it apart into its prefix and identifier, then reconsititute those
3884 // as the canonical nested-name-specifier. This is required to canonicalize
3885 // a dependent nested-name-specifier involving typedefs of dependent-name
3886 // types, e.g.,
3887 // typedef typename T::type T1;
3888 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00003889 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3890 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00003891 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003892
Eli Friedman5358a0a2012-03-03 04:09:56 +00003893 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3894 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3895 // first place?
John McCall33ddac02011-01-19 10:06:00 +00003896 return NestedNameSpecifier::Create(*this, 0, false,
3897 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003898 }
3899
3900 case NestedNameSpecifier::Global:
3901 // The global specifier is canonical and unique.
3902 return NNS;
3903 }
3904
David Blaikie8a40f702012-01-17 06:56:22 +00003905 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00003906}
3907
Chris Lattner7adf0762008-08-04 07:31:14 +00003908
Jay Foad39c79802011-01-12 09:06:06 +00003909const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003910 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003911 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003912 // Handle the common positive case fast.
3913 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3914 return AT;
3915 }
Mike Stump11289f42009-09-09 15:08:12 +00003916
John McCall8ccfcb52009-09-24 19:53:00 +00003917 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003918 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003919 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003920
John McCall8ccfcb52009-09-24 19:53:00 +00003921 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003922 // implements C99 6.7.3p8: "If the specification of an array type includes
3923 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003924
Chris Lattner7adf0762008-08-04 07:31:14 +00003925 // If we get here, we either have type qualifiers on the type, or we have
3926 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003927 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003928
John McCall33ddac02011-01-19 10:06:00 +00003929 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003930 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00003931
Chris Lattner7adf0762008-08-04 07:31:14 +00003932 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00003933 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00003934 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003935 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003936
Chris Lattner7adf0762008-08-04 07:31:14 +00003937 // Otherwise, we have an array and we have qualifiers on it. Push the
3938 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003939 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003940
Chris Lattner7adf0762008-08-04 07:31:14 +00003941 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3942 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3943 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003944 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003945 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3946 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3947 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003948 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003949
Mike Stump11289f42009-09-09 15:08:12 +00003950 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003951 = dyn_cast<DependentSizedArrayType>(ATy))
3952 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003953 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003954 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003955 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003956 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003957 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003958
Chris Lattner7adf0762008-08-04 07:31:14 +00003959 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003960 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003961 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003962 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003963 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003964 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003965}
3966
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003967QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003968 // C99 6.7.5.3p7:
3969 // A declaration of a parameter as "array of type" shall be
3970 // adjusted to "qualified pointer to type", where the type
3971 // qualifiers (if any) are those specified within the [ and ] of
3972 // the array type derivation.
3973 if (T->isArrayType())
3974 return getArrayDecayedType(T);
3975
3976 // C99 6.7.5.3p8:
3977 // A declaration of a parameter as "function returning type"
3978 // shall be adjusted to "pointer to function returning type", as
3979 // in 6.3.2.1.
3980 if (T->isFunctionType())
3981 return getPointerType(T);
3982
3983 return T;
3984}
3985
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003986QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003987 T = getVariableArrayDecayedType(T);
3988 T = getAdjustedParameterType(T);
3989 return T.getUnqualifiedType();
3990}
3991
Chris Lattnera21ad802008-04-02 05:18:44 +00003992/// getArrayDecayedType - Return the properly qualified result of decaying the
3993/// specified array type to a pointer. This operation is non-trivial when
3994/// handling typedefs etc. The canonical type of "T" must be an array type,
3995/// this returns a pointer to a properly qualified element of the array.
3996///
3997/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003998QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003999 // Get the element type with 'getAsArrayType' so that we don't lose any
4000 // typedefs in the element type of the array. This also handles propagation
4001 // of type qualifiers from the array type into the element type if present
4002 // (C99 6.7.3p8).
4003 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4004 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004005
Chris Lattner7adf0762008-08-04 07:31:14 +00004006 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004007
4008 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004009 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004010}
4011
John McCall33ddac02011-01-19 10:06:00 +00004012QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4013 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004014}
4015
John McCall33ddac02011-01-19 10:06:00 +00004016QualType ASTContext::getBaseElementType(QualType type) const {
4017 Qualifiers qs;
4018 while (true) {
4019 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004020 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004021 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004022
John McCall33ddac02011-01-19 10:06:00 +00004023 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004024 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004025 }
Mike Stump11289f42009-09-09 15:08:12 +00004026
John McCall33ddac02011-01-19 10:06:00 +00004027 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004028}
4029
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004030/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004031uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004032ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4033 uint64_t ElementCount = 1;
4034 do {
4035 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004036 CA = dyn_cast_or_null<ConstantArrayType>(
4037 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004038 } while (CA);
4039 return ElementCount;
4040}
4041
Steve Naroff0af91202007-04-27 21:51:21 +00004042/// getFloatingRank - Return a relative rank for floating point types.
4043/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004044static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004045 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004046 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004047
John McCall9dd450b2009-09-21 23:43:11 +00004048 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4049 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004050 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004051 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004052 case BuiltinType::Float: return FloatRank;
4053 case BuiltinType::Double: return DoubleRank;
4054 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004055 }
4056}
4057
Mike Stump11289f42009-09-09 15:08:12 +00004058/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4059/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004060/// 'typeDomain' is a real floating point or complex type.
4061/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004062QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4063 QualType Domain) const {
4064 FloatingRank EltRank = getFloatingRank(Size);
4065 if (Domain->isComplexType()) {
4066 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004067 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004068 case FloatRank: return FloatComplexTy;
4069 case DoubleRank: return DoubleComplexTy;
4070 case LongDoubleRank: return LongDoubleComplexTy;
4071 }
Steve Naroff0af91202007-04-27 21:51:21 +00004072 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004073
4074 assert(Domain->isRealFloatingType() && "Unknown domain!");
4075 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004076 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004077 case FloatRank: return FloatTy;
4078 case DoubleRank: return DoubleTy;
4079 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004080 }
David Blaikief47fa302012-01-17 02:30:50 +00004081 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004082}
4083
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004084/// getFloatingTypeOrder - Compare the rank of the two specified floating
4085/// point types, ignoring the domain of the type (i.e. 'double' ==
4086/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004087/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004088int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004089 FloatingRank LHSR = getFloatingRank(LHS);
4090 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004091
Chris Lattnerb90739d2008-04-06 23:38:49 +00004092 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004093 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004094 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004095 return 1;
4096 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004097}
4098
Chris Lattner76a00cf2008-04-06 22:59:24 +00004099/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4100/// routine will assert if passed a built-in type that isn't an integer or enum,
4101/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004102unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004103 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004104
Chris Lattner76a00cf2008-04-06 22:59:24 +00004105 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004106 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004107 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004108 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004109 case BuiltinType::Char_S:
4110 case BuiltinType::Char_U:
4111 case BuiltinType::SChar:
4112 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004113 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004114 case BuiltinType::Short:
4115 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004116 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004117 case BuiltinType::Int:
4118 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004119 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004120 case BuiltinType::Long:
4121 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004122 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004123 case BuiltinType::LongLong:
4124 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004125 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004126 case BuiltinType::Int128:
4127 case BuiltinType::UInt128:
4128 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004129 }
4130}
4131
Eli Friedman629ffb92009-08-20 04:21:42 +00004132/// \brief Whether this is a promotable bitfield reference according
4133/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4134///
4135/// \returns the type this bit-field will promote to, or NULL if no
4136/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004137QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004138 if (E->isTypeDependent() || E->isValueDependent())
4139 return QualType();
4140
Eli Friedman629ffb92009-08-20 04:21:42 +00004141 FieldDecl *Field = E->getBitField();
4142 if (!Field)
4143 return QualType();
4144
4145 QualType FT = Field->getType();
4146
Richard Smithcaf33902011-10-10 18:28:20 +00004147 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004148 uint64_t IntSize = getTypeSize(IntTy);
4149 // GCC extension compatibility: if the bit-field size is less than or equal
4150 // to the size of int, it gets promoted no matter what its type is.
4151 // For instance, unsigned long bf : 4 gets promoted to signed int.
4152 if (BitWidth < IntSize)
4153 return IntTy;
4154
4155 if (BitWidth == IntSize)
4156 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4157
4158 // Types bigger than int are not subject to promotions, and therefore act
4159 // like the base type.
4160 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4161 // is ridiculous.
4162 return QualType();
4163}
4164
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004165/// getPromotedIntegerType - Returns the type that Promotable will
4166/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4167/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004168QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004169 assert(!Promotable.isNull());
4170 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004171 if (const EnumType *ET = Promotable->getAs<EnumType>())
4172 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004173
4174 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4175 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4176 // (3.9.1) can be converted to a prvalue of the first of the following
4177 // types that can represent all the values of its underlying type:
4178 // int, unsigned int, long int, unsigned long int, long long int, or
4179 // unsigned long long int [...]
4180 // FIXME: Is there some better way to compute this?
4181 if (BT->getKind() == BuiltinType::WChar_S ||
4182 BT->getKind() == BuiltinType::WChar_U ||
4183 BT->getKind() == BuiltinType::Char16 ||
4184 BT->getKind() == BuiltinType::Char32) {
4185 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4186 uint64_t FromSize = getTypeSize(BT);
4187 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4188 LongLongTy, UnsignedLongLongTy };
4189 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4190 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4191 if (FromSize < ToSize ||
4192 (FromSize == ToSize &&
4193 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4194 return PromoteTypes[Idx];
4195 }
4196 llvm_unreachable("char type should fit into long long");
4197 }
4198 }
4199
4200 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004201 if (Promotable->isSignedIntegerType())
4202 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004203 uint64_t PromotableSize = getIntWidth(Promotable);
4204 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004205 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4206 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4207}
4208
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004209/// \brief Recurses in pointer/array types until it finds an objc retainable
4210/// type and returns its ownership.
4211Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4212 while (!T.isNull()) {
4213 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4214 return T.getObjCLifetime();
4215 if (T->isArrayType())
4216 T = getBaseElementType(T);
4217 else if (const PointerType *PT = T->getAs<PointerType>())
4218 T = PT->getPointeeType();
4219 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004220 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004221 else
4222 break;
4223 }
4224
4225 return Qualifiers::OCL_None;
4226}
4227
Mike Stump11289f42009-09-09 15:08:12 +00004228/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004229/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004230/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004231int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004232 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4233 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004234 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004235
Chris Lattner76a00cf2008-04-06 22:59:24 +00004236 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4237 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004238
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004239 unsigned LHSRank = getIntegerRank(LHSC);
4240 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004241
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004242 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4243 if (LHSRank == RHSRank) return 0;
4244 return LHSRank > RHSRank ? 1 : -1;
4245 }
Mike Stump11289f42009-09-09 15:08:12 +00004246
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004247 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4248 if (LHSUnsigned) {
4249 // If the unsigned [LHS] type is larger, return it.
4250 if (LHSRank >= RHSRank)
4251 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004252
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004253 // If the signed type can represent all values of the unsigned type, it
4254 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004255 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004256 return -1;
4257 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004258
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004259 // If the unsigned [RHS] type is larger, return it.
4260 if (RHSRank >= LHSRank)
4261 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004262
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004263 // If the signed type can represent all values of the unsigned type, it
4264 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004265 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004266 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004267}
Anders Carlsson98f07902007-08-17 05:31:46 +00004268
Anders Carlsson6d417272009-11-14 21:45:58 +00004269static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004270CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4271 DeclContext *DC, IdentifierInfo *Id) {
4272 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004273 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004274 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004275 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004276 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004277}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004278
Mike Stump11289f42009-09-09 15:08:12 +00004279// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004280QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004281 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00004282 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004283 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004284 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00004285 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004286
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004287 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004288
Anders Carlsson98f07902007-08-17 05:31:46 +00004289 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004290 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004291 // int flags;
4292 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004293 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004294 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004295 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004296 FieldTypes[3] = LongTy;
4297
Anders Carlsson98f07902007-08-17 05:31:46 +00004298 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004299 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004300 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004301 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004302 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00004303 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00004304 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004305 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004306 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004307 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004308 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004309 }
4310
Douglas Gregord5058122010-02-11 01:19:42 +00004311 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004312 }
Mike Stump11289f42009-09-09 15:08:12 +00004313
Anders Carlsson98f07902007-08-17 05:31:46 +00004314 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004315}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004316
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004317QualType ASTContext::getObjCSuperType() const {
4318 if (ObjCSuperType.isNull()) {
4319 RecordDecl *ObjCSuperTypeDecl =
4320 CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get("objc_super"));
4321 TUDecl->addDecl(ObjCSuperTypeDecl);
4322 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4323 }
4324 return ObjCSuperType;
4325}
4326
Douglas Gregor512b0772009-04-23 22:29:11 +00004327void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004328 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004329 assert(Rec && "Invalid CFConstantStringType");
4330 CFConstantStringTypeDecl = Rec->getDecl();
4331}
4332
Jay Foad39c79802011-01-12 09:06:06 +00004333QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004334 if (BlockDescriptorType)
4335 return getTagDeclType(BlockDescriptorType);
4336
4337 RecordDecl *T;
4338 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004339 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004340 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00004341 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004342
4343 QualType FieldTypes[] = {
4344 UnsignedLongTy,
4345 UnsignedLongTy,
4346 };
4347
4348 const char *FieldNames[] = {
4349 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004350 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004351 };
4352
4353 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004354 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00004355 SourceLocation(),
4356 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004357 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00004358 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004359 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004360 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004361 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00004362 T->addDecl(Field);
4363 }
4364
Douglas Gregord5058122010-02-11 01:19:42 +00004365 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004366
4367 BlockDescriptorType = T;
4368
4369 return getTagDeclType(BlockDescriptorType);
4370}
4371
Jay Foad39c79802011-01-12 09:06:06 +00004372QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004373 if (BlockDescriptorExtendedType)
4374 return getTagDeclType(BlockDescriptorExtendedType);
4375
4376 RecordDecl *T;
4377 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004378 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004379 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00004380 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004381
4382 QualType FieldTypes[] = {
4383 UnsignedLongTy,
4384 UnsignedLongTy,
4385 getPointerType(VoidPtrTy),
4386 getPointerType(VoidPtrTy)
4387 };
4388
4389 const char *FieldNames[] = {
4390 "reserved",
4391 "Size",
4392 "CopyFuncPtr",
4393 "DestroyFuncPtr"
4394 };
4395
4396 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004397 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004398 SourceLocation(),
4399 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004400 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004401 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004402 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004403 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004404 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004405 T->addDecl(Field);
4406 }
4407
Douglas Gregord5058122010-02-11 01:19:42 +00004408 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004409
4410 BlockDescriptorExtendedType = T;
4411
4412 return getTagDeclType(BlockDescriptorExtendedType);
4413}
4414
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004415/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4416/// requires copy/dispose. Note that this must match the logic
4417/// in buildByrefHelpers.
4418bool ASTContext::BlockRequiresCopying(QualType Ty,
4419 const VarDecl *D) {
4420 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4421 const Expr *copyExpr = getBlockVarCopyInits(D);
4422 if (!copyExpr && record->hasTrivialDestructor()) return false;
4423
Mike Stump94967902009-10-21 18:16:27 +00004424 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004425 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004426
4427 if (!Ty->isObjCRetainableType()) return false;
4428
4429 Qualifiers qs = Ty.getQualifiers();
4430
4431 // If we have lifetime, that dominates.
4432 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4433 assert(getLangOpts().ObjCAutoRefCount);
4434
4435 switch (lifetime) {
4436 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4437
4438 // These are just bits as far as the runtime is concerned.
4439 case Qualifiers::OCL_ExplicitNone:
4440 case Qualifiers::OCL_Autoreleasing:
4441 return false;
4442
4443 // Tell the runtime that this is ARC __weak, called by the
4444 // byref routines.
4445 case Qualifiers::OCL_Weak:
4446 // ARC __strong __block variables need to be retained.
4447 case Qualifiers::OCL_Strong:
4448 return true;
4449 }
4450 llvm_unreachable("fell out of lifetime switch!");
4451 }
4452 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4453 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004454}
4455
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004456bool ASTContext::getByrefLifetime(QualType Ty,
4457 Qualifiers::ObjCLifetime &LifeTime,
4458 bool &HasByrefExtendedLayout) const {
4459
4460 if (!getLangOpts().ObjC1 ||
4461 getLangOpts().getGC() != LangOptions::NonGC)
4462 return false;
4463
4464 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004465 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004466 HasByrefExtendedLayout = true;
4467 LifeTime = Qualifiers::OCL_None;
4468 }
4469 else if (getLangOpts().ObjCAutoRefCount)
4470 LifeTime = Ty.getObjCLifetime();
4471 // MRR.
4472 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4473 LifeTime = Qualifiers::OCL_ExplicitNone;
4474 else
4475 LifeTime = Qualifiers::OCL_None;
4476 return true;
4477}
4478
Douglas Gregorbab8a962011-09-08 01:46:34 +00004479TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4480 if (!ObjCInstanceTypeDecl)
4481 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4482 getTranslationUnitDecl(),
4483 SourceLocation(),
4484 SourceLocation(),
4485 &Idents.get("instancetype"),
4486 getTrivialTypeSourceInfo(getObjCIdType()));
4487 return ObjCInstanceTypeDecl;
4488}
4489
Anders Carlsson18acd442007-10-29 06:33:42 +00004490// This returns true if a type has been typedefed to BOOL:
4491// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004492static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004493 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004494 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4495 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004496
Anders Carlssond8499822007-10-29 05:01:08 +00004497 return false;
4498}
4499
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004500/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004501/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004502CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004503 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4504 return CharUnits::Zero();
4505
Ken Dyck40775002010-01-11 17:06:35 +00004506 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004507
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004508 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004509 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004510 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004511 // Treat arrays as pointers, since that's how they're passed in.
4512 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004513 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004514 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004515}
4516
4517static inline
4518std::string charUnitsToString(const CharUnits &CU) {
4519 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004520}
4521
John McCall351762c2011-02-07 10:33:21 +00004522/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004523/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004524std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4525 std::string S;
4526
David Chisnall950a9512009-11-17 19:33:30 +00004527 const BlockDecl *Decl = Expr->getBlockDecl();
4528 QualType BlockTy =
4529 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4530 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004531 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004532 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4533 BlockTy->getAs<FunctionType>()->getResultType(),
4534 S, true /*Extended*/);
4535 else
4536 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4537 S);
David Chisnall950a9512009-11-17 19:33:30 +00004538 // Compute size of all parameters.
4539 // Start with computing size of a pointer in number of bytes.
4540 // FIXME: There might(should) be a better way of doing this computation!
4541 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004542 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4543 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004544 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004545 E = Decl->param_end(); PI != E; ++PI) {
4546 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004547 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004548 if (sz.isZero())
4549 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004550 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004551 ParmOffset += sz;
4552 }
4553 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004554 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004555 // Block pointer and offset.
4556 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004557
4558 // Argument types.
4559 ParmOffset = PtrSize;
4560 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4561 Decl->param_end(); PI != E; ++PI) {
4562 ParmVarDecl *PVDecl = *PI;
4563 QualType PType = PVDecl->getOriginalType();
4564 if (const ArrayType *AT =
4565 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4566 // Use array's original type only if it has known number of
4567 // elements.
4568 if (!isa<ConstantArrayType>(AT))
4569 PType = PVDecl->getType();
4570 } else if (PType->isFunctionType())
4571 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004572 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004573 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4574 S, true /*Extended*/);
4575 else
4576 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004577 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004578 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004579 }
John McCall351762c2011-02-07 10:33:21 +00004580
4581 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004582}
4583
Douglas Gregora9d84932011-05-27 01:19:52 +00004584bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004585 std::string& S) {
4586 // Encode result type.
4587 getObjCEncodingForType(Decl->getResultType(), S);
4588 CharUnits ParmOffset;
4589 // Compute size of all parameters.
4590 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4591 E = Decl->param_end(); PI != E; ++PI) {
4592 QualType PType = (*PI)->getType();
4593 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004594 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004595 continue;
4596
David Chisnall50e4eba2010-12-30 14:05:53 +00004597 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004598 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004599 ParmOffset += sz;
4600 }
4601 S += charUnitsToString(ParmOffset);
4602 ParmOffset = CharUnits::Zero();
4603
4604 // Argument types.
4605 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4606 E = Decl->param_end(); PI != E; ++PI) {
4607 ParmVarDecl *PVDecl = *PI;
4608 QualType PType = PVDecl->getOriginalType();
4609 if (const ArrayType *AT =
4610 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4611 // Use array's original type only if it has known number of
4612 // elements.
4613 if (!isa<ConstantArrayType>(AT))
4614 PType = PVDecl->getType();
4615 } else if (PType->isFunctionType())
4616 PType = PVDecl->getType();
4617 getObjCEncodingForType(PType, S);
4618 S += charUnitsToString(ParmOffset);
4619 ParmOffset += getObjCEncodingTypeSize(PType);
4620 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004621
4622 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004623}
4624
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004625/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4626/// method parameter or return type. If Extended, include class names and
4627/// block object types.
4628void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4629 QualType T, std::string& S,
4630 bool Extended) const {
4631 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4632 getObjCEncodingForTypeQualifier(QT, S);
4633 // Encode parameter type.
4634 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4635 true /*OutermostType*/,
4636 false /*EncodingProperty*/,
4637 false /*StructField*/,
4638 Extended /*EncodeBlockParameters*/,
4639 Extended /*EncodeClassNames*/);
4640}
4641
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004642/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004643/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004644bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004645 std::string& S,
4646 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004647 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004648 // Encode return type.
4649 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4650 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004651 // Compute size of all parameters.
4652 // Start with computing size of a pointer in number of bytes.
4653 // FIXME: There might(should) be a better way of doing this computation!
4654 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004655 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004656 // The first two arguments (self and _cmd) are pointers; account for
4657 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004658 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004659 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004660 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004661 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004662 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004663 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004664 continue;
4665
Ken Dyck40775002010-01-11 17:06:35 +00004666 assert (sz.isPositive() &&
4667 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004668 ParmOffset += sz;
4669 }
Ken Dyck40775002010-01-11 17:06:35 +00004670 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004671 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004672 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004673
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004674 // Argument types.
4675 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004676 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004677 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004678 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004679 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004680 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004681 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4682 // Use array's original type only if it has known number of
4683 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004684 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004685 PType = PVDecl->getType();
4686 } else if (PType->isFunctionType())
4687 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004688 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4689 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004690 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004691 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004692 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004693
4694 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004695}
4696
Daniel Dunbar4932b362008-08-28 04:38:10 +00004697/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004698/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004699/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4700/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004701/// Property attributes are stored as a comma-delimited C string. The simple
4702/// attributes readonly and bycopy are encoded as single characters. The
4703/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4704/// encoded as single characters, followed by an identifier. Property types
4705/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004706/// these attributes are defined by the following enumeration:
4707/// @code
4708/// enum PropertyAttributes {
4709/// kPropertyReadOnly = 'R', // property is read-only.
4710/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4711/// kPropertyByref = '&', // property is a reference to the value last assigned
4712/// kPropertyDynamic = 'D', // property is dynamic
4713/// kPropertyGetter = 'G', // followed by getter selector name
4714/// kPropertySetter = 'S', // followed by setter selector name
4715/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004716/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004717/// kPropertyWeak = 'W' // 'weak' property
4718/// kPropertyStrong = 'P' // property GC'able
4719/// kPropertyNonAtomic = 'N' // property non-atomic
4720/// };
4721/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004722void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004723 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004724 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004725 // Collect information from the property implementation decl(s).
4726 bool Dynamic = false;
4727 ObjCPropertyImplDecl *SynthesizePID = 0;
4728
4729 // FIXME: Duplicated code due to poor abstraction.
4730 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004731 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004732 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4733 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004734 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004735 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004736 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004737 if (PID->getPropertyDecl() == PD) {
4738 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4739 Dynamic = true;
4740 } else {
4741 SynthesizePID = PID;
4742 }
4743 }
4744 }
4745 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004746 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004747 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004748 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004749 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004750 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004751 if (PID->getPropertyDecl() == PD) {
4752 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4753 Dynamic = true;
4754 } else {
4755 SynthesizePID = PID;
4756 }
4757 }
Mike Stump11289f42009-09-09 15:08:12 +00004758 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004759 }
4760 }
4761
4762 // FIXME: This is not very efficient.
4763 S = "T";
4764
4765 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004766 // GCC has some special rules regarding encoding of properties which
4767 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004768 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004769 true /* outermost type */,
4770 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004771
4772 if (PD->isReadOnly()) {
4773 S += ",R";
4774 } else {
4775 switch (PD->getSetterKind()) {
4776 case ObjCPropertyDecl::Assign: break;
4777 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004778 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004779 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004780 }
4781 }
4782
4783 // It really isn't clear at all what this means, since properties
4784 // are "dynamic by default".
4785 if (Dynamic)
4786 S += ",D";
4787
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004788 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4789 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004790
Daniel Dunbar4932b362008-08-28 04:38:10 +00004791 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4792 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004793 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004794 }
4795
4796 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4797 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004798 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004799 }
4800
4801 if (SynthesizePID) {
4802 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4803 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004804 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004805 }
4806
4807 // FIXME: OBJCGC: weak & strong
4808}
4809
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004810/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004811/// Another legacy compatibility encoding: 32-bit longs are encoded as
4812/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004813/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4814///
4815void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004816 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004817 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004818 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004819 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004820 else
Jay Foad39c79802011-01-12 09:06:06 +00004821 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004822 PointeeTy = IntTy;
4823 }
4824 }
4825}
4826
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004827void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004828 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004829 // We follow the behavior of gcc, expanding structures which are
4830 // directly pointed to, and expanding embedded structures. Note that
4831 // these rules are sufficient to prevent recursive encoding of the
4832 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004833 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004834 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004835}
4836
John McCall393a78d2012-12-20 02:45:14 +00004837static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
4838 BuiltinType::Kind kind) {
4839 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004840 case BuiltinType::Void: return 'v';
4841 case BuiltinType::Bool: return 'B';
4842 case BuiltinType::Char_U:
4843 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00004844 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00004845 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00004846 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00004847 case BuiltinType::UInt: return 'I';
4848 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00004849 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004850 case BuiltinType::UInt128: return 'T';
4851 case BuiltinType::ULongLong: return 'Q';
4852 case BuiltinType::Char_S:
4853 case BuiltinType::SChar: return 'c';
4854 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004855 case BuiltinType::WChar_S:
4856 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004857 case BuiltinType::Int: return 'i';
4858 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00004859 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004860 case BuiltinType::LongLong: return 'q';
4861 case BuiltinType::Int128: return 't';
4862 case BuiltinType::Float: return 'f';
4863 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004864 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00004865 case BuiltinType::NullPtr: return '*'; // like char*
4866
4867 case BuiltinType::Half:
4868 // FIXME: potentially need @encodes for these!
4869 return ' ';
4870
4871 case BuiltinType::ObjCId:
4872 case BuiltinType::ObjCClass:
4873 case BuiltinType::ObjCSel:
4874 llvm_unreachable("@encoding ObjC primitive type");
4875
4876 // OpenCL and placeholder types don't need @encodings.
4877 case BuiltinType::OCLImage1d:
4878 case BuiltinType::OCLImage1dArray:
4879 case BuiltinType::OCLImage1dBuffer:
4880 case BuiltinType::OCLImage2d:
4881 case BuiltinType::OCLImage2dArray:
4882 case BuiltinType::OCLImage3d:
4883 case BuiltinType::Dependent:
4884#define BUILTIN_TYPE(KIND, ID)
4885#define PLACEHOLDER_TYPE(KIND, ID) \
4886 case BuiltinType::KIND:
4887#include "clang/AST/BuiltinTypes.def"
4888 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00004889 }
David Blaikie5a6a0202013-01-09 17:48:41 +00004890 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00004891}
4892
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004893static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4894 EnumDecl *Enum = ET->getDecl();
4895
4896 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4897 if (!Enum->isFixed())
4898 return 'i';
4899
4900 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00004901 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
4902 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004903}
4904
Jay Foad39c79802011-01-12 09:06:06 +00004905static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004906 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00004907 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004908 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004909 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4910 // The GNU runtime requires more information; bitfields are encoded as b,
4911 // then the offset (in bits) of the first element, then the type of the
4912 // bitfield, then the size in bits. For example, in this structure:
4913 //
4914 // struct
4915 // {
4916 // int integer;
4917 // int flags:2;
4918 // };
4919 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4920 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4921 // information is not especially sensible, but we're stuck with it for
4922 // compatibility with GCC, although providing it breaks anything that
4923 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00004924 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004925 const RecordDecl *RD = FD->getParent();
4926 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004927 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004928 if (const EnumType *ET = T->getAs<EnumType>())
4929 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00004930 else {
4931 const BuiltinType *BT = T->castAs<BuiltinType>();
4932 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
4933 }
David Chisnallb190a2c2010-06-04 01:10:52 +00004934 }
Richard Smithcaf33902011-10-10 18:28:20 +00004935 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004936}
4937
Daniel Dunbar07d07852009-10-18 21:17:35 +00004938// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004939void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4940 bool ExpandPointedToStructures,
4941 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004942 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004943 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004944 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004945 bool StructField,
4946 bool EncodeBlockParameters,
4947 bool EncodeClassNames) const {
John McCall393a78d2012-12-20 02:45:14 +00004948 CanQualType CT = getCanonicalType(T);
4949 switch (CT->getTypeClass()) {
4950 case Type::Builtin:
4951 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00004952 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004953 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00004954 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
4955 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
4956 else
4957 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00004958 return;
Mike Stump11289f42009-09-09 15:08:12 +00004959
John McCall393a78d2012-12-20 02:45:14 +00004960 case Type::Complex: {
4961 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00004962 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004963 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004964 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004965 return;
4966 }
John McCall393a78d2012-12-20 02:45:14 +00004967
4968 case Type::Atomic: {
4969 const AtomicType *AT = T->castAs<AtomicType>();
4970 S += 'A';
4971 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
4972 false, false);
4973 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004974 }
John McCall393a78d2012-12-20 02:45:14 +00004975
4976 // encoding for pointer or reference types.
4977 case Type::Pointer:
4978 case Type::LValueReference:
4979 case Type::RValueReference: {
4980 QualType PointeeTy;
4981 if (isa<PointerType>(CT)) {
4982 const PointerType *PT = T->castAs<PointerType>();
4983 if (PT->isObjCSelType()) {
4984 S += ':';
4985 return;
4986 }
4987 PointeeTy = PT->getPointeeType();
4988 } else {
4989 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
4990 }
4991
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004992 bool isReadOnly = false;
4993 // For historical/compatibility reasons, the read-only qualifier of the
4994 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4995 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004996 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004997 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004998 if (OutermostType && T.isConstQualified()) {
4999 isReadOnly = true;
5000 S += 'r';
5001 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005002 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005003 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005004 while (P->getAs<PointerType>())
5005 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005006 if (P.isConstQualified()) {
5007 isReadOnly = true;
5008 S += 'r';
5009 }
5010 }
5011 if (isReadOnly) {
5012 // Another legacy compatibility encoding. Some ObjC qualifier and type
5013 // combinations need to be rearranged.
5014 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005015 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005016 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005017 }
Mike Stump11289f42009-09-09 15:08:12 +00005018
Anders Carlssond8499822007-10-29 05:01:08 +00005019 if (PointeeTy->isCharType()) {
5020 // char pointer types should be encoded as '*' unless it is a
5021 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005022 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005023 S += '*';
5024 return;
5025 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005026 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005027 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5028 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5029 S += '#';
5030 return;
5031 }
5032 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5033 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5034 S += '@';
5035 return;
5036 }
5037 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005038 }
Anders Carlssond8499822007-10-29 05:01:08 +00005039 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005040 getLegacyIntegralTypeEncoding(PointeeTy);
5041
Mike Stump11289f42009-09-09 15:08:12 +00005042 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005043 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005044 return;
5045 }
John McCall393a78d2012-12-20 02:45:14 +00005046
5047 case Type::ConstantArray:
5048 case Type::IncompleteArray:
5049 case Type::VariableArray: {
5050 const ArrayType *AT = cast<ArrayType>(CT);
5051
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005052 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005053 // Incomplete arrays are encoded as a pointer to the array element.
5054 S += '^';
5055
Mike Stump11289f42009-09-09 15:08:12 +00005056 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005057 false, ExpandStructures, FD);
5058 } else {
5059 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005060
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005061 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
5062 if (getTypeSize(CAT->getElementType()) == 0)
5063 S += '0';
5064 else
5065 S += llvm::utostr(CAT->getSize().getZExtValue());
5066 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005067 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005068 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5069 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005070 S += '0';
5071 }
Mike Stump11289f42009-09-09 15:08:12 +00005072
5073 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005074 false, ExpandStructures, FD);
5075 S += ']';
5076 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005077 return;
5078 }
Mike Stump11289f42009-09-09 15:08:12 +00005079
John McCall393a78d2012-12-20 02:45:14 +00005080 case Type::FunctionNoProto:
5081 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005082 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005083 return;
Mike Stump11289f42009-09-09 15:08:12 +00005084
John McCall393a78d2012-12-20 02:45:14 +00005085 case Type::Record: {
5086 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005087 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005088 // Anonymous structures print as '?'
5089 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5090 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005091 if (ClassTemplateSpecializationDecl *Spec
5092 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5093 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
5094 std::string TemplateArgsStr
5095 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005096 TemplateArgs.data(),
5097 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005098 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005099
5100 S += TemplateArgsStr;
5101 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005102 } else {
5103 S += '?';
5104 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005105 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005106 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005107 if (!RDecl->isUnion()) {
5108 getObjCEncodingForStructureImpl(RDecl, S, FD);
5109 } else {
5110 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5111 FieldEnd = RDecl->field_end();
5112 Field != FieldEnd; ++Field) {
5113 if (FD) {
5114 S += '"';
5115 S += Field->getNameAsString();
5116 S += '"';
5117 }
Mike Stump11289f42009-09-09 15:08:12 +00005118
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005119 // Special case bit-fields.
5120 if (Field->isBitField()) {
5121 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00005122 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005123 } else {
5124 QualType qt = Field->getType();
5125 getLegacyIntegralTypeEncoding(qt);
5126 getObjCEncodingForTypeImpl(qt, S, false, true,
5127 FD, /*OutermostType*/false,
5128 /*EncodingProperty*/false,
5129 /*StructField*/true);
5130 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005131 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005132 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005133 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005134 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005135 return;
5136 }
Mike Stump11289f42009-09-09 15:08:12 +00005137
John McCall393a78d2012-12-20 02:45:14 +00005138 case Type::BlockPointer: {
5139 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005140 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005141 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005142 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005143
5144 S += '<';
5145 // Block return type
5146 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5147 ExpandPointedToStructures, ExpandStructures,
5148 FD,
5149 false /* OutermostType */,
5150 EncodingProperty,
5151 false /* StructField */,
5152 EncodeBlockParameters,
5153 EncodeClassNames);
5154 // Block self
5155 S += "@?";
5156 // Block parameters
5157 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5158 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5159 E = FPT->arg_type_end(); I && (I != E); ++I) {
5160 getObjCEncodingForTypeImpl(*I, S,
5161 ExpandPointedToStructures,
5162 ExpandStructures,
5163 FD,
5164 false /* OutermostType */,
5165 EncodingProperty,
5166 false /* StructField */,
5167 EncodeBlockParameters,
5168 EncodeClassNames);
5169 }
5170 }
5171 S += '>';
5172 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005173 return;
5174 }
Mike Stump11289f42009-09-09 15:08:12 +00005175
John McCall393a78d2012-12-20 02:45:14 +00005176 case Type::ObjCObject:
5177 case Type::ObjCInterface: {
5178 // Ignore protocol qualifiers when mangling at this level.
5179 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCall8b07ec22010-05-15 11:32:37 +00005180
John McCall393a78d2012-12-20 02:45:14 +00005181 // The assumption seems to be that this assert will succeed
5182 // because nested levels will have filtered out 'id' and 'Class'.
5183 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005184 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005185 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005186 S += '{';
5187 const IdentifierInfo *II = OI->getIdentifier();
5188 S += II->getName();
5189 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005190 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005191 DeepCollectObjCIvars(OI, true, Ivars);
5192 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005193 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005194 if (Field->isBitField())
5195 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005196 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005197 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005198 }
5199 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005200 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005201 }
Mike Stump11289f42009-09-09 15:08:12 +00005202
John McCall393a78d2012-12-20 02:45:14 +00005203 case Type::ObjCObjectPointer: {
5204 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005205 if (OPT->isObjCIdType()) {
5206 S += '@';
5207 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005208 }
Mike Stump11289f42009-09-09 15:08:12 +00005209
Steve Narofff0c86112009-10-28 22:03:49 +00005210 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5211 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5212 // Since this is a binary compatibility issue, need to consult with runtime
5213 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005214 S += '#';
5215 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005216 }
Mike Stump11289f42009-09-09 15:08:12 +00005217
Chris Lattnere7cabb92009-07-13 00:10:46 +00005218 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005219 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005220 ExpandPointedToStructures,
5221 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005222 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005223 // Note that we do extended encoding of protocol qualifer list
5224 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005225 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00005226 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5227 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005228 S += '<';
5229 S += (*I)->getNameAsString();
5230 S += '>';
5231 }
5232 S += '"';
5233 }
5234 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005235 }
Mike Stump11289f42009-09-09 15:08:12 +00005236
Chris Lattnere7cabb92009-07-13 00:10:46 +00005237 QualType PointeeTy = OPT->getPointeeType();
5238 if (!EncodingProperty &&
5239 isa<TypedefType>(PointeeTy.getTypePtr())) {
5240 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005241 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005242 // {...};
5243 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00005244 getObjCEncodingForTypeImpl(PointeeTy, S,
5245 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00005246 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005247 return;
5248 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005249
5250 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005251 if (OPT->getInterfaceDecl() &&
5252 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005253 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005254 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00005255 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5256 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005257 S += '<';
5258 S += (*I)->getNameAsString();
5259 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005260 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005261 S += '"';
5262 }
5263 return;
5264 }
Mike Stump11289f42009-09-09 15:08:12 +00005265
John McCalla9e6e8d2010-05-17 23:56:34 +00005266 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005267 // FIXME: we shoul do better than that. 'M' is available.
5268 case Type::MemberPointer:
John McCalla9e6e8d2010-05-17 23:56:34 +00005269 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005270
John McCall393a78d2012-12-20 02:45:14 +00005271 case Type::Vector:
5272 case Type::ExtVector:
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005273 // This matches gcc's encoding, even though technically it is
5274 // insufficient.
5275 // FIXME. We should do a better job than gcc.
5276 return;
John McCall393a78d2012-12-20 02:45:14 +00005277
5278#define ABSTRACT_TYPE(KIND, BASE)
5279#define TYPE(KIND, BASE)
5280#define DEPENDENT_TYPE(KIND, BASE) \
5281 case Type::KIND:
5282#define NON_CANONICAL_TYPE(KIND, BASE) \
5283 case Type::KIND:
5284#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5285 case Type::KIND:
5286#include "clang/AST/TypeNodes.def"
5287 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005288 }
John McCall393a78d2012-12-20 02:45:14 +00005289 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005290}
5291
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005292void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5293 std::string &S,
5294 const FieldDecl *FD,
5295 bool includeVBases) const {
5296 assert(RDecl && "Expected non-null RecordDecl");
5297 assert(!RDecl->isUnion() && "Should not be called for unions");
5298 if (!RDecl->getDefinition())
5299 return;
5300
5301 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5302 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5303 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5304
5305 if (CXXRec) {
5306 for (CXXRecordDecl::base_class_iterator
5307 BI = CXXRec->bases_begin(),
5308 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5309 if (!BI->isVirtual()) {
5310 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005311 if (base->isEmpty())
5312 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005313 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005314 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5315 std::make_pair(offs, base));
5316 }
5317 }
5318 }
5319
5320 unsigned i = 0;
5321 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5322 FieldEnd = RDecl->field_end();
5323 Field != FieldEnd; ++Field, ++i) {
5324 uint64_t offs = layout.getFieldOffset(i);
5325 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00005326 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005327 }
5328
5329 if (CXXRec && includeVBases) {
5330 for (CXXRecordDecl::base_class_iterator
5331 BI = CXXRec->vbases_begin(),
5332 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5333 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005334 if (base->isEmpty())
5335 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005336 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005337 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5338 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5339 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005340 }
5341 }
5342
5343 CharUnits size;
5344 if (CXXRec) {
5345 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5346 } else {
5347 size = layout.getSize();
5348 }
5349
5350 uint64_t CurOffs = 0;
5351 std::multimap<uint64_t, NamedDecl *>::iterator
5352 CurLayObj = FieldOrBaseOffsets.begin();
5353
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005354 if (CXXRec && CXXRec->isDynamicClass() &&
5355 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005356 if (FD) {
5357 S += "\"_vptr$";
5358 std::string recname = CXXRec->getNameAsString();
5359 if (recname.empty()) recname = "?";
5360 S += recname;
5361 S += '"';
5362 }
5363 S += "^^?";
5364 CurOffs += getTypeSize(VoidPtrTy);
5365 }
5366
5367 if (!RDecl->hasFlexibleArrayMember()) {
5368 // Mark the end of the structure.
5369 uint64_t offs = toBits(size);
5370 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5371 std::make_pair(offs, (NamedDecl*)0));
5372 }
5373
5374 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5375 assert(CurOffs <= CurLayObj->first);
5376
5377 if (CurOffs < CurLayObj->first) {
5378 uint64_t padding = CurLayObj->first - CurOffs;
5379 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5380 // packing/alignment of members is different that normal, in which case
5381 // the encoding will be out-of-sync with the real layout.
5382 // If the runtime switches to just consider the size of types without
5383 // taking into account alignment, we could make padding explicit in the
5384 // encoding (e.g. using arrays of chars). The encoding strings would be
5385 // longer then though.
5386 CurOffs += padding;
5387 }
5388
5389 NamedDecl *dcl = CurLayObj->second;
5390 if (dcl == 0)
5391 break; // reached end of structure.
5392
5393 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5394 // We expand the bases without their virtual bases since those are going
5395 // in the initial structure. Note that this differs from gcc which
5396 // expands virtual bases each time one is encountered in the hierarchy,
5397 // making the encoding type bigger than it really is.
5398 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005399 assert(!base->isEmpty());
5400 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005401 } else {
5402 FieldDecl *field = cast<FieldDecl>(dcl);
5403 if (FD) {
5404 S += '"';
5405 S += field->getNameAsString();
5406 S += '"';
5407 }
5408
5409 if (field->isBitField()) {
5410 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00005411 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005412 } else {
5413 QualType qt = field->getType();
5414 getLegacyIntegralTypeEncoding(qt);
5415 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5416 /*OutermostType*/false,
5417 /*EncodingProperty*/false,
5418 /*StructField*/true);
5419 CurOffs += getTypeSize(field->getType());
5420 }
5421 }
5422 }
5423}
5424
Mike Stump11289f42009-09-09 15:08:12 +00005425void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005426 std::string& S) const {
5427 if (QT & Decl::OBJC_TQ_In)
5428 S += 'n';
5429 if (QT & Decl::OBJC_TQ_Inout)
5430 S += 'N';
5431 if (QT & Decl::OBJC_TQ_Out)
5432 S += 'o';
5433 if (QT & Decl::OBJC_TQ_Bycopy)
5434 S += 'O';
5435 if (QT & Decl::OBJC_TQ_Byref)
5436 S += 'R';
5437 if (QT & Decl::OBJC_TQ_Oneway)
5438 S += 'V';
5439}
5440
Douglas Gregor3ea72692011-08-12 05:46:01 +00005441TypedefDecl *ASTContext::getObjCIdDecl() const {
5442 if (!ObjCIdDecl) {
5443 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5444 T = getObjCObjectPointerType(T);
5445 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5446 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5447 getTranslationUnitDecl(),
5448 SourceLocation(), SourceLocation(),
5449 &Idents.get("id"), IdInfo);
5450 }
5451
5452 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005453}
5454
Douglas Gregor52e02802011-08-12 06:17:30 +00005455TypedefDecl *ASTContext::getObjCSelDecl() const {
5456 if (!ObjCSelDecl) {
5457 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5458 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5459 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5460 getTranslationUnitDecl(),
5461 SourceLocation(), SourceLocation(),
5462 &Idents.get("SEL"), SelInfo);
5463 }
5464 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005465}
5466
Douglas Gregor0a586182011-08-12 05:59:41 +00005467TypedefDecl *ASTContext::getObjCClassDecl() const {
5468 if (!ObjCClassDecl) {
5469 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5470 T = getObjCObjectPointerType(T);
5471 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5472 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5473 getTranslationUnitDecl(),
5474 SourceLocation(), SourceLocation(),
5475 &Idents.get("Class"), ClassInfo);
5476 }
5477
5478 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005479}
5480
Douglas Gregord53ae832012-01-17 18:09:05 +00005481ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5482 if (!ObjCProtocolClassDecl) {
5483 ObjCProtocolClassDecl
5484 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5485 SourceLocation(),
5486 &Idents.get("Protocol"),
5487 /*PrevDecl=*/0,
5488 SourceLocation(), true);
5489 }
5490
5491 return ObjCProtocolClassDecl;
5492}
5493
Meador Inge5d3fb222012-06-16 03:34:49 +00005494//===----------------------------------------------------------------------===//
5495// __builtin_va_list Construction Functions
5496//===----------------------------------------------------------------------===//
5497
5498static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5499 // typedef char* __builtin_va_list;
5500 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5501 TypeSourceInfo *TInfo
5502 = Context->getTrivialTypeSourceInfo(CharPtrType);
5503
5504 TypedefDecl *VaListTypeDecl
5505 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5506 Context->getTranslationUnitDecl(),
5507 SourceLocation(), SourceLocation(),
5508 &Context->Idents.get("__builtin_va_list"),
5509 TInfo);
5510 return VaListTypeDecl;
5511}
5512
5513static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5514 // typedef void* __builtin_va_list;
5515 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5516 TypeSourceInfo *TInfo
5517 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5518
5519 TypedefDecl *VaListTypeDecl
5520 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5521 Context->getTranslationUnitDecl(),
5522 SourceLocation(), SourceLocation(),
5523 &Context->Idents.get("__builtin_va_list"),
5524 TInfo);
5525 return VaListTypeDecl;
5526}
5527
5528static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5529 // typedef struct __va_list_tag {
5530 RecordDecl *VaListTagDecl;
5531
5532 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5533 Context->getTranslationUnitDecl(),
5534 &Context->Idents.get("__va_list_tag"));
5535 VaListTagDecl->startDefinition();
5536
5537 const size_t NumFields = 5;
5538 QualType FieldTypes[NumFields];
5539 const char *FieldNames[NumFields];
5540
5541 // unsigned char gpr;
5542 FieldTypes[0] = Context->UnsignedCharTy;
5543 FieldNames[0] = "gpr";
5544
5545 // unsigned char fpr;
5546 FieldTypes[1] = Context->UnsignedCharTy;
5547 FieldNames[1] = "fpr";
5548
5549 // unsigned short reserved;
5550 FieldTypes[2] = Context->UnsignedShortTy;
5551 FieldNames[2] = "reserved";
5552
5553 // void* overflow_arg_area;
5554 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5555 FieldNames[3] = "overflow_arg_area";
5556
5557 // void* reg_save_area;
5558 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5559 FieldNames[4] = "reg_save_area";
5560
5561 // Create fields
5562 for (unsigned i = 0; i < NumFields; ++i) {
5563 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5564 SourceLocation(),
5565 SourceLocation(),
5566 &Context->Idents.get(FieldNames[i]),
5567 FieldTypes[i], /*TInfo=*/0,
5568 /*BitWidth=*/0,
5569 /*Mutable=*/false,
5570 ICIS_NoInit);
5571 Field->setAccess(AS_public);
5572 VaListTagDecl->addDecl(Field);
5573 }
5574 VaListTagDecl->completeDefinition();
5575 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005576 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005577
5578 // } __va_list_tag;
5579 TypedefDecl *VaListTagTypedefDecl
5580 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5581 Context->getTranslationUnitDecl(),
5582 SourceLocation(), SourceLocation(),
5583 &Context->Idents.get("__va_list_tag"),
5584 Context->getTrivialTypeSourceInfo(VaListTagType));
5585 QualType VaListTagTypedefType =
5586 Context->getTypedefType(VaListTagTypedefDecl);
5587
5588 // typedef __va_list_tag __builtin_va_list[1];
5589 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5590 QualType VaListTagArrayType
5591 = Context->getConstantArrayType(VaListTagTypedefType,
5592 Size, ArrayType::Normal, 0);
5593 TypeSourceInfo *TInfo
5594 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5595 TypedefDecl *VaListTypedefDecl
5596 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5597 Context->getTranslationUnitDecl(),
5598 SourceLocation(), SourceLocation(),
5599 &Context->Idents.get("__builtin_va_list"),
5600 TInfo);
5601
5602 return VaListTypedefDecl;
5603}
5604
5605static TypedefDecl *
5606CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5607 // typedef struct __va_list_tag {
5608 RecordDecl *VaListTagDecl;
5609 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5610 Context->getTranslationUnitDecl(),
5611 &Context->Idents.get("__va_list_tag"));
5612 VaListTagDecl->startDefinition();
5613
5614 const size_t NumFields = 4;
5615 QualType FieldTypes[NumFields];
5616 const char *FieldNames[NumFields];
5617
5618 // unsigned gp_offset;
5619 FieldTypes[0] = Context->UnsignedIntTy;
5620 FieldNames[0] = "gp_offset";
5621
5622 // unsigned fp_offset;
5623 FieldTypes[1] = Context->UnsignedIntTy;
5624 FieldNames[1] = "fp_offset";
5625
5626 // void* overflow_arg_area;
5627 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5628 FieldNames[2] = "overflow_arg_area";
5629
5630 // void* reg_save_area;
5631 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5632 FieldNames[3] = "reg_save_area";
5633
5634 // Create fields
5635 for (unsigned i = 0; i < NumFields; ++i) {
5636 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5637 VaListTagDecl,
5638 SourceLocation(),
5639 SourceLocation(),
5640 &Context->Idents.get(FieldNames[i]),
5641 FieldTypes[i], /*TInfo=*/0,
5642 /*BitWidth=*/0,
5643 /*Mutable=*/false,
5644 ICIS_NoInit);
5645 Field->setAccess(AS_public);
5646 VaListTagDecl->addDecl(Field);
5647 }
5648 VaListTagDecl->completeDefinition();
5649 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005650 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005651
5652 // } __va_list_tag;
5653 TypedefDecl *VaListTagTypedefDecl
5654 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5655 Context->getTranslationUnitDecl(),
5656 SourceLocation(), SourceLocation(),
5657 &Context->Idents.get("__va_list_tag"),
5658 Context->getTrivialTypeSourceInfo(VaListTagType));
5659 QualType VaListTagTypedefType =
5660 Context->getTypedefType(VaListTagTypedefDecl);
5661
5662 // typedef __va_list_tag __builtin_va_list[1];
5663 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5664 QualType VaListTagArrayType
5665 = Context->getConstantArrayType(VaListTagTypedefType,
5666 Size, ArrayType::Normal,0);
5667 TypeSourceInfo *TInfo
5668 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5669 TypedefDecl *VaListTypedefDecl
5670 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5671 Context->getTranslationUnitDecl(),
5672 SourceLocation(), SourceLocation(),
5673 &Context->Idents.get("__builtin_va_list"),
5674 TInfo);
5675
5676 return VaListTypedefDecl;
5677}
5678
5679static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5680 // typedef int __builtin_va_list[4];
5681 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5682 QualType IntArrayType
5683 = Context->getConstantArrayType(Context->IntTy,
5684 Size, ArrayType::Normal, 0);
5685 TypedefDecl *VaListTypedefDecl
5686 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5687 Context->getTranslationUnitDecl(),
5688 SourceLocation(), SourceLocation(),
5689 &Context->Idents.get("__builtin_va_list"),
5690 Context->getTrivialTypeSourceInfo(IntArrayType));
5691
5692 return VaListTypedefDecl;
5693}
5694
Logan Chien57086ce2012-10-10 06:56:20 +00005695static TypedefDecl *
5696CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
5697 RecordDecl *VaListDecl;
5698 if (Context->getLangOpts().CPlusPlus) {
5699 // namespace std { struct __va_list {
5700 NamespaceDecl *NS;
5701 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5702 Context->getTranslationUnitDecl(),
5703 /*Inline*/false, SourceLocation(),
5704 SourceLocation(), &Context->Idents.get("std"),
5705 /*PrevDecl*/0);
5706
5707 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5708 Context->getTranslationUnitDecl(),
5709 SourceLocation(), SourceLocation(),
5710 &Context->Idents.get("__va_list"));
5711
5712 VaListDecl->setDeclContext(NS);
5713
5714 } else {
5715 // struct __va_list {
5716 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
5717 Context->getTranslationUnitDecl(),
5718 &Context->Idents.get("__va_list"));
5719 }
5720
5721 VaListDecl->startDefinition();
5722
5723 // void * __ap;
5724 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5725 VaListDecl,
5726 SourceLocation(),
5727 SourceLocation(),
5728 &Context->Idents.get("__ap"),
5729 Context->getPointerType(Context->VoidTy),
5730 /*TInfo=*/0,
5731 /*BitWidth=*/0,
5732 /*Mutable=*/false,
5733 ICIS_NoInit);
5734 Field->setAccess(AS_public);
5735 VaListDecl->addDecl(Field);
5736
5737 // };
5738 VaListDecl->completeDefinition();
5739
5740 // typedef struct __va_list __builtin_va_list;
5741 TypeSourceInfo *TInfo
5742 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
5743
5744 TypedefDecl *VaListTypeDecl
5745 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5746 Context->getTranslationUnitDecl(),
5747 SourceLocation(), SourceLocation(),
5748 &Context->Idents.get("__builtin_va_list"),
5749 TInfo);
5750
5751 return VaListTypeDecl;
5752}
5753
Meador Inge5d3fb222012-06-16 03:34:49 +00005754static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5755 TargetInfo::BuiltinVaListKind Kind) {
5756 switch (Kind) {
5757 case TargetInfo::CharPtrBuiltinVaList:
5758 return CreateCharPtrBuiltinVaListDecl(Context);
5759 case TargetInfo::VoidPtrBuiltinVaList:
5760 return CreateVoidPtrBuiltinVaListDecl(Context);
5761 case TargetInfo::PowerABIBuiltinVaList:
5762 return CreatePowerABIBuiltinVaListDecl(Context);
5763 case TargetInfo::X86_64ABIBuiltinVaList:
5764 return CreateX86_64ABIBuiltinVaListDecl(Context);
5765 case TargetInfo::PNaClABIBuiltinVaList:
5766 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00005767 case TargetInfo::AAPCSABIBuiltinVaList:
5768 return CreateAAPCSABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00005769 }
5770
5771 llvm_unreachable("Unhandled __builtin_va_list type kind");
5772}
5773
5774TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5775 if (!BuiltinVaListDecl)
5776 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5777
5778 return BuiltinVaListDecl;
5779}
5780
Meador Ingecfb60902012-07-01 15:57:25 +00005781QualType ASTContext::getVaListTagType() const {
5782 // Force the creation of VaListTagTy by building the __builtin_va_list
5783 // declaration.
5784 if (VaListTagTy.isNull())
5785 (void) getBuiltinVaListDecl();
5786
5787 return VaListTagTy;
5788}
5789
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005790void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00005791 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00005792 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00005793
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005794 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00005795}
5796
John McCalld28ae272009-12-02 08:04:21 +00005797/// \brief Retrieve the template name that corresponds to a non-empty
5798/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00005799TemplateName
5800ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5801 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00005802 unsigned size = End - Begin;
5803 assert(size > 1 && "set is not overloaded!");
5804
5805 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5806 size * sizeof(FunctionTemplateDecl*));
5807 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5808
5809 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00005810 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00005811 NamedDecl *D = *I;
5812 assert(isa<FunctionTemplateDecl>(D) ||
5813 (isa<UsingShadowDecl>(D) &&
5814 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5815 *Storage++ = D;
5816 }
5817
5818 return TemplateName(OT);
5819}
5820
Douglas Gregordc572a32009-03-30 22:58:21 +00005821/// \brief Retrieve the template name that represents a qualified
5822/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00005823TemplateName
5824ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5825 bool TemplateKeyword,
5826 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00005827 assert(NNS && "Missing nested-name-specifier in qualified template name");
5828
Douglas Gregorc42075a2010-02-04 18:10:26 +00005829 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00005830 llvm::FoldingSetNodeID ID;
5831 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5832
5833 void *InsertPos = 0;
5834 QualifiedTemplateName *QTN =
5835 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5836 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00005837 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
5838 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00005839 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5840 }
5841
5842 return TemplateName(QTN);
5843}
5844
5845/// \brief Retrieve the template name that represents a dependent
5846/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00005847TemplateName
5848ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5849 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00005850 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00005851 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00005852
5853 llvm::FoldingSetNodeID ID;
5854 DependentTemplateName::Profile(ID, NNS, Name);
5855
5856 void *InsertPos = 0;
5857 DependentTemplateName *QTN =
5858 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5859
5860 if (QTN)
5861 return TemplateName(QTN);
5862
5863 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5864 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00005865 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5866 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00005867 } else {
5868 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00005869 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5870 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005871 DependentTemplateName *CheckQTN =
5872 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5873 assert(!CheckQTN && "Dependent type name canonicalization broken");
5874 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00005875 }
5876
5877 DependentTemplateNames.InsertNode(QTN, InsertPos);
5878 return TemplateName(QTN);
5879}
5880
Douglas Gregor71395fa2009-11-04 00:56:37 +00005881/// \brief Retrieve the template name that represents a dependent
5882/// template name such as \c MetaFun::template operator+.
5883TemplateName
5884ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00005885 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00005886 assert((!NNS || NNS->isDependent()) &&
5887 "Nested name specifier must be dependent");
5888
5889 llvm::FoldingSetNodeID ID;
5890 DependentTemplateName::Profile(ID, NNS, Operator);
5891
5892 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00005893 DependentTemplateName *QTN
5894 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005895
5896 if (QTN)
5897 return TemplateName(QTN);
5898
5899 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5900 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00005901 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5902 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005903 } else {
5904 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00005905 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5906 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005907
5908 DependentTemplateName *CheckQTN
5909 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5910 assert(!CheckQTN && "Dependent template name canonicalization broken");
5911 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00005912 }
5913
5914 DependentTemplateNames.InsertNode(QTN, InsertPos);
5915 return TemplateName(QTN);
5916}
5917
Douglas Gregor5590be02011-01-15 06:45:20 +00005918TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00005919ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5920 TemplateName replacement) const {
5921 llvm::FoldingSetNodeID ID;
5922 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5923
5924 void *insertPos = 0;
5925 SubstTemplateTemplateParmStorage *subst
5926 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5927
5928 if (!subst) {
5929 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5930 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5931 }
5932
5933 return TemplateName(subst);
5934}
5935
5936TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00005937ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5938 const TemplateArgument &ArgPack) const {
5939 ASTContext &Self = const_cast<ASTContext &>(*this);
5940 llvm::FoldingSetNodeID ID;
5941 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5942
5943 void *InsertPos = 0;
5944 SubstTemplateTemplateParmPackStorage *Subst
5945 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5946
5947 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00005948 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00005949 ArgPack.pack_size(),
5950 ArgPack.pack_begin());
5951 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5952 }
5953
5954 return TemplateName(Subst);
5955}
5956
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005957/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00005958/// TargetInfo, produce the corresponding type. The unsigned @p Type
5959/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00005960CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005961 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00005962 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005963 case TargetInfo::SignedShort: return ShortTy;
5964 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5965 case TargetInfo::SignedInt: return IntTy;
5966 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5967 case TargetInfo::SignedLong: return LongTy;
5968 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5969 case TargetInfo::SignedLongLong: return LongLongTy;
5970 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5971 }
5972
David Blaikie83d382b2011-09-23 05:06:16 +00005973 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005974}
Ted Kremenek77c51b22008-07-24 23:58:27 +00005975
5976//===----------------------------------------------------------------------===//
5977// Type Predicates.
5978//===----------------------------------------------------------------------===//
5979
Fariborz Jahanian96207692009-02-18 21:49:28 +00005980/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5981/// garbage collection attribute.
5982///
John McCall553d45a2011-01-12 00:34:59 +00005983Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005984 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00005985 return Qualifiers::GCNone;
5986
David Blaikiebbafb8a2012-03-11 07:00:24 +00005987 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00005988 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5989
5990 // Default behaviour under objective-C's gc is for ObjC pointers
5991 // (or pointers to them) be treated as though they were declared
5992 // as __strong.
5993 if (GCAttrs == Qualifiers::GCNone) {
5994 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5995 return Qualifiers::Strong;
5996 else if (Ty->isPointerType())
5997 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5998 } else {
5999 // It's not valid to set GC attributes on anything that isn't a
6000 // pointer.
6001#ifndef NDEBUG
6002 QualType CT = Ty->getCanonicalTypeInternal();
6003 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6004 CT = AT->getElementType();
6005 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6006#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006007 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006008 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006009}
6010
Chris Lattner49af6a42008-04-07 06:51:04 +00006011//===----------------------------------------------------------------------===//
6012// Type Compatibility Testing
6013//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006014
Mike Stump11289f42009-09-09 15:08:12 +00006015/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006016/// compatible.
6017static bool areCompatVectorTypes(const VectorType *LHS,
6018 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006019 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006020 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006021 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006022}
6023
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006024bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6025 QualType SecondVec) {
6026 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6027 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6028
6029 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6030 return true;
6031
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006032 // Treat Neon vector types and most AltiVec vector types as if they are the
6033 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006034 const VectorType *First = FirstVec->getAs<VectorType>();
6035 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006036 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006037 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006038 First->getVectorKind() != VectorType::AltiVecPixel &&
6039 First->getVectorKind() != VectorType::AltiVecBool &&
6040 Second->getVectorKind() != VectorType::AltiVecPixel &&
6041 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006042 return true;
6043
6044 return false;
6045}
6046
Steve Naroff8e6aee52009-07-23 01:01:38 +00006047//===----------------------------------------------------------------------===//
6048// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6049//===----------------------------------------------------------------------===//
6050
6051/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6052/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006053bool
6054ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6055 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006056 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006057 return true;
6058 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6059 E = rProto->protocol_end(); PI != E; ++PI)
6060 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6061 return true;
6062 return false;
6063}
6064
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006065/// QualifiedIdConformsQualifiedId - compare id<pr,...> with id<pr1,...>
Steve Naroff8e6aee52009-07-23 01:01:38 +00006066/// return true if lhs's protocols conform to rhs's protocol; false
6067/// otherwise.
6068bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
6069 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
6070 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
6071 return false;
6072}
6073
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006074/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6075/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006076bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6077 QualType rhs) {
6078 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6079 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6080 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6081
6082 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6083 E = lhsQID->qual_end(); I != E; ++I) {
6084 bool match = false;
6085 ObjCProtocolDecl *lhsProto = *I;
6086 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6087 E = rhsOPT->qual_end(); J != E; ++J) {
6088 ObjCProtocolDecl *rhsProto = *J;
6089 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6090 match = true;
6091 break;
6092 }
6093 }
6094 if (!match)
6095 return false;
6096 }
6097 return true;
6098}
6099
Steve Naroff8e6aee52009-07-23 01:01:38 +00006100/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6101/// ObjCQualifiedIDType.
6102bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6103 bool compare) {
6104 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006105 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006106 lhs->isObjCIdType() || lhs->isObjCClassType())
6107 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006108 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006109 rhs->isObjCIdType() || rhs->isObjCClassType())
6110 return true;
6111
6112 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006113 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006114
Steve Naroff8e6aee52009-07-23 01:01:38 +00006115 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006116
Steve Naroff8e6aee52009-07-23 01:01:38 +00006117 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006118 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006119 // make sure we check the class hierarchy.
6120 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6121 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6122 E = lhsQID->qual_end(); I != E; ++I) {
6123 // when comparing an id<P> on lhs with a static type on rhs,
6124 // see if static class implements all of id's protocols, directly or
6125 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006126 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006127 return false;
6128 }
6129 }
6130 // If there are no qualifiers and no interface, we have an 'id'.
6131 return true;
6132 }
Mike Stump11289f42009-09-09 15:08:12 +00006133 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006134 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6135 E = lhsQID->qual_end(); I != E; ++I) {
6136 ObjCProtocolDecl *lhsProto = *I;
6137 bool match = false;
6138
6139 // when comparing an id<P> on lhs with a static type on rhs,
6140 // see if static class implements all of id's protocols, directly or
6141 // through its super class and categories.
6142 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6143 E = rhsOPT->qual_end(); J != E; ++J) {
6144 ObjCProtocolDecl *rhsProto = *J;
6145 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6146 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6147 match = true;
6148 break;
6149 }
6150 }
Mike Stump11289f42009-09-09 15:08:12 +00006151 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006152 // make sure we check the class hierarchy.
6153 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6154 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6155 E = lhsQID->qual_end(); I != E; ++I) {
6156 // when comparing an id<P> on lhs with a static type on rhs,
6157 // see if static class implements all of id's protocols, directly or
6158 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006159 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006160 match = true;
6161 break;
6162 }
6163 }
6164 }
6165 if (!match)
6166 return false;
6167 }
Mike Stump11289f42009-09-09 15:08:12 +00006168
Steve Naroff8e6aee52009-07-23 01:01:38 +00006169 return true;
6170 }
Mike Stump11289f42009-09-09 15:08:12 +00006171
Steve Naroff8e6aee52009-07-23 01:01:38 +00006172 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6173 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6174
Mike Stump11289f42009-09-09 15:08:12 +00006175 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006176 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006177 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006178 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6179 E = lhsOPT->qual_end(); I != E; ++I) {
6180 ObjCProtocolDecl *lhsProto = *I;
6181 bool match = false;
6182
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006183 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006184 // see if static class implements all of id's protocols, directly or
6185 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006186 // First, lhs protocols in the qualifier list must be found, direct
6187 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006188 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6189 E = rhsQID->qual_end(); J != E; ++J) {
6190 ObjCProtocolDecl *rhsProto = *J;
6191 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6192 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6193 match = true;
6194 break;
6195 }
6196 }
6197 if (!match)
6198 return false;
6199 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006200
6201 // Static class's protocols, or its super class or category protocols
6202 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6203 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6204 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6205 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6206 // This is rather dubious but matches gcc's behavior. If lhs has
6207 // no type qualifier and its class has no static protocol(s)
6208 // assume that it is mismatch.
6209 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6210 return false;
6211 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6212 LHSInheritedProtocols.begin(),
6213 E = LHSInheritedProtocols.end(); I != E; ++I) {
6214 bool match = false;
6215 ObjCProtocolDecl *lhsProto = (*I);
6216 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6217 E = rhsQID->qual_end(); J != E; ++J) {
6218 ObjCProtocolDecl *rhsProto = *J;
6219 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6220 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6221 match = true;
6222 break;
6223 }
6224 }
6225 if (!match)
6226 return false;
6227 }
6228 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006229 return true;
6230 }
6231 return false;
6232}
6233
Eli Friedman47f77112008-08-22 00:56:42 +00006234/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006235/// compatible for assignment from RHS to LHS. This handles validation of any
6236/// protocol qualifiers on the LHS or RHS.
6237///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006238bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6239 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006240 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6241 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6242
Steve Naroff1329fa02009-07-15 18:40:39 +00006243 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006244 if (LHS->isObjCUnqualifiedIdOrClass() ||
6245 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006246 return true;
6247
John McCall8b07ec22010-05-15 11:32:37 +00006248 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006249 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6250 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006251 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006252
6253 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6254 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6255 QualType(RHSOPT,0));
6256
John McCall8b07ec22010-05-15 11:32:37 +00006257 // If we have 2 user-defined types, fall into that path.
6258 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006259 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006260
Steve Naroff8e6aee52009-07-23 01:01:38 +00006261 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006262}
6263
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006264/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006265/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006266/// arguments in block literals. When passed as arguments, passing 'A*' where
6267/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6268/// not OK. For the return type, the opposite is not OK.
6269bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6270 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006271 const ObjCObjectPointerType *RHSOPT,
6272 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006273 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006274 return true;
6275
6276 if (LHSOPT->isObjCBuiltinType()) {
6277 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6278 }
6279
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006280 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006281 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6282 QualType(RHSOPT,0),
6283 false);
6284
6285 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6286 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6287 if (LHS && RHS) { // We have 2 user-defined types.
6288 if (LHS != RHS) {
6289 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006290 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006291 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006292 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006293 }
6294 else
6295 return true;
6296 }
6297 return false;
6298}
6299
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006300/// getIntersectionOfProtocols - This routine finds the intersection of set
6301/// of protocols inherited from two distinct objective-c pointer objects.
6302/// It is used to build composite qualifier list of the composite type of
6303/// the conditional expression involving two objective-c pointer objects.
6304static
6305void getIntersectionOfProtocols(ASTContext &Context,
6306 const ObjCObjectPointerType *LHSOPT,
6307 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006308 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006309
John McCall8b07ec22010-05-15 11:32:37 +00006310 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6311 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6312 assert(LHS->getInterface() && "LHS must have an interface base");
6313 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006314
6315 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6316 unsigned LHSNumProtocols = LHS->getNumProtocols();
6317 if (LHSNumProtocols > 0)
6318 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6319 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006320 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006321 Context.CollectInheritedProtocols(LHS->getInterface(),
6322 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006323 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6324 LHSInheritedProtocols.end());
6325 }
6326
6327 unsigned RHSNumProtocols = RHS->getNumProtocols();
6328 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006329 ObjCProtocolDecl **RHSProtocols =
6330 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006331 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6332 if (InheritedProtocolSet.count(RHSProtocols[i]))
6333 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006334 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006335 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006336 Context.CollectInheritedProtocols(RHS->getInterface(),
6337 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006338 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6339 RHSInheritedProtocols.begin(),
6340 E = RHSInheritedProtocols.end(); I != E; ++I)
6341 if (InheritedProtocolSet.count((*I)))
6342 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006343 }
6344}
6345
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006346/// areCommonBaseCompatible - Returns common base class of the two classes if
6347/// one found. Note that this is O'2 algorithm. But it will be called as the
6348/// last type comparison in a ?-exp of ObjC pointer types before a
6349/// warning is issued. So, its invokation is extremely rare.
6350QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006351 const ObjCObjectPointerType *Lptr,
6352 const ObjCObjectPointerType *Rptr) {
6353 const ObjCObjectType *LHS = Lptr->getObjectType();
6354 const ObjCObjectType *RHS = Rptr->getObjectType();
6355 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6356 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006357 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006358 return QualType();
6359
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006360 do {
John McCall8b07ec22010-05-15 11:32:37 +00006361 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006362 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006363 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006364 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6365
6366 QualType Result = QualType(LHS, 0);
6367 if (!Protocols.empty())
6368 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6369 Result = getObjCObjectPointerType(Result);
6370 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006371 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006372 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006373
6374 return QualType();
6375}
6376
John McCall8b07ec22010-05-15 11:32:37 +00006377bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6378 const ObjCObjectType *RHS) {
6379 assert(LHS->getInterface() && "LHS is not an interface type");
6380 assert(RHS->getInterface() && "RHS is not an interface type");
6381
Chris Lattner49af6a42008-04-07 06:51:04 +00006382 // Verify that the base decls are compatible: the RHS must be a subclass of
6383 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006384 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006385 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006386
Chris Lattner49af6a42008-04-07 06:51:04 +00006387 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6388 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006389 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006390 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006391
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006392 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6393 // more detailed analysis is required.
6394 if (RHS->getNumProtocols() == 0) {
6395 // OK, if LHS is a superclass of RHS *and*
6396 // this superclass is assignment compatible with LHS.
6397 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006398 bool IsSuperClass =
6399 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6400 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006401 // OK if conversion of LHS to SuperClass results in narrowing of types
6402 // ; i.e., SuperClass may implement at least one of the protocols
6403 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6404 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6405 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006406 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006407 // If super class has no protocols, it is not a match.
6408 if (SuperClassInheritedProtocols.empty())
6409 return false;
6410
6411 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6412 LHSPE = LHS->qual_end();
6413 LHSPI != LHSPE; LHSPI++) {
6414 bool SuperImplementsProtocol = false;
6415 ObjCProtocolDecl *LHSProto = (*LHSPI);
6416
6417 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6418 SuperClassInheritedProtocols.begin(),
6419 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6420 ObjCProtocolDecl *SuperClassProto = (*I);
6421 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6422 SuperImplementsProtocol = true;
6423 break;
6424 }
6425 }
6426 if (!SuperImplementsProtocol)
6427 return false;
6428 }
6429 return true;
6430 }
6431 return false;
6432 }
Mike Stump11289f42009-09-09 15:08:12 +00006433
John McCall8b07ec22010-05-15 11:32:37 +00006434 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6435 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00006436 LHSPI != LHSPE; LHSPI++) {
6437 bool RHSImplementsProtocol = false;
6438
6439 // If the RHS doesn't implement the protocol on the left, the types
6440 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00006441 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6442 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00006443 RHSPI != RHSPE; RHSPI++) {
6444 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006445 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00006446 break;
6447 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006448 }
6449 // FIXME: For better diagnostics, consider passing back the protocol name.
6450 if (!RHSImplementsProtocol)
6451 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006452 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006453 // The RHS implements all protocols listed on the LHS.
6454 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006455}
6456
Steve Naroffb7605152009-02-12 17:52:19 +00006457bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6458 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006459 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6460 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006461
Steve Naroff7cae42b2009-07-10 23:34:53 +00006462 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006463 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006464
6465 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6466 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006467}
6468
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006469bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6470 return canAssignObjCInterfaces(
6471 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6472 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6473}
6474
Mike Stump11289f42009-09-09 15:08:12 +00006475/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006476/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006477/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006478/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006479bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6480 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006481 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006482 return hasSameType(LHS, RHS);
6483
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006484 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006485}
6486
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006487bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006488 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006489}
6490
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006491bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6492 return !mergeTypes(LHS, RHS, true).isNull();
6493}
6494
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006495/// mergeTransparentUnionType - if T is a transparent union type and a member
6496/// of T is compatible with SubType, return the merged type, else return
6497/// QualType()
6498QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6499 bool OfBlockPointer,
6500 bool Unqualified) {
6501 if (const RecordType *UT = T->getAsUnionType()) {
6502 RecordDecl *UD = UT->getDecl();
6503 if (UD->hasAttr<TransparentUnionAttr>()) {
6504 for (RecordDecl::field_iterator it = UD->field_begin(),
6505 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00006506 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006507 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6508 if (!MT.isNull())
6509 return MT;
6510 }
6511 }
6512 }
6513
6514 return QualType();
6515}
6516
6517/// mergeFunctionArgumentTypes - merge two types which appear as function
6518/// argument types
6519QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6520 bool OfBlockPointer,
6521 bool Unqualified) {
6522 // GNU extension: two types are compatible if they appear as a function
6523 // argument, one of the types is a transparent union type and the other
6524 // type is compatible with a union member
6525 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6526 Unqualified);
6527 if (!lmerge.isNull())
6528 return lmerge;
6529
6530 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6531 Unqualified);
6532 if (!rmerge.isNull())
6533 return rmerge;
6534
6535 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6536}
6537
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006538QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006539 bool OfBlockPointer,
6540 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006541 const FunctionType *lbase = lhs->getAs<FunctionType>();
6542 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006543 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6544 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006545 bool allLTypes = true;
6546 bool allRTypes = true;
6547
6548 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006549 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006550 if (OfBlockPointer) {
6551 QualType RHS = rbase->getResultType();
6552 QualType LHS = lbase->getResultType();
6553 bool UnqualifiedResult = Unqualified;
6554 if (!UnqualifiedResult)
6555 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006556 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006557 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006558 else
John McCall8c6b56f2010-12-15 01:06:38 +00006559 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6560 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006561 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006562
6563 if (Unqualified)
6564 retType = retType.getUnqualifiedType();
6565
6566 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6567 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6568 if (Unqualified) {
6569 LRetType = LRetType.getUnqualifiedType();
6570 RRetType = RRetType.getUnqualifiedType();
6571 }
6572
6573 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006574 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006575 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006576 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006577
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006578 // FIXME: double check this
6579 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6580 // rbase->getRegParmAttr() != 0 &&
6581 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006582 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6583 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006584
Douglas Gregor8c940862010-01-18 17:14:39 +00006585 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00006586 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00006587 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006588
John McCall8c6b56f2010-12-15 01:06:38 +00006589 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006590 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6591 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006592 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6593 return QualType();
6594
John McCall31168b02011-06-15 23:02:42 +00006595 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6596 return QualType();
6597
John McCall8c6b56f2010-12-15 01:06:38 +00006598 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6599 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006600
Rafael Espindola8778c282012-11-29 16:09:03 +00006601 if (lbaseInfo.getNoReturn() != NoReturn)
6602 allLTypes = false;
6603 if (rbaseInfo.getNoReturn() != NoReturn)
6604 allRTypes = false;
6605
John McCall31168b02011-06-15 23:02:42 +00006606 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006607
Eli Friedman47f77112008-08-22 00:56:42 +00006608 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006609 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6610 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006611 unsigned lproto_nargs = lproto->getNumArgs();
6612 unsigned rproto_nargs = rproto->getNumArgs();
6613
6614 // Compatible functions must have the same number of arguments
6615 if (lproto_nargs != rproto_nargs)
6616 return QualType();
6617
6618 // Variadic and non-variadic functions aren't compatible
6619 if (lproto->isVariadic() != rproto->isVariadic())
6620 return QualType();
6621
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006622 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6623 return QualType();
6624
Fariborz Jahanian97676972011-09-28 21:52:05 +00006625 if (LangOpts.ObjCAutoRefCount &&
6626 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6627 return QualType();
6628
Eli Friedman47f77112008-08-22 00:56:42 +00006629 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006630 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00006631 for (unsigned i = 0; i < lproto_nargs; i++) {
6632 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6633 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006634 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6635 OfBlockPointer,
6636 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006637 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006638
6639 if (Unqualified)
6640 argtype = argtype.getUnqualifiedType();
6641
Eli Friedman47f77112008-08-22 00:56:42 +00006642 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006643 if (Unqualified) {
6644 largtype = largtype.getUnqualifiedType();
6645 rargtype = rargtype.getUnqualifiedType();
6646 }
6647
Chris Lattner465fa322008-10-05 17:34:18 +00006648 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6649 allLTypes = false;
6650 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6651 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006652 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006653
Eli Friedman47f77112008-08-22 00:56:42 +00006654 if (allLTypes) return lhs;
6655 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006656
6657 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6658 EPI.ExtInfo = einfo;
6659 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006660 }
6661
6662 if (lproto) allRTypes = false;
6663 if (rproto) allLTypes = false;
6664
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006665 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006666 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006667 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006668 if (proto->isVariadic()) return QualType();
6669 // Check that the types are compatible with the types that
6670 // would result from default argument promotions (C99 6.7.5.3p15).
6671 // The only types actually affected are promotable integer
6672 // types and floats, which would be passed as a different
6673 // type depending on whether the prototype is visible.
6674 unsigned proto_nargs = proto->getNumArgs();
6675 for (unsigned i = 0; i < proto_nargs; ++i) {
6676 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00006677
Eli Friedman448ce402012-08-30 00:44:15 +00006678 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00006679 // to pass enum values.
Eli Friedman448ce402012-08-30 00:44:15 +00006680 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
6681 argTy = Enum->getDecl()->getIntegerType();
6682 if (argTy.isNull())
6683 return QualType();
6684 }
Douglas Gregor2973d402010-02-03 19:27:29 +00006685
Eli Friedman47f77112008-08-22 00:56:42 +00006686 if (argTy->isPromotableIntegerType() ||
6687 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6688 return QualType();
6689 }
6690
6691 if (allLTypes) return lhs;
6692 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006693
6694 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6695 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00006696 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006697 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006698 }
6699
6700 if (allLTypes) return lhs;
6701 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00006702 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00006703}
6704
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006705QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006706 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006707 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00006708 // C++ [expr]: If an expression initially has the type "reference to T", the
6709 // type is adjusted to "T" prior to any further analysis, the expression
6710 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006711 // expression is an lvalue unless the reference is an rvalue reference and
6712 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00006713 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6714 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006715
6716 if (Unqualified) {
6717 LHS = LHS.getUnqualifiedType();
6718 RHS = RHS.getUnqualifiedType();
6719 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00006720
Eli Friedman47f77112008-08-22 00:56:42 +00006721 QualType LHSCan = getCanonicalType(LHS),
6722 RHSCan = getCanonicalType(RHS);
6723
6724 // If two types are identical, they are compatible.
6725 if (LHSCan == RHSCan)
6726 return LHS;
6727
John McCall8ccfcb52009-09-24 19:53:00 +00006728 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006729 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6730 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00006731 if (LQuals != RQuals) {
6732 // If any of these qualifiers are different, we have a type
6733 // mismatch.
6734 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00006735 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6736 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00006737 return QualType();
6738
6739 // Exactly one GC qualifier difference is allowed: __strong is
6740 // okay if the other type has no GC qualifier but is an Objective
6741 // C object pointer (i.e. implicitly strong by default). We fix
6742 // this by pretending that the unqualified type was actually
6743 // qualified __strong.
6744 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6745 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6746 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6747
6748 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6749 return QualType();
6750
6751 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6752 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6753 }
6754 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6755 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6756 }
Eli Friedman47f77112008-08-22 00:56:42 +00006757 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00006758 }
6759
6760 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00006761
Eli Friedmandcca6332009-06-01 01:22:52 +00006762 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6763 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00006764
Chris Lattnerfd652912008-01-14 05:45:46 +00006765 // We want to consider the two function types to be the same for these
6766 // comparisons, just force one to the other.
6767 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6768 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00006769
6770 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00006771 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6772 LHSClass = Type::ConstantArray;
6773 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6774 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00006775
John McCall8b07ec22010-05-15 11:32:37 +00006776 // ObjCInterfaces are just specialized ObjCObjects.
6777 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6778 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6779
Nate Begemance4d7fc2008-04-18 23:10:10 +00006780 // Canonicalize ExtVector -> Vector.
6781 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6782 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00006783
Chris Lattner95554662008-04-07 05:43:21 +00006784 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006785 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00006786 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00006787 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00006788 // Compatibility is based on the underlying type, not the promotion
6789 // type.
John McCall9dd450b2009-09-21 23:43:11 +00006790 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006791 QualType TINT = ETy->getDecl()->getIntegerType();
6792 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006793 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006794 }
John McCall9dd450b2009-09-21 23:43:11 +00006795 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006796 QualType TINT = ETy->getDecl()->getIntegerType();
6797 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006798 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006799 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006800 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00006801 if (OfBlockPointer && !BlockReturnType) {
6802 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6803 return LHS;
6804 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6805 return RHS;
6806 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006807
Eli Friedman47f77112008-08-22 00:56:42 +00006808 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00006809 }
Eli Friedman47f77112008-08-22 00:56:42 +00006810
Steve Naroffc6edcbd2008-01-09 22:43:08 +00006811 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006812 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006813#define TYPE(Class, Base)
6814#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00006815#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006816#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6817#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6818#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00006819 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006820
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006821 case Type::LValueReference:
6822 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006823 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00006824 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006825
John McCall8b07ec22010-05-15 11:32:37 +00006826 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006827 case Type::IncompleteArray:
6828 case Type::VariableArray:
6829 case Type::FunctionProto:
6830 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00006831 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006832
Chris Lattnerfd652912008-01-14 05:45:46 +00006833 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00006834 {
6835 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006836 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6837 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006838 if (Unqualified) {
6839 LHSPointee = LHSPointee.getUnqualifiedType();
6840 RHSPointee = RHSPointee.getUnqualifiedType();
6841 }
6842 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6843 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006844 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00006845 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006846 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00006847 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006848 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006849 return getPointerType(ResultType);
6850 }
Steve Naroff68e167d2008-12-10 17:49:55 +00006851 case Type::BlockPointer:
6852 {
6853 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006854 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6855 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006856 if (Unqualified) {
6857 LHSPointee = LHSPointee.getUnqualifiedType();
6858 RHSPointee = RHSPointee.getUnqualifiedType();
6859 }
6860 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6861 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00006862 if (ResultType.isNull()) return QualType();
6863 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6864 return LHS;
6865 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6866 return RHS;
6867 return getBlockPointerType(ResultType);
6868 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00006869 case Type::Atomic:
6870 {
6871 // Merge two pointer types, while trying to preserve typedef info
6872 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6873 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6874 if (Unqualified) {
6875 LHSValue = LHSValue.getUnqualifiedType();
6876 RHSValue = RHSValue.getUnqualifiedType();
6877 }
6878 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6879 Unqualified);
6880 if (ResultType.isNull()) return QualType();
6881 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6882 return LHS;
6883 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6884 return RHS;
6885 return getAtomicType(ResultType);
6886 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006887 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00006888 {
6889 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6890 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6891 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6892 return QualType();
6893
6894 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6895 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006896 if (Unqualified) {
6897 LHSElem = LHSElem.getUnqualifiedType();
6898 RHSElem = RHSElem.getUnqualifiedType();
6899 }
6900
6901 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006902 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00006903 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6904 return LHS;
6905 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6906 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00006907 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6908 ArrayType::ArraySizeModifier(), 0);
6909 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6910 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006911 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6912 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00006913 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6914 return LHS;
6915 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6916 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006917 if (LVAT) {
6918 // FIXME: This isn't correct! But tricky to implement because
6919 // the array's size has to be the size of LHS, but the type
6920 // has to be different.
6921 return LHS;
6922 }
6923 if (RVAT) {
6924 // FIXME: This isn't correct! But tricky to implement because
6925 // the array's size has to be the size of RHS, but the type
6926 // has to be different.
6927 return RHS;
6928 }
Eli Friedman3e62c212008-08-22 01:48:21 +00006929 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6930 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00006931 return getIncompleteArrayType(ResultType,
6932 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006933 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006934 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006935 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006936 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006937 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00006938 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00006939 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006940 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00006941 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00006942 case Type::Complex:
6943 // Distinct complex types are incompatible.
6944 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006945 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00006946 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00006947 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6948 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00006949 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00006950 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00006951 case Type::ObjCObject: {
6952 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00006953 // FIXME: This should be type compatibility, e.g. whether
6954 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00006955 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6956 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6957 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00006958 return LHS;
6959
Eli Friedman47f77112008-08-22 00:56:42 +00006960 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00006961 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006962 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006963 if (OfBlockPointer) {
6964 if (canAssignObjCInterfacesInBlockPointer(
6965 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006966 RHS->getAs<ObjCObjectPointerType>(),
6967 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00006968 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006969 return QualType();
6970 }
John McCall9dd450b2009-09-21 23:43:11 +00006971 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6972 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006973 return LHS;
6974
Steve Naroffc68cfcf2008-12-10 22:14:21 +00006975 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00006976 }
Steve Naroff32e44c02007-10-15 20:41:53 +00006977 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006978
David Blaikie8a40f702012-01-17 06:56:22 +00006979 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00006980}
Ted Kremenekfc581a92007-10-31 17:10:13 +00006981
Fariborz Jahanian97676972011-09-28 21:52:05 +00006982bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6983 const FunctionProtoType *FromFunctionType,
6984 const FunctionProtoType *ToFunctionType) {
6985 if (FromFunctionType->hasAnyConsumedArgs() !=
6986 ToFunctionType->hasAnyConsumedArgs())
6987 return false;
6988 FunctionProtoType::ExtProtoInfo FromEPI =
6989 FromFunctionType->getExtProtoInfo();
6990 FunctionProtoType::ExtProtoInfo ToEPI =
6991 ToFunctionType->getExtProtoInfo();
6992 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6993 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6994 ArgIdx != NumArgs; ++ArgIdx) {
6995 if (FromEPI.ConsumedArguments[ArgIdx] !=
6996 ToEPI.ConsumedArguments[ArgIdx])
6997 return false;
6998 }
6999 return true;
7000}
7001
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007002/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7003/// 'RHS' attributes and returns the merged version; including for function
7004/// return types.
7005QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7006 QualType LHSCan = getCanonicalType(LHS),
7007 RHSCan = getCanonicalType(RHS);
7008 // If two types are identical, they are compatible.
7009 if (LHSCan == RHSCan)
7010 return LHS;
7011 if (RHSCan->isFunctionType()) {
7012 if (!LHSCan->isFunctionType())
7013 return QualType();
7014 QualType OldReturnType =
7015 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
7016 QualType NewReturnType =
7017 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
7018 QualType ResReturnType =
7019 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7020 if (ResReturnType.isNull())
7021 return QualType();
7022 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7023 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7024 // In either case, use OldReturnType to build the new function type.
7025 const FunctionType *F = LHS->getAs<FunctionType>();
7026 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007027 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7028 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007029 QualType ResultType
7030 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00007031 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007032 return ResultType;
7033 }
7034 }
7035 return QualType();
7036 }
7037
7038 // If the qualifiers are different, the types can still be merged.
7039 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7040 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7041 if (LQuals != RQuals) {
7042 // If any of these qualifiers are different, we have a type mismatch.
7043 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7044 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7045 return QualType();
7046
7047 // Exactly one GC qualifier difference is allowed: __strong is
7048 // okay if the other type has no GC qualifier but is an Objective
7049 // C object pointer (i.e. implicitly strong by default). We fix
7050 // this by pretending that the unqualified type was actually
7051 // qualified __strong.
7052 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7053 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7054 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7055
7056 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7057 return QualType();
7058
7059 if (GC_L == Qualifiers::Strong)
7060 return LHS;
7061 if (GC_R == Qualifiers::Strong)
7062 return RHS;
7063 return QualType();
7064 }
7065
7066 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7067 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7068 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7069 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7070 if (ResQT == LHSBaseQT)
7071 return LHS;
7072 if (ResQT == RHSBaseQT)
7073 return RHS;
7074 }
7075 return QualType();
7076}
7077
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007078//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007079// Integer Predicates
7080//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007081
Jay Foad39c79802011-01-12 09:06:06 +00007082unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00007083 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00007084 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007085 if (T->isBooleanType())
7086 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007087 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007088 return (unsigned)getTypeSize(T);
7089}
7090
Abramo Bagnara13640492012-09-09 10:21:24 +00007091QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007092 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007093
7094 // Turn <4 x signed int> -> <4 x unsigned int>
7095 if (const VectorType *VTy = T->getAs<VectorType>())
7096 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007097 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007098
7099 // For enums, we return the unsigned version of the base type.
7100 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007101 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007102
7103 const BuiltinType *BTy = T->getAs<BuiltinType>();
7104 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007105 switch (BTy->getKind()) {
7106 case BuiltinType::Char_S:
7107 case BuiltinType::SChar:
7108 return UnsignedCharTy;
7109 case BuiltinType::Short:
7110 return UnsignedShortTy;
7111 case BuiltinType::Int:
7112 return UnsignedIntTy;
7113 case BuiltinType::Long:
7114 return UnsignedLongTy;
7115 case BuiltinType::LongLong:
7116 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007117 case BuiltinType::Int128:
7118 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007119 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007120 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007121 }
7122}
7123
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007124ASTMutationListener::~ASTMutationListener() { }
7125
Chris Lattnerecd79c62009-06-14 00:45:47 +00007126
7127//===----------------------------------------------------------------------===//
7128// Builtin Type Computation
7129//===----------------------------------------------------------------------===//
7130
7131/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007132/// pointer over the consumed characters. This returns the resultant type. If
7133/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7134/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7135/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007136///
7137/// RequiresICE is filled in on return to indicate whether the value is required
7138/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007139static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007140 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007141 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007142 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007143 // Modifiers.
7144 int HowLong = 0;
7145 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007146 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007147
Chris Lattnerdc226c22010-10-01 22:42:38 +00007148 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007149 bool Done = false;
7150 while (!Done) {
7151 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007152 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007153 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007154 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007155 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007156 case 'S':
7157 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7158 assert(!Signed && "Can't use 'S' modifier multiple times!");
7159 Signed = true;
7160 break;
7161 case 'U':
7162 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7163 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7164 Unsigned = true;
7165 break;
7166 case 'L':
7167 assert(HowLong <= 2 && "Can't have LLLL modifier");
7168 ++HowLong;
7169 break;
7170 }
7171 }
7172
7173 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007174
Chris Lattnerecd79c62009-06-14 00:45:47 +00007175 // Read the base type.
7176 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007177 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007178 case 'v':
7179 assert(HowLong == 0 && !Signed && !Unsigned &&
7180 "Bad modifiers used with 'v'!");
7181 Type = Context.VoidTy;
7182 break;
7183 case 'f':
7184 assert(HowLong == 0 && !Signed && !Unsigned &&
7185 "Bad modifiers used with 'f'!");
7186 Type = Context.FloatTy;
7187 break;
7188 case 'd':
7189 assert(HowLong < 2 && !Signed && !Unsigned &&
7190 "Bad modifiers used with 'd'!");
7191 if (HowLong)
7192 Type = Context.LongDoubleTy;
7193 else
7194 Type = Context.DoubleTy;
7195 break;
7196 case 's':
7197 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7198 if (Unsigned)
7199 Type = Context.UnsignedShortTy;
7200 else
7201 Type = Context.ShortTy;
7202 break;
7203 case 'i':
7204 if (HowLong == 3)
7205 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7206 else if (HowLong == 2)
7207 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7208 else if (HowLong == 1)
7209 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7210 else
7211 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7212 break;
7213 case 'c':
7214 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7215 if (Signed)
7216 Type = Context.SignedCharTy;
7217 else if (Unsigned)
7218 Type = Context.UnsignedCharTy;
7219 else
7220 Type = Context.CharTy;
7221 break;
7222 case 'b': // boolean
7223 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7224 Type = Context.BoolTy;
7225 break;
7226 case 'z': // size_t.
7227 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7228 Type = Context.getSizeType();
7229 break;
7230 case 'F':
7231 Type = Context.getCFConstantStringType();
7232 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007233 case 'G':
7234 Type = Context.getObjCIdType();
7235 break;
7236 case 'H':
7237 Type = Context.getObjCSelType();
7238 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00007239 case 'M':
7240 Type = Context.getObjCSuperType();
7241 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007242 case 'a':
7243 Type = Context.getBuiltinVaListType();
7244 assert(!Type.isNull() && "builtin va list type not initialized!");
7245 break;
7246 case 'A':
7247 // This is a "reference" to a va_list; however, what exactly
7248 // this means depends on how va_list is defined. There are two
7249 // different kinds of va_list: ones passed by value, and ones
7250 // passed by reference. An example of a by-value va_list is
7251 // x86, where va_list is a char*. An example of by-ref va_list
7252 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7253 // we want this argument to be a char*&; for x86-64, we want
7254 // it to be a __va_list_tag*.
7255 Type = Context.getBuiltinVaListType();
7256 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007257 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007258 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007259 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007260 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007261 break;
7262 case 'V': {
7263 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007264 unsigned NumElements = strtoul(Str, &End, 10);
7265 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007266 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007267
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007268 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7269 RequiresICE, false);
7270 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007271
7272 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007273 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007274 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007275 break;
7276 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007277 case 'E': {
7278 char *End;
7279
7280 unsigned NumElements = strtoul(Str, &End, 10);
7281 assert(End != Str && "Missing vector size");
7282
7283 Str = End;
7284
7285 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7286 false);
7287 Type = Context.getExtVectorType(ElementType, NumElements);
7288 break;
7289 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007290 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007291 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7292 false);
7293 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007294 Type = Context.getComplexType(ElementType);
7295 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007296 }
7297 case 'Y' : {
7298 Type = Context.getPointerDiffType();
7299 break;
7300 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007301 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007302 Type = Context.getFILEType();
7303 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007304 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007305 return QualType();
7306 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007307 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007308 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007309 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007310 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007311 else
7312 Type = Context.getjmp_bufType();
7313
Mike Stump2adb4da2009-07-28 23:47:15 +00007314 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007315 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007316 return QualType();
7317 }
7318 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007319 case 'K':
7320 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7321 Type = Context.getucontext_tType();
7322
7323 if (Type.isNull()) {
7324 Error = ASTContext::GE_Missing_ucontext;
7325 return QualType();
7326 }
7327 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00007328 case 'p':
7329 Type = Context.getProcessIDType();
7330 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007331 }
Mike Stump11289f42009-09-09 15:08:12 +00007332
Chris Lattnerdc226c22010-10-01 22:42:38 +00007333 // If there are modifiers and if we're allowed to parse them, go for it.
7334 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007335 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007336 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007337 default: Done = true; --Str; break;
7338 case '*':
7339 case '&': {
7340 // Both pointers and references can have their pointee types
7341 // qualified with an address space.
7342 char *End;
7343 unsigned AddrSpace = strtoul(Str, &End, 10);
7344 if (End != Str && AddrSpace != 0) {
7345 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7346 Str = End;
7347 }
7348 if (c == '*')
7349 Type = Context.getPointerType(Type);
7350 else
7351 Type = Context.getLValueReferenceType(Type);
7352 break;
7353 }
7354 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7355 case 'C':
7356 Type = Type.withConst();
7357 break;
7358 case 'D':
7359 Type = Context.getVolatileType(Type);
7360 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007361 case 'R':
7362 Type = Type.withRestrict();
7363 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007364 }
7365 }
Chris Lattner84733392010-10-01 07:13:18 +00007366
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007367 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007368 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007369
Chris Lattnerecd79c62009-06-14 00:45:47 +00007370 return Type;
7371}
7372
7373/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007374QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007375 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007376 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007377 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007378
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007379 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007380
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007381 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007382 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007383 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7384 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007385 if (Error != GE_None)
7386 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007387
7388 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7389
Chris Lattnerecd79c62009-06-14 00:45:47 +00007390 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007391 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007392 if (Error != GE_None)
7393 return QualType();
7394
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007395 // If this argument is required to be an IntegerConstantExpression and the
7396 // caller cares, fill in the bitmask we return.
7397 if (RequiresICE && IntegerConstantArgs)
7398 *IntegerConstantArgs |= 1 << ArgTypes.size();
7399
Chris Lattnerecd79c62009-06-14 00:45:47 +00007400 // Do array -> pointer decay. The builtin should use the decayed type.
7401 if (Ty->isArrayType())
7402 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007403
Chris Lattnerecd79c62009-06-14 00:45:47 +00007404 ArgTypes.push_back(Ty);
7405 }
7406
7407 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7408 "'.' should only occur at end of builtin type list!");
7409
John McCall991eb4b2010-12-21 00:44:39 +00007410 FunctionType::ExtInfo EI;
7411 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7412
7413 bool Variadic = (TypeStr[0] == '.');
7414
7415 // We really shouldn't be making a no-proto type here, especially in C++.
7416 if (ArgTypes.empty() && Variadic)
7417 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007418
John McCalldb40c7f2010-12-14 08:05:40 +00007419 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007420 EPI.ExtInfo = EI;
7421 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007422
7423 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007424}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007425
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007426GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
7427 GVALinkage External = GVA_StrongExternal;
7428
7429 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007430 switch (L) {
7431 case NoLinkage:
7432 case InternalLinkage:
7433 case UniqueExternalLinkage:
7434 return GVA_Internal;
7435
7436 case ExternalLinkage:
7437 switch (FD->getTemplateSpecializationKind()) {
7438 case TSK_Undeclared:
7439 case TSK_ExplicitSpecialization:
7440 External = GVA_StrongExternal;
7441 break;
7442
7443 case TSK_ExplicitInstantiationDefinition:
7444 return GVA_ExplicitTemplateInstantiation;
7445
7446 case TSK_ExplicitInstantiationDeclaration:
7447 case TSK_ImplicitInstantiation:
7448 External = GVA_TemplateInstantiation;
7449 break;
7450 }
7451 }
7452
7453 if (!FD->isInlined())
7454 return External;
7455
David Blaikiebbafb8a2012-03-11 07:00:24 +00007456 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007457 // GNU or C99 inline semantics. Determine whether this symbol should be
7458 // externally visible.
7459 if (FD->isInlineDefinitionExternallyVisible())
7460 return External;
7461
7462 // C99 inline semantics, where the symbol is not externally visible.
7463 return GVA_C99Inline;
7464 }
7465
7466 // C++0x [temp.explicit]p9:
7467 // [ Note: The intent is that an inline function that is the subject of
7468 // an explicit instantiation declaration will still be implicitly
7469 // instantiated when used so that the body can be considered for
7470 // inlining, but that no out-of-line copy of the inline function would be
7471 // generated in the translation unit. -- end note ]
7472 if (FD->getTemplateSpecializationKind()
7473 == TSK_ExplicitInstantiationDeclaration)
7474 return GVA_C99Inline;
7475
7476 return GVA_CXXInline;
7477}
7478
7479GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7480 // If this is a static data member, compute the kind of template
7481 // specialization. Otherwise, this variable is not part of a
7482 // template.
7483 TemplateSpecializationKind TSK = TSK_Undeclared;
7484 if (VD->isStaticDataMember())
7485 TSK = VD->getTemplateSpecializationKind();
7486
7487 Linkage L = VD->getLinkage();
Rafael Espindola6525f962013-01-02 04:19:07 +00007488 assert (!(L == ExternalLinkage && getLangOpts().CPlusPlus &&
7489 VD->getType()->getLinkage() == UniqueExternalLinkage));
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007490
7491 switch (L) {
7492 case NoLinkage:
7493 case InternalLinkage:
7494 case UniqueExternalLinkage:
7495 return GVA_Internal;
7496
7497 case ExternalLinkage:
7498 switch (TSK) {
7499 case TSK_Undeclared:
7500 case TSK_ExplicitSpecialization:
7501 return GVA_StrongExternal;
7502
7503 case TSK_ExplicitInstantiationDeclaration:
7504 llvm_unreachable("Variable should not be instantiated");
7505 // Fall through to treat this like any other instantiation.
7506
7507 case TSK_ExplicitInstantiationDefinition:
7508 return GVA_ExplicitTemplateInstantiation;
7509
7510 case TSK_ImplicitInstantiation:
7511 return GVA_TemplateInstantiation;
7512 }
7513 }
7514
David Blaikie8a40f702012-01-17 06:56:22 +00007515 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007516}
7517
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007518bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007519 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7520 if (!VD->isFileVarDecl())
7521 return false;
Argyrios Kyrtzidisa98e8612011-09-13 21:35:00 +00007522 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007523 return false;
7524
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007525 // Weak references don't produce any output by themselves.
7526 if (D->hasAttr<WeakRefAttr>())
7527 return false;
7528
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007529 // Aliases and used decls are required.
7530 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7531 return true;
7532
7533 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7534 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007535 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007536 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007537
7538 // Constructors and destructors are required.
7539 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7540 return true;
7541
7542 // The key function for a class is required.
7543 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7544 const CXXRecordDecl *RD = MD->getParent();
7545 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7546 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
7547 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7548 return true;
7549 }
7550 }
7551
7552 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7553
7554 // static, static inline, always_inline, and extern inline functions can
7555 // always be deferred. Normal inline functions can be deferred in C99/C++.
7556 // Implicit template instantiations can also be deferred in C++.
7557 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007558 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007559 return false;
7560 return true;
7561 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007562
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007563 const VarDecl *VD = cast<VarDecl>(D);
7564 assert(VD->isFileVarDecl() && "Expected file scoped var");
7565
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007566 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7567 return false;
7568
Richard Smitha0e5e542012-11-12 21:38:00 +00007569 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007570 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smitha0e5e542012-11-12 21:38:00 +00007571 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7572 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007573
Richard Smitha0e5e542012-11-12 21:38:00 +00007574 // Variables that have destruction with side-effects are required.
7575 if (VD->getType().isDestructedType())
7576 return true;
7577
7578 // Variables that have initialization with side-effects are required.
7579 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7580 return true;
7581
7582 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007583}
Charles Davis53c59df2010-08-16 03:33:14 +00007584
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007585CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davis99202b32010-11-09 18:04:24 +00007586 // Pass through to the C++ ABI object
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007587 return ABI->getDefaultMethodCallConv(isVariadic);
7588}
7589
7590CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
7591 if (CC == CC_C && !LangOpts.MRTD && getTargetInfo().getCXXABI() != CXXABI_Microsoft)
7592 return CC_Default;
7593 return CC;
Charles Davis99202b32010-11-09 18:04:24 +00007594}
7595
Jay Foad39c79802011-01-12 09:06:06 +00007596bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007597 // Pass through to the C++ ABI object
7598 return ABI->isNearlyEmpty(RD);
7599}
7600
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007601MangleContext *ASTContext::createMangleContext() {
Douglas Gregore8bbc122011-09-02 00:18:52 +00007602 switch (Target->getCXXABI()) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007603 case CXXABI_ARM:
7604 case CXXABI_Itanium:
7605 return createItaniumMangleContext(*this, getDiagnostics());
7606 case CXXABI_Microsoft:
7607 return createMicrosoftMangleContext(*this, getDiagnostics());
7608 }
David Blaikie83d382b2011-09-23 05:06:16 +00007609 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007610}
7611
Charles Davis53c59df2010-08-16 03:33:14 +00007612CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007613
7614size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00007615 return ASTRecordLayouts.getMemorySize()
7616 + llvm::capacity_in_bytes(ObjCLayouts)
7617 + llvm::capacity_in_bytes(KeyFunctions)
7618 + llvm::capacity_in_bytes(ObjCImpls)
7619 + llvm::capacity_in_bytes(BlockVarCopyInits)
7620 + llvm::capacity_in_bytes(DeclAttrs)
7621 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7622 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7623 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7624 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7625 + llvm::capacity_in_bytes(OverriddenMethods)
7626 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007627 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00007628 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007629}
Ted Kremenek540017e2011-10-06 05:00:56 +00007630
David Blaikie095deba2012-11-14 01:52:05 +00007631void ASTContext::addUnnamedTag(const TagDecl *Tag) {
7632 // FIXME: This mangling should be applied to function local classes too
7633 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl() ||
7634 !isa<CXXRecordDecl>(Tag->getParent()) || Tag->getLinkage() != ExternalLinkage)
7635 return;
7636
7637 std::pair<llvm::DenseMap<const DeclContext *, unsigned>::iterator, bool> P =
7638 UnnamedMangleContexts.insert(std::make_pair(Tag->getParent(), 0));
7639 UnnamedMangleNumbers.insert(std::make_pair(Tag, P.first->second++));
7640}
7641
7642int ASTContext::getUnnamedTagManglingNumber(const TagDecl *Tag) const {
7643 llvm::DenseMap<const TagDecl *, unsigned>::const_iterator I =
7644 UnnamedMangleNumbers.find(Tag);
7645 return I != UnnamedMangleNumbers.end() ? I->second : -1;
7646}
7647
Douglas Gregor63798542012-02-20 19:44:39 +00007648unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7649 CXXRecordDecl *Lambda = CallOperator->getParent();
7650 return LambdaMangleContexts[Lambda->getDeclContext()]
7651 .getManglingNumber(CallOperator);
7652}
7653
7654
Ted Kremenek540017e2011-10-06 05:00:56 +00007655void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7656 ParamIndices[D] = index;
7657}
7658
7659unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7660 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7661 assert(I != ParamIndices.end() &&
7662 "ParmIndices lacks entry set by ParmVarDecl");
7663 return I->second;
7664}