blob: 2e13d0cc445485a64f76c0c54e18320ddb1d79a6 [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"
Ken Dyck8c89d592009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Dmitri Gribenkoec925312012-07-06 00:28:32 +000016#include "clang/AST/CommentLexer.h"
17#include "clang/AST/CommentSema.h"
18#include "clang/AST/CommentParser.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000019#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000020#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000021#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +000022#include "clang/AST/TypeLoc.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000023#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000024#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000025#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +000026#include "clang/AST/ASTMutationListener.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000027#include "clang/AST/RecordLayout.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000028#include "clang/AST/Mangle.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000029#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000030#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000031#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000032#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000033#include "llvm/ADT/StringExtras.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000034#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000035#include "llvm/Support/raw_ostream.h"
Ted Kremenek7d39c9a2011-07-27 18:41:12 +000036#include "llvm/Support/Capacity.h"
Charles Davis53c59df2010-08-16 03:33:14 +000037#include "CXXABI.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 Gribenkoaab83832012-06-20 00:34:58 +000071 // TODO: handle comments for function parameters properly.
72 if (isa<ParmVarDecl>(D))
73 return NULL;
74
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +000075 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000076
77 // If there are no comments anywhere, we won't find anything.
78 if (RawComments.empty())
79 return NULL;
80
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +000081 // Find declaration location.
82 // For Objective-C declarations we generally don't expect to have multiple
83 // declarators, thus use declaration starting location as the "declaration
84 // location".
85 // For all other declarations multiple declarators are used quite frequently,
86 // so we use the location of the identifier as the "declaration location".
87 SourceLocation DeclLoc;
88 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
89 isa<ObjCPropertyDecl>(D))
90 DeclLoc = D->getLocStart();
91 else
92 DeclLoc = D->getLocation();
93
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000094 // If the declaration doesn't map directly to a location in a file, we
95 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000096 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
97 return NULL;
98
99 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000100 ArrayRef<RawComment *>::iterator Comment;
101 {
102 // When searching for comments during parsing, the comment we are looking
103 // for is usually among the last two comments we parsed -- check them
104 // first.
105 RawComment CommentAtDeclLoc(SourceMgr, SourceRange(DeclLoc));
106 BeforeThanCompare<RawComment> Compare(SourceMgr);
107 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
108 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
109 if (!Found && RawComments.size() >= 2) {
110 MaybeBeforeDecl--;
111 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
112 }
113
114 if (Found) {
115 Comment = MaybeBeforeDecl + 1;
116 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
117 &CommentAtDeclLoc, Compare));
118 } else {
119 // Slow path.
120 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
121 &CommentAtDeclLoc, Compare);
122 }
123 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000124
125 // Decompose the location for the declaration and find the beginning of the
126 // file buffer.
127 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
128
129 // First check whether we have a trailing comment.
130 if (Comment != RawComments.end() &&
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000131 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Dmitri Gribenko44cd7e62012-07-06 23:27:33 +0000132 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000133 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000134 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000135 // Check that Doxygen trailing comment comes after the declaration, starts
136 // on the same line and in the same file as the declaration.
137 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
138 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
139 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
140 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000141 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000142 }
143 }
144
145 // The comment just after the declaration was not a trailing comment.
146 // Let's look at the previous comment.
147 if (Comment == RawComments.begin())
148 return NULL;
149 --Comment;
150
151 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000152 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000153 return NULL;
154
155 // Decompose the end of the comment.
156 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000157 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000158
159 // If the comment and the declaration aren't in the same file, then they
160 // aren't related.
161 if (DeclLocDecomp.first != CommentEndDecomp.first)
162 return NULL;
163
164 // Get the corresponding buffer.
165 bool Invalid = false;
166 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
167 &Invalid).data();
168 if (Invalid)
169 return NULL;
170
171 // Extract text between the comment and declaration.
172 StringRef Text(Buffer + CommentEndDecomp.second,
173 DeclLocDecomp.second - CommentEndDecomp.second);
174
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000175 // There should be no other declarations or preprocessor directives between
176 // comment and declaration.
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000177 if (Text.find_first_of(",;{}#@") != StringRef::npos)
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000178 return NULL;
179
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000180 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000181}
182
183const RawComment *ASTContext::getRawCommentForDecl(const Decl *D) const {
184 // Check whether we have cached a comment string for this declaration
185 // already.
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000186 llvm::DenseMap<const Decl *, RawAndParsedComment>::iterator Pos
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000187 = DeclComments.find(D);
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000188 if (Pos != DeclComments.end()) {
189 RawAndParsedComment C = Pos->second;
190 return C.first;
191 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000192
Dmitri Gribenkof26054f2012-07-11 21:38:39 +0000193 RawComment *RC = getRawCommentForDeclNoCache(D);
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000194 // If we found a comment, it should be a documentation comment.
195 assert(!RC || RC->isDocumentation());
Dmitri Gribenko08630052012-07-06 15:40:08 +0000196 DeclComments[D] =
197 RawAndParsedComment(RC, static_cast<comments::FullComment *>(NULL));
Dmitri Gribenkof26054f2012-07-11 21:38:39 +0000198 if (RC)
199 RC->setAttached();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000200 return RC;
201}
202
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000203comments::FullComment *ASTContext::getCommentForDecl(const Decl *D) const {
204 llvm::DenseMap<const Decl *, RawAndParsedComment>::iterator Pos
205 = DeclComments.find(D);
206 const RawComment *RC;
207 if (Pos != DeclComments.end()) {
208 RawAndParsedComment C = Pos->second;
209 if (comments::FullComment *FC = C.second)
210 return FC;
211 RC = C.first;
212 } else
213 RC = getRawCommentForDecl(D);
214
215 if (!RC)
216 return NULL;
217
218 const StringRef RawText = RC->getRawText(SourceMgr);
219 comments::Lexer L(RC->getSourceRange().getBegin(), comments::CommentOptions(),
220 RawText.begin(), RawText.end());
221
Dmitri Gribenkof26054f2012-07-11 21:38:39 +0000222 comments::Sema S(getAllocator(), getSourceManager(), getDiagnostics());
223 S.setDecl(D);
224 comments::Parser P(L, S, getAllocator(), getSourceManager(),
225 getDiagnostics());
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000226
227 comments::FullComment *FC = P.parseFullComment();
228 DeclComments[D].second = FC;
229 return FC;
230}
231
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000232void
233ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
234 TemplateTemplateParmDecl *Parm) {
235 ID.AddInteger(Parm->getDepth());
236 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000237 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000238
239 TemplateParameterList *Params = Parm->getTemplateParameters();
240 ID.AddInteger(Params->size());
241 for (TemplateParameterList::const_iterator P = Params->begin(),
242 PEnd = Params->end();
243 P != PEnd; ++P) {
244 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
245 ID.AddInteger(0);
246 ID.AddBoolean(TTP->isParameterPack());
247 continue;
248 }
249
250 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
251 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000252 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000253 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000254 if (NTTP->isExpandedParameterPack()) {
255 ID.AddBoolean(true);
256 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000257 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
258 QualType T = NTTP->getExpansionType(I);
259 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
260 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000261 } else
262 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000263 continue;
264 }
265
266 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
267 ID.AddInteger(2);
268 Profile(ID, TTP);
269 }
270}
271
272TemplateTemplateParmDecl *
273ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000274 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000275 // Check if we already have a canonical template template parameter.
276 llvm::FoldingSetNodeID ID;
277 CanonicalTemplateTemplateParm::Profile(ID, TTP);
278 void *InsertPos = 0;
279 CanonicalTemplateTemplateParm *Canonical
280 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
281 if (Canonical)
282 return Canonical->getParam();
283
284 // Build a canonical template parameter list.
285 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000286 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000287 CanonParams.reserve(Params->size());
288 for (TemplateParameterList::const_iterator P = Params->begin(),
289 PEnd = Params->end();
290 P != PEnd; ++P) {
291 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
292 CanonParams.push_back(
293 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000294 SourceLocation(),
295 SourceLocation(),
296 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000297 TTP->getIndex(), 0, false,
298 TTP->isParameterPack()));
299 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000300 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
301 QualType T = getCanonicalType(NTTP->getType());
302 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
303 NonTypeTemplateParmDecl *Param;
304 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000305 SmallVector<QualType, 2> ExpandedTypes;
306 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000307 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
308 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
309 ExpandedTInfos.push_back(
310 getTrivialTypeSourceInfo(ExpandedTypes.back()));
311 }
312
313 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000314 SourceLocation(),
315 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000316 NTTP->getDepth(),
317 NTTP->getPosition(), 0,
318 T,
319 TInfo,
320 ExpandedTypes.data(),
321 ExpandedTypes.size(),
322 ExpandedTInfos.data());
323 } else {
324 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000325 SourceLocation(),
326 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000327 NTTP->getDepth(),
328 NTTP->getPosition(), 0,
329 T,
330 NTTP->isParameterPack(),
331 TInfo);
332 }
333 CanonParams.push_back(Param);
334
335 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000336 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
337 cast<TemplateTemplateParmDecl>(*P)));
338 }
339
340 TemplateTemplateParmDecl *CanonTTP
341 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
342 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000343 TTP->getPosition(),
344 TTP->isParameterPack(),
345 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000346 TemplateParameterList::Create(*this, SourceLocation(),
347 SourceLocation(),
348 CanonParams.data(),
349 CanonParams.size(),
350 SourceLocation()));
351
352 // Get the new insert position for the node we care about.
353 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
354 assert(Canonical == 0 && "Shouldn't be in the map!");
355 (void)Canonical;
356
357 // Create the canonical template template parameter entry.
358 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
359 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
360 return CanonTTP;
361}
362
Charles Davis53c59df2010-08-16 03:33:14 +0000363CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000364 if (!LangOpts.CPlusPlus) return 0;
365
Charles Davis6bcb07a2010-08-19 02:18:14 +0000366 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000367 case CXXABI_ARM:
368 return CreateARMCXXABI(*this);
369 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000370 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000371 case CXXABI_Microsoft:
372 return CreateMicrosoftCXXABI(*this);
373 }
David Blaikie8a40f702012-01-17 06:56:22 +0000374 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000375}
376
Douglas Gregore8bbc122011-09-02 00:18:52 +0000377static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000378 const LangOptions &LOpts) {
379 if (LOpts.FakeAddressSpaceMap) {
380 // The fake address space map must have a distinct entry for each
381 // language-specific address space.
382 static const unsigned FakeAddrSpaceMap[] = {
383 1, // opencl_global
384 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000385 3, // opencl_constant
386 4, // cuda_device
387 5, // cuda_constant
388 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000389 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000390 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000391 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000392 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000393 }
394}
395
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000396ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000397 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000398 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000399 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000400 unsigned size_reserve,
401 bool DelayInitialization)
402 : FunctionProtoTypes(this_()),
403 TemplateSpecializationTypes(this_()),
404 DependentTemplateSpecializationTypes(this_()),
405 SubstTemplateTemplateParmPacks(this_()),
406 GlobalNestedNameSpecifier(0),
407 Int128Decl(0), UInt128Decl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000408 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000409 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000410 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000411 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000412 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
413 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
414 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000415 NullTypeSourceInfo(QualType()),
416 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000417 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000418 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000419 Idents(idents), Selectors(sels),
420 BuiltinInfo(builtins),
421 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000422 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000423 Comments(SM), CommentsLoaded(false),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000424 LastSDM(0, 0),
425 UniqueBlockByRefTypeID(0)
426{
Mike Stump11289f42009-09-09 15:08:12 +0000427 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000428 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000429
430 if (!DelayInitialization) {
431 assert(t && "No target supplied for ASTContext initialization");
432 InitBuiltinTypes(*t);
433 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000434}
435
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000436ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000437 // Release the DenseMaps associated with DeclContext objects.
438 // FIXME: Is this the ideal solution?
439 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000440
Douglas Gregor5b11d492010-07-25 17:53:33 +0000441 // Call all of the deallocation functions.
442 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
443 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000444
Ted Kremenek076baeb2010-06-08 23:00:58 +0000445 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000446 // because they can contain DenseMaps.
447 for (llvm::DenseMap<const ObjCContainerDecl*,
448 const ASTRecordLayout*>::iterator
449 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
450 // Increment in loop to prevent using deallocated memory.
451 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
452 R->Destroy(*this);
453
Ted Kremenek076baeb2010-06-08 23:00:58 +0000454 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
455 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
456 // Increment in loop to prevent using deallocated memory.
457 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
458 R->Destroy(*this);
459 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000460
461 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
462 AEnd = DeclAttrs.end();
463 A != AEnd; ++A)
464 A->second->~AttrVec();
465}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000466
Douglas Gregor1a809332010-05-23 18:26:36 +0000467void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
468 Deallocations.push_back(std::make_pair(Callback, Data));
469}
470
Mike Stump11289f42009-09-09 15:08:12 +0000471void
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000472ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000473 ExternalSource.reset(Source.take());
474}
475
Chris Lattner4eb445d2007-01-26 01:27:23 +0000476void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000477 llvm::errs() << "\n*** AST Context Stats:\n";
478 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000479
Douglas Gregora30d0462009-05-26 14:40:08 +0000480 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000481#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000482#define ABSTRACT_TYPE(Name, Parent)
483#include "clang/AST/TypeNodes.def"
484 0 // Extra
485 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000486
Chris Lattner4eb445d2007-01-26 01:27:23 +0000487 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
488 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000489 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000490 }
491
Douglas Gregora30d0462009-05-26 14:40:08 +0000492 unsigned Idx = 0;
493 unsigned TotalBytes = 0;
494#define TYPE(Name, Parent) \
495 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000496 llvm::errs() << " " << counts[Idx] << " " << #Name \
497 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000498 TotalBytes += counts[Idx] * sizeof(Name##Type); \
499 ++Idx;
500#define ABSTRACT_TYPE(Name, Parent)
501#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000502
Chandler Carruth3c147a72011-07-04 05:32:14 +0000503 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
504
Douglas Gregor7454c562010-07-02 20:37:36 +0000505 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000506 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
507 << NumImplicitDefaultConstructors
508 << " implicit default constructors created\n";
509 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
510 << NumImplicitCopyConstructors
511 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000512 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000513 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
514 << NumImplicitMoveConstructors
515 << " implicit move constructors created\n";
516 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
517 << NumImplicitCopyAssignmentOperators
518 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000519 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000520 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
521 << NumImplicitMoveAssignmentOperators
522 << " implicit move assignment operators created\n";
523 llvm::errs() << NumImplicitDestructorsDeclared << "/"
524 << NumImplicitDestructors
525 << " implicit destructors created\n";
526
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000527 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000528 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000529 ExternalSource->PrintStats();
530 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000531
Douglas Gregor5b11d492010-07-25 17:53:33 +0000532 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000533}
534
Douglas Gregor801c99d2011-08-12 06:49:56 +0000535TypedefDecl *ASTContext::getInt128Decl() const {
536 if (!Int128Decl) {
537 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
538 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
539 getTranslationUnitDecl(),
540 SourceLocation(),
541 SourceLocation(),
542 &Idents.get("__int128_t"),
543 TInfo);
544 }
545
546 return Int128Decl;
547}
548
549TypedefDecl *ASTContext::getUInt128Decl() const {
550 if (!UInt128Decl) {
551 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
552 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
553 getTranslationUnitDecl(),
554 SourceLocation(),
555 SourceLocation(),
556 &Idents.get("__uint128_t"),
557 TInfo);
558 }
559
560 return UInt128Decl;
561}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000562
John McCall48f2d582009-10-23 23:03:21 +0000563void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000564 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000565 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000566 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000567}
568
Douglas Gregore8bbc122011-09-02 00:18:52 +0000569void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
570 assert((!this->Target || this->Target == &Target) &&
571 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000572 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000573
Douglas Gregore8bbc122011-09-02 00:18:52 +0000574 this->Target = &Target;
575
576 ABI.reset(createCXXABI(Target));
577 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
578
Chris Lattner970e54e2006-11-12 00:37:36 +0000579 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000580 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000581
Chris Lattner970e54e2006-11-12 00:37:36 +0000582 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000583 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000584 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000585 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000586 InitBuiltinType(CharTy, BuiltinType::Char_S);
587 else
588 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000589 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000590 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
591 InitBuiltinType(ShortTy, BuiltinType::Short);
592 InitBuiltinType(IntTy, BuiltinType::Int);
593 InitBuiltinType(LongTy, BuiltinType::Long);
594 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000595
Chris Lattner970e54e2006-11-12 00:37:36 +0000596 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000597 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
598 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
599 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
600 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
601 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000602
Chris Lattner970e54e2006-11-12 00:37:36 +0000603 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000604 InitBuiltinType(FloatTy, BuiltinType::Float);
605 InitBuiltinType(DoubleTy, BuiltinType::Double);
606 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000607
Chris Lattnerf122cef2009-04-30 02:43:43 +0000608 // GNU extension, 128-bit integers.
609 InitBuiltinType(Int128Ty, BuiltinType::Int128);
610 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
611
Chris Lattnerad3467e2010-12-25 23:25:43 +0000612 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedman786d0872011-04-30 19:24:24 +0000613 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000614 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
615 else // -fshort-wchar makes wchar_t be unsigned.
616 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
617 } else // C99
Chris Lattner007cb022009-02-26 23:43:47 +0000618 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000619
James Molloy36365542012-05-04 10:55:22 +0000620 WIntTy = getFromTargetType(Target.getWIntType());
621
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000622 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
623 InitBuiltinType(Char16Ty, BuiltinType::Char16);
624 else // C99
625 Char16Ty = getFromTargetType(Target.getChar16Type());
626
627 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
628 InitBuiltinType(Char32Ty, BuiltinType::Char32);
629 else // C99
630 Char32Ty = getFromTargetType(Target.getChar32Type());
631
Douglas Gregor4619e432008-12-05 23:32:09 +0000632 // Placeholder type for type-dependent expressions whose type is
633 // completely unknown. No code should ever check a type against
634 // DependentTy and users should never see it; however, it is here to
635 // help diagnose failures to properly check for type-dependent
636 // expressions.
637 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000638
John McCall36e7fe32010-10-12 00:20:44 +0000639 // Placeholder type for functions.
640 InitBuiltinType(OverloadTy, BuiltinType::Overload);
641
John McCall0009fcc2011-04-26 20:42:42 +0000642 // Placeholder type for bound members.
643 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
644
John McCall526ab472011-10-25 17:37:35 +0000645 // Placeholder type for pseudo-objects.
646 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
647
John McCall31996342011-04-07 08:22:57 +0000648 // "any" type; useful for debugger-like clients.
649 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
650
John McCall8a6b59a2011-10-17 18:09:15 +0000651 // Placeholder type for unbridged ARC casts.
652 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
653
Chris Lattner970e54e2006-11-12 00:37:36 +0000654 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000655 FloatComplexTy = getComplexType(FloatTy);
656 DoubleComplexTy = getComplexType(DoubleTy);
657 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000658
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000659 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000660 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
661 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000662 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000663
664 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +0000665 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
666 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000667
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000668 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000669
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000670 // void * type
671 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000672
673 // nullptr type (C++0x 2.14.7)
674 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000675
676 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
677 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +0000678
679 // Builtin type used to help define __builtin_va_list.
680 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +0000681}
682
David Blaikie9c902b52011-09-25 23:23:43 +0000683DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000684 return SourceMgr.getDiagnostics();
685}
686
Douglas Gregor561eceb2010-08-30 16:49:28 +0000687AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
688 AttrVec *&Result = DeclAttrs[D];
689 if (!Result) {
690 void *Mem = Allocate(sizeof(AttrVec));
691 Result = new (Mem) AttrVec;
692 }
693
694 return *Result;
695}
696
697/// \brief Erase the attributes corresponding to the given declaration.
698void ASTContext::eraseDeclAttrs(const Decl *D) {
699 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
700 if (Pos != DeclAttrs.end()) {
701 Pos->second->~AttrVec();
702 DeclAttrs.erase(Pos);
703 }
704}
705
Douglas Gregor86d142a2009-10-08 07:24:58 +0000706MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000707ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000708 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000709 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000710 = InstantiatedFromStaticDataMember.find(Var);
711 if (Pos == InstantiatedFromStaticDataMember.end())
712 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000713
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000714 return Pos->second;
715}
716
Mike Stump11289f42009-09-09 15:08:12 +0000717void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000718ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000719 TemplateSpecializationKind TSK,
720 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000721 assert(Inst->isStaticDataMember() && "Not a static data member");
722 assert(Tmpl->isStaticDataMember() && "Not a static data member");
723 assert(!InstantiatedFromStaticDataMember[Inst] &&
724 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000725 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000726 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000727}
728
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000729FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
730 const FunctionDecl *FD){
731 assert(FD && "Specialization is 0");
732 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +0000733 = ClassScopeSpecializationPattern.find(FD);
734 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000735 return 0;
736
737 return Pos->second;
738}
739
740void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
741 FunctionDecl *Pattern) {
742 assert(FD && "Specialization is 0");
743 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +0000744 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000745}
746
John McCalle61f2ba2009-11-18 02:36:19 +0000747NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000748ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000749 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000750 = InstantiatedFromUsingDecl.find(UUD);
751 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000752 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000753
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000754 return Pos->second;
755}
756
757void
John McCallb96ec562009-12-04 22:46:56 +0000758ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
759 assert((isa<UsingDecl>(Pattern) ||
760 isa<UnresolvedUsingValueDecl>(Pattern) ||
761 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
762 "pattern decl is not a using decl");
763 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
764 InstantiatedFromUsingDecl[Inst] = Pattern;
765}
766
767UsingShadowDecl *
768ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
769 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
770 = InstantiatedFromUsingShadowDecl.find(Inst);
771 if (Pos == InstantiatedFromUsingShadowDecl.end())
772 return 0;
773
774 return Pos->second;
775}
776
777void
778ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
779 UsingShadowDecl *Pattern) {
780 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
781 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000782}
783
Anders Carlsson5da84842009-09-01 04:26:58 +0000784FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
785 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
786 = InstantiatedFromUnnamedFieldDecl.find(Field);
787 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
788 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000789
Anders Carlsson5da84842009-09-01 04:26:58 +0000790 return Pos->second;
791}
792
793void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
794 FieldDecl *Tmpl) {
795 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
796 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
797 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
798 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000799
Anders Carlsson5da84842009-09-01 04:26:58 +0000800 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
801}
802
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000803bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
804 const FieldDecl *LastFD) const {
805 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000806 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000807}
808
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000809bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
810 const FieldDecl *LastFD) const {
811 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000812 FD->getBitWidthValue(*this) == 0 &&
813 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000814}
815
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000816bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
817 const FieldDecl *LastFD) const {
818 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000819 FD->getBitWidthValue(*this) &&
820 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000821}
822
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000823bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000824 const FieldDecl *LastFD) const {
825 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000826 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000827}
828
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000829bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000830 const FieldDecl *LastFD) const {
831 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000832 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000833}
834
Douglas Gregor832940b2010-03-02 23:58:15 +0000835ASTContext::overridden_cxx_method_iterator
836ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
837 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
838 = OverriddenMethods.find(Method);
839 if (Pos == OverriddenMethods.end())
840 return 0;
841
842 return Pos->second.begin();
843}
844
845ASTContext::overridden_cxx_method_iterator
846ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
847 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
848 = OverriddenMethods.find(Method);
849 if (Pos == OverriddenMethods.end())
850 return 0;
851
852 return Pos->second.end();
853}
854
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000855unsigned
856ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
857 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
858 = OverriddenMethods.find(Method);
859 if (Pos == OverriddenMethods.end())
860 return 0;
861
862 return Pos->second.size();
863}
864
Douglas Gregor832940b2010-03-02 23:58:15 +0000865void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
866 const CXXMethodDecl *Overridden) {
867 OverriddenMethods[Method].push_back(Overridden);
868}
869
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000870void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
871 assert(!Import->NextLocalImport && "Import declaration already in the chain");
872 assert(!Import->isFromASTFile() && "Non-local import declaration");
873 if (!FirstLocalImport) {
874 FirstLocalImport = Import;
875 LastLocalImport = Import;
876 return;
877 }
878
879 LastLocalImport->NextLocalImport = Import;
880 LastLocalImport = Import;
881}
882
Chris Lattner53cfe802007-07-18 17:52:12 +0000883//===----------------------------------------------------------------------===//
884// Type Sizing and Analysis
885//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000886
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000887/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
888/// scalar floating point type.
889const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000890 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000891 assert(BT && "Not a floating point type!");
892 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +0000893 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000894 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +0000895 case BuiltinType::Float: return Target->getFloatFormat();
896 case BuiltinType::Double: return Target->getDoubleFormat();
897 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000898 }
899}
900
Ken Dyck160146e2010-01-27 17:10:57 +0000901/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000902/// specified decl. Note that bitfields do not have a valid alignment, so
903/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000904/// If @p RefAsPointee, references are treated like their underlying type
905/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000906CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000907 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +0000908
John McCall94268702010-10-08 18:24:19 +0000909 bool UseAlignAttrOnly = false;
910 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
911 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000912
John McCall94268702010-10-08 18:24:19 +0000913 // __attribute__((aligned)) can increase or decrease alignment
914 // *except* on a struct or struct member, where it only increases
915 // alignment unless 'packed' is also specified.
916 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +0000917 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +0000918 // ignore that possibility; Sema should diagnose it.
919 if (isa<FieldDecl>(D)) {
920 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
921 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
922 } else {
923 UseAlignAttrOnly = true;
924 }
925 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +0000926 else if (isa<FieldDecl>(D))
927 UseAlignAttrOnly =
928 D->hasAttr<PackedAttr>() ||
929 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +0000930
John McCall4e819612011-01-20 07:57:12 +0000931 // If we're using the align attribute only, just ignore everything
932 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +0000933 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +0000934 // do nothing
935
John McCall94268702010-10-08 18:24:19 +0000936 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000937 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000938 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000939 if (RefAsPointee)
940 T = RT->getPointeeType();
941 else
942 T = getPointerType(RT->getPointeeType());
943 }
944 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +0000945 // Adjust alignments of declarations with array type by the
946 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +0000947 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +0000948 const ArrayType *arrayType;
949 if (MinWidth && (arrayType = getAsArrayType(T))) {
950 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000951 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +0000952 else if (isa<ConstantArrayType>(arrayType) &&
953 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000954 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +0000955
John McCall33ddac02011-01-19 10:06:00 +0000956 // Walk through any array types while we're at it.
957 T = getBaseElementType(arrayType);
958 }
Chad Rosier99ee7822011-07-26 07:03:04 +0000959 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +0000960 }
John McCall4e819612011-01-20 07:57:12 +0000961
962 // Fields can be subject to extra alignment constraints, like if
963 // the field is packed, the struct is packed, or the struct has a
964 // a max-field-alignment constraint (#pragma pack). So calculate
965 // the actual alignment of the field within the struct, and then
966 // (as we're expected to) constrain that by the alignment of the type.
967 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
968 // So calculate the alignment of the field.
969 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
970
971 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +0000972 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +0000973
974 // Use the GCD of that and the offset within the record.
975 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
976 if (offset > 0) {
977 // Alignment is always a power of 2, so the GCD will be a power of 2,
978 // which means we get to do this crazy thing instead of Euclid's.
979 uint64_t lowBitOfOffset = offset & (~offset + 1);
980 if (lowBitOfOffset < fieldAlign)
981 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
982 }
983
984 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +0000985 }
Chris Lattner68061312009-01-24 21:53:27 +0000986 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000987
Ken Dyckcc56c542011-01-15 18:38:59 +0000988 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +0000989}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000990
John McCall87fe5d52010-05-20 01:18:31 +0000991std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000992ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000993 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +0000994 return std::make_pair(toCharUnitsFromBits(Info.first),
995 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +0000996}
997
998std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000999ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001000 return getTypeInfoInChars(T.getTypePtr());
1001}
1002
Daniel Dunbarc6475872012-03-09 04:12:54 +00001003std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1004 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1005 if (it != MemoizedTypeInfo.end())
1006 return it->second;
1007
1008 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1009 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1010 return Info;
1011}
1012
1013/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1014/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001015///
1016/// FIXME: Pointers into different addr spaces could have different sizes and
1017/// alignment requirements: getPointerInfo should take an AddrSpace, this
1018/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +00001019std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +00001020ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +00001021 uint64_t Width=0;
1022 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001023 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001024#define TYPE(Class, Base)
1025#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001026#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001027#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1028#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001029 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001030
Chris Lattner355332d2007-07-13 22:27:08 +00001031 case Type::FunctionNoProto:
1032 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001033 // GCC extension: alignof(function) = 32 bits
1034 Width = 0;
1035 Align = 32;
1036 break;
1037
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001038 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001039 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001040 Width = 0;
1041 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1042 break;
1043
Steve Naroff5c131802007-08-30 01:06:46 +00001044 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001045 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001046
Chris Lattner37e05872008-03-05 18:54:05 +00001047 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001048 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +00001049 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1050 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001051 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001052 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +00001053 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001054 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001055 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001056 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001057 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001058 const VectorType *VT = cast<VectorType>(T);
1059 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1060 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001061 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001062 // If the alignment is not a power of 2, round up to the next power of 2.
1063 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001064 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001065 Align = llvm::NextPowerOf2(Align);
1066 Width = llvm::RoundUpToAlignment(Width, Align);
1067 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001068 // Adjust the alignment based on the target max.
1069 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1070 if (TargetVectorAlign && TargetVectorAlign < Align)
1071 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001072 break;
1073 }
Chris Lattner647fb222007-07-18 18:26:58 +00001074
Chris Lattner7570e9c2008-03-08 08:52:55 +00001075 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001076 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001077 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001078 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001079 // GCC extension: alignof(void) = 8 bits.
1080 Width = 0;
1081 Align = 8;
1082 break;
1083
Chris Lattner6a4f7452007-12-19 19:23:28 +00001084 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001085 Width = Target->getBoolWidth();
1086 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001087 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001088 case BuiltinType::Char_S:
1089 case BuiltinType::Char_U:
1090 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001091 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001092 Width = Target->getCharWidth();
1093 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001094 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001095 case BuiltinType::WChar_S:
1096 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001097 Width = Target->getWCharWidth();
1098 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001099 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001100 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001101 Width = Target->getChar16Width();
1102 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001103 break;
1104 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001105 Width = Target->getChar32Width();
1106 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001107 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001108 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001109 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001110 Width = Target->getShortWidth();
1111 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001112 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001113 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001114 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001115 Width = Target->getIntWidth();
1116 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001117 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001118 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001119 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001120 Width = Target->getLongWidth();
1121 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001122 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001123 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001124 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001125 Width = Target->getLongLongWidth();
1126 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001127 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001128 case BuiltinType::Int128:
1129 case BuiltinType::UInt128:
1130 Width = 128;
1131 Align = 128; // int128_t is 128-bit aligned on all targets.
1132 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001133 case BuiltinType::Half:
1134 Width = Target->getHalfWidth();
1135 Align = Target->getHalfAlign();
1136 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001137 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001138 Width = Target->getFloatWidth();
1139 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001140 break;
1141 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001142 Width = Target->getDoubleWidth();
1143 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001144 break;
1145 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001146 Width = Target->getLongDoubleWidth();
1147 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001148 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001149 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001150 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1151 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001152 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001153 case BuiltinType::ObjCId:
1154 case BuiltinType::ObjCClass:
1155 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001156 Width = Target->getPointerWidth(0);
1157 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001158 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001159 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001160 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001161 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001162 Width = Target->getPointerWidth(0);
1163 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001164 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001165 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001166 unsigned AS = getTargetAddressSpace(
1167 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001168 Width = Target->getPointerWidth(AS);
1169 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001170 break;
1171 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001172 case Type::LValueReference:
1173 case Type::RValueReference: {
1174 // alignof and sizeof should never enter this code path here, so we go
1175 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001176 unsigned AS = getTargetAddressSpace(
1177 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001178 Width = Target->getPointerWidth(AS);
1179 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001180 break;
1181 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001182 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001183 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001184 Width = Target->getPointerWidth(AS);
1185 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001186 break;
1187 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001188 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001189 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001190 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +00001191 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +00001192 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001193 Align = PtrDiffInfo.second;
1194 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001195 }
Chris Lattner647fb222007-07-18 18:26:58 +00001196 case Type::Complex: {
1197 // Complex types have the same alignment as their elements, but twice the
1198 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001199 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001200 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001201 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001202 Align = EltInfo.second;
1203 break;
1204 }
John McCall8b07ec22010-05-15 11:32:37 +00001205 case Type::ObjCObject:
1206 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001207 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001208 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001209 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001210 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001211 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001212 break;
1213 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001214 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001215 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001216 const TagType *TT = cast<TagType>(T);
1217
1218 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001219 Width = 8;
1220 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001221 break;
1222 }
Mike Stump11289f42009-09-09 15:08:12 +00001223
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001224 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001225 return getTypeInfo(ET->getDecl()->getIntegerType());
1226
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001227 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001228 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001229 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001230 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001231 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001232 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001233
Chris Lattner63d2b362009-10-22 05:17:15 +00001234 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001235 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1236 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001237
Richard Smith30482bc2011-02-20 03:19:35 +00001238 case Type::Auto: {
1239 const AutoType *A = cast<AutoType>(T);
1240 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001241 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001242 }
1243
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001244 case Type::Paren:
1245 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1246
Douglas Gregoref462e62009-04-30 17:32:17 +00001247 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001248 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001249 std::pair<uint64_t, unsigned> Info
1250 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001251 // If the typedef has an aligned attribute on it, it overrides any computed
1252 // alignment we have. This violates the GCC documentation (which says that
1253 // attribute(aligned) can only round up) but matches its implementation.
1254 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1255 Align = AttrAlign;
1256 else
1257 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001258 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001259 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001260 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001261
1262 case Type::TypeOfExpr:
1263 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1264 .getTypePtr());
1265
1266 case Type::TypeOf:
1267 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1268
Anders Carlsson81df7b82009-06-24 19:06:50 +00001269 case Type::Decltype:
1270 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1271 .getTypePtr());
1272
Alexis Hunte852b102011-05-24 22:41:36 +00001273 case Type::UnaryTransform:
1274 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1275
Abramo Bagnara6150c882010-05-11 21:36:43 +00001276 case Type::Elaborated:
1277 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001278
John McCall81904512011-01-06 01:58:22 +00001279 case Type::Attributed:
1280 return getTypeInfo(
1281 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1282
Richard Smith3f1b5d02011-05-05 21:57:07 +00001283 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001284 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001285 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001286 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1287 // A type alias template specialization may refer to a typedef with the
1288 // aligned attribute on it.
1289 if (TST->isTypeAlias())
1290 return getTypeInfo(TST->getAliasedType().getTypePtr());
1291 else
1292 return getTypeInfo(getCanonicalType(T));
1293 }
1294
Eli Friedman0dfb8892011-10-06 23:00:33 +00001295 case Type::Atomic: {
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001296 std::pair<uint64_t, unsigned> Info
1297 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1298 Width = Info.first;
1299 Align = Info.second;
1300 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1301 llvm::isPowerOf2_64(Width)) {
1302 // We can potentially perform lock-free atomic operations for this
1303 // type; promote the alignment appropriately.
1304 // FIXME: We could potentially promote the width here as well...
1305 // is that worthwhile? (Non-struct atomic types generally have
1306 // power-of-two size anyway, but structs might not. Requires a bit
1307 // of implementation work to make sure we zero out the extra bits.)
1308 Align = static_cast<unsigned>(Width);
1309 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001310 }
1311
Douglas Gregoref462e62009-04-30 17:32:17 +00001312 }
Mike Stump11289f42009-09-09 15:08:12 +00001313
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001314 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001315 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001316}
1317
Ken Dyckcc56c542011-01-15 18:38:59 +00001318/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1319CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1320 return CharUnits::fromQuantity(BitSize / getCharWidth());
1321}
1322
Ken Dyckb0fcc592011-02-11 01:54:29 +00001323/// toBits - Convert a size in characters to a size in characters.
1324int64_t ASTContext::toBits(CharUnits CharSize) const {
1325 return CharSize.getQuantity() * getCharWidth();
1326}
1327
Ken Dyck8c89d592009-12-22 14:23:30 +00001328/// getTypeSizeInChars - Return the size of the specified type, in characters.
1329/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001330CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001331 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001332}
Jay Foad39c79802011-01-12 09:06:06 +00001333CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001334 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001335}
1336
Ken Dycka6046ab2010-01-26 17:25:18 +00001337/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001338/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001339CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001340 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001341}
Jay Foad39c79802011-01-12 09:06:06 +00001342CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001343 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001344}
1345
Chris Lattnera3402cd2009-01-27 18:08:34 +00001346/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1347/// type for the current target in bits. This can be different than the ABI
1348/// alignment in cases where it is beneficial for performance to overalign
1349/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001350unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001351 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001352
1353 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001354 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001355 T = CT->getElementType().getTypePtr();
1356 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001357 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1358 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001359 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1360
Chris Lattnera3402cd2009-01-27 18:08:34 +00001361 return ABIAlign;
1362}
1363
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001364/// DeepCollectObjCIvars -
1365/// This routine first collects all declared, but not synthesized, ivars in
1366/// super class and then collects all ivars, including those synthesized for
1367/// current class. This routine is used for implementation of current class
1368/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001369///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001370void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1371 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001372 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001373 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1374 DeepCollectObjCIvars(SuperClass, false, Ivars);
1375 if (!leafClass) {
1376 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1377 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001378 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001379 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001380 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001381 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001382 Iv= Iv->getNextIvar())
1383 Ivars.push_back(Iv);
1384 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001385}
1386
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001387/// CollectInheritedProtocols - Collect all protocols in current class and
1388/// those inherited by it.
1389void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001390 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001391 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001392 // We can use protocol_iterator here instead of
1393 // all_referenced_protocol_iterator since we are walking all categories.
1394 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1395 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001396 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001397 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001398 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001399 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001400 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001401 CollectInheritedProtocols(*P, Protocols);
1402 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001403 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001404
1405 // Categories of this Interface.
1406 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1407 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1408 CollectInheritedProtocols(CDeclChain, Protocols);
1409 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1410 while (SD) {
1411 CollectInheritedProtocols(SD, Protocols);
1412 SD = SD->getSuperClass();
1413 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001414 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001415 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001416 PE = OC->protocol_end(); P != PE; ++P) {
1417 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001418 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001419 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1420 PE = Proto->protocol_end(); P != PE; ++P)
1421 CollectInheritedProtocols(*P, Protocols);
1422 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001423 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001424 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1425 PE = OP->protocol_end(); P != PE; ++P) {
1426 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001427 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001428 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1429 PE = Proto->protocol_end(); P != PE; ++P)
1430 CollectInheritedProtocols(*P, Protocols);
1431 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001432 }
1433}
1434
Jay Foad39c79802011-01-12 09:06:06 +00001435unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001436 unsigned count = 0;
1437 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001438 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1439 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001440 count += CDecl->ivar_size();
1441
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001442 // Count ivar defined in this class's implementation. This
1443 // includes synthesized ivars.
1444 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001445 count += ImplDecl->ivar_size();
1446
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001447 return count;
1448}
1449
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001450bool ASTContext::isSentinelNullExpr(const Expr *E) {
1451 if (!E)
1452 return false;
1453
1454 // nullptr_t is always treated as null.
1455 if (E->getType()->isNullPtrType()) return true;
1456
1457 if (E->getType()->isAnyPointerType() &&
1458 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1459 Expr::NPC_ValueDependentIsNull))
1460 return true;
1461
1462 // Unfortunately, __null has type 'int'.
1463 if (isa<GNUNullExpr>(E)) return true;
1464
1465 return false;
1466}
1467
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001468/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1469ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1470 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1471 I = ObjCImpls.find(D);
1472 if (I != ObjCImpls.end())
1473 return cast<ObjCImplementationDecl>(I->second);
1474 return 0;
1475}
1476/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1477ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1478 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1479 I = ObjCImpls.find(D);
1480 if (I != ObjCImpls.end())
1481 return cast<ObjCCategoryImplDecl>(I->second);
1482 return 0;
1483}
1484
1485/// \brief Set the implementation of ObjCInterfaceDecl.
1486void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1487 ObjCImplementationDecl *ImplD) {
1488 assert(IFaceD && ImplD && "Passed null params");
1489 ObjCImpls[IFaceD] = ImplD;
1490}
1491/// \brief Set the implementation of ObjCCategoryDecl.
1492void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1493 ObjCCategoryImplDecl *ImplD) {
1494 assert(CatD && ImplD && "Passed null params");
1495 ObjCImpls[CatD] = ImplD;
1496}
1497
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001498ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1499 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1500 return ID;
1501 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1502 return CD->getClassInterface();
1503 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1504 return IMD->getClassInterface();
1505
1506 return 0;
1507}
1508
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001509/// \brief Get the copy initialization expression of VarDecl,or NULL if
1510/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001511Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001512 assert(VD && "Passed null params");
1513 assert(VD->hasAttr<BlocksAttr>() &&
1514 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001515 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001516 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001517 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1518}
1519
1520/// \brief Set the copy inialization expression of a block var decl.
1521void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1522 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001523 assert(VD->hasAttr<BlocksAttr>() &&
1524 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001525 BlockVarCopyInits[VD] = Init;
1526}
1527
John McCallbcd03502009-12-07 02:54:59 +00001528TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001529 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001530 if (!DataSize)
1531 DataSize = TypeLoc::getFullDataSizeForType(T);
1532 else
1533 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001534 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001535
John McCallbcd03502009-12-07 02:54:59 +00001536 TypeSourceInfo *TInfo =
1537 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1538 new (TInfo) TypeSourceInfo(T);
1539 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001540}
1541
John McCallbcd03502009-12-07 02:54:59 +00001542TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001543 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001544 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001545 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001546 return DI;
1547}
1548
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001549const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001550ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001551 return getObjCLayout(D, 0);
1552}
1553
1554const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001555ASTContext::getASTObjCImplementationLayout(
1556 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001557 return getObjCLayout(D->getClassInterface(), D);
1558}
1559
Chris Lattner983a8bb2007-07-13 22:13:22 +00001560//===----------------------------------------------------------------------===//
1561// Type creation/memoization methods
1562//===----------------------------------------------------------------------===//
1563
Jay Foad39c79802011-01-12 09:06:06 +00001564QualType
John McCall33ddac02011-01-19 10:06:00 +00001565ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1566 unsigned fastQuals = quals.getFastQualifiers();
1567 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001568
1569 // Check if we've already instantiated this type.
1570 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001571 ExtQuals::Profile(ID, baseType, quals);
1572 void *insertPos = 0;
1573 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1574 assert(eq->getQualifiers() == quals);
1575 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001576 }
1577
John McCall33ddac02011-01-19 10:06:00 +00001578 // If the base type is not canonical, make the appropriate canonical type.
1579 QualType canon;
1580 if (!baseType->isCanonicalUnqualified()) {
1581 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00001582 canonSplit.Quals.addConsistentQualifiers(quals);
1583 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001584
1585 // Re-find the insert position.
1586 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1587 }
1588
1589 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1590 ExtQualNodes.InsertNode(eq, insertPos);
1591 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001592}
1593
Jay Foad39c79802011-01-12 09:06:06 +00001594QualType
1595ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001596 QualType CanT = getCanonicalType(T);
1597 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001598 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001599
John McCall8ccfcb52009-09-24 19:53:00 +00001600 // If we are composing extended qualifiers together, merge together
1601 // into one ExtQuals node.
1602 QualifierCollector Quals;
1603 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001604
John McCall8ccfcb52009-09-24 19:53:00 +00001605 // If this type already has an address space specified, it cannot get
1606 // another one.
1607 assert(!Quals.hasAddressSpace() &&
1608 "Type cannot be in multiple addr spaces!");
1609 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001610
John McCall8ccfcb52009-09-24 19:53:00 +00001611 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001612}
1613
Chris Lattnerd60183d2009-02-18 22:53:11 +00001614QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001615 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001616 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001617 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001618 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001619
John McCall53fa7142010-12-24 02:08:15 +00001620 if (const PointerType *ptr = T->getAs<PointerType>()) {
1621 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001622 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001623 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1624 return getPointerType(ResultType);
1625 }
1626 }
Mike Stump11289f42009-09-09 15:08:12 +00001627
John McCall8ccfcb52009-09-24 19:53:00 +00001628 // If we are composing extended qualifiers together, merge together
1629 // into one ExtQuals node.
1630 QualifierCollector Quals;
1631 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001632
John McCall8ccfcb52009-09-24 19:53:00 +00001633 // If this type already has an ObjCGC specified, it cannot get
1634 // another one.
1635 assert(!Quals.hasObjCGCAttr() &&
1636 "Type cannot have multiple ObjCGCs!");
1637 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001638
John McCall8ccfcb52009-09-24 19:53:00 +00001639 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001640}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001641
John McCall4f5019e2010-12-19 02:44:49 +00001642const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1643 FunctionType::ExtInfo Info) {
1644 if (T->getExtInfo() == Info)
1645 return T;
1646
1647 QualType Result;
1648 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1649 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1650 } else {
1651 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1652 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1653 EPI.ExtInfo = Info;
1654 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1655 FPT->getNumArgs(), EPI);
1656 }
1657
1658 return cast<FunctionType>(Result.getTypePtr());
1659}
1660
Chris Lattnerc6395932007-06-22 20:56:16 +00001661/// getComplexType - Return the uniqued reference to the type for a complex
1662/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001663QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001664 // Unique pointers, to guarantee there is only one pointer of a particular
1665 // structure.
1666 llvm::FoldingSetNodeID ID;
1667 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001668
Chris Lattnerc6395932007-06-22 20:56:16 +00001669 void *InsertPos = 0;
1670 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1671 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001672
Chris Lattnerc6395932007-06-22 20:56:16 +00001673 // If the pointee type isn't canonical, this won't be a canonical type either,
1674 // so fill in the canonical type field.
1675 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001676 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001677 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001678
Chris Lattnerc6395932007-06-22 20:56:16 +00001679 // Get the new insert position for the node we care about.
1680 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001681 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001682 }
John McCall90d1c2d2009-09-24 23:30:46 +00001683 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001684 Types.push_back(New);
1685 ComplexTypes.InsertNode(New, InsertPos);
1686 return QualType(New, 0);
1687}
1688
Chris Lattner970e54e2006-11-12 00:37:36 +00001689/// getPointerType - Return the uniqued reference to the type for a pointer to
1690/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001691QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001692 // Unique pointers, to guarantee there is only one pointer of a particular
1693 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001694 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001695 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001696
Chris Lattner67521df2007-01-27 01:29:36 +00001697 void *InsertPos = 0;
1698 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001699 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001700
Chris Lattner7ccecb92006-11-12 08:50:50 +00001701 // If the pointee type isn't canonical, this won't be a canonical type either,
1702 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001703 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001704 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001705 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001706
Chris Lattner67521df2007-01-27 01:29:36 +00001707 // Get the new insert position for the node we care about.
1708 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001709 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001710 }
John McCall90d1c2d2009-09-24 23:30:46 +00001711 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001712 Types.push_back(New);
1713 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001714 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001715}
1716
Mike Stump11289f42009-09-09 15:08:12 +00001717/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001718/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001719QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001720 assert(T->isFunctionType() && "block of function types only");
1721 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001722 // structure.
1723 llvm::FoldingSetNodeID ID;
1724 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001725
Steve Naroffec33ed92008-08-27 16:04:49 +00001726 void *InsertPos = 0;
1727 if (BlockPointerType *PT =
1728 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1729 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001730
1731 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001732 // type either so fill in the canonical type field.
1733 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001734 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001735 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001736
Steve Naroffec33ed92008-08-27 16:04:49 +00001737 // Get the new insert position for the node we care about.
1738 BlockPointerType *NewIP =
1739 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001740 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001741 }
John McCall90d1c2d2009-09-24 23:30:46 +00001742 BlockPointerType *New
1743 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001744 Types.push_back(New);
1745 BlockPointerTypes.InsertNode(New, InsertPos);
1746 return QualType(New, 0);
1747}
1748
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001749/// getLValueReferenceType - Return the uniqued reference to the type for an
1750/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001751QualType
1752ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00001753 assert(getCanonicalType(T) != OverloadTy &&
1754 "Unresolved overloaded function type");
1755
Bill Wendling3708c182007-05-27 10:15:43 +00001756 // Unique pointers, to guarantee there is only one pointer of a particular
1757 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001758 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001759 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001760
1761 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001762 if (LValueReferenceType *RT =
1763 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001764 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001765
John McCallfc93cf92009-10-22 22:37:11 +00001766 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1767
Bill Wendling3708c182007-05-27 10:15:43 +00001768 // If the referencee type isn't canonical, this won't be a canonical type
1769 // either, so fill in the canonical type field.
1770 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001771 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1772 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1773 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001774
Bill Wendling3708c182007-05-27 10:15:43 +00001775 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001776 LValueReferenceType *NewIP =
1777 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001778 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001779 }
1780
John McCall90d1c2d2009-09-24 23:30:46 +00001781 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001782 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1783 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001784 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001785 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001786
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001787 return QualType(New, 0);
1788}
1789
1790/// getRValueReferenceType - Return the uniqued reference to the type for an
1791/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001792QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001793 // Unique pointers, to guarantee there is only one pointer of a particular
1794 // structure.
1795 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001796 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001797
1798 void *InsertPos = 0;
1799 if (RValueReferenceType *RT =
1800 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1801 return QualType(RT, 0);
1802
John McCallfc93cf92009-10-22 22:37:11 +00001803 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1804
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001805 // If the referencee type isn't canonical, this won't be a canonical type
1806 // either, so fill in the canonical type field.
1807 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001808 if (InnerRef || !T.isCanonical()) {
1809 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1810 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001811
1812 // Get the new insert position for the node we care about.
1813 RValueReferenceType *NewIP =
1814 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001815 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001816 }
1817
John McCall90d1c2d2009-09-24 23:30:46 +00001818 RValueReferenceType *New
1819 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001820 Types.push_back(New);
1821 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001822 return QualType(New, 0);
1823}
1824
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001825/// getMemberPointerType - Return the uniqued reference to the type for a
1826/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001827QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001828 // Unique pointers, to guarantee there is only one pointer of a particular
1829 // structure.
1830 llvm::FoldingSetNodeID ID;
1831 MemberPointerType::Profile(ID, T, Cls);
1832
1833 void *InsertPos = 0;
1834 if (MemberPointerType *PT =
1835 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1836 return QualType(PT, 0);
1837
1838 // If the pointee or class type isn't canonical, this won't be a canonical
1839 // type either, so fill in the canonical type field.
1840 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001841 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001842 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1843
1844 // Get the new insert position for the node we care about.
1845 MemberPointerType *NewIP =
1846 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001847 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001848 }
John McCall90d1c2d2009-09-24 23:30:46 +00001849 MemberPointerType *New
1850 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001851 Types.push_back(New);
1852 MemberPointerTypes.InsertNode(New, InsertPos);
1853 return QualType(New, 0);
1854}
1855
Mike Stump11289f42009-09-09 15:08:12 +00001856/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001857/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001858QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001859 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001860 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001861 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001862 assert((EltTy->isDependentType() ||
1863 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001864 "Constant array of VLAs is illegal!");
1865
Chris Lattnere2df3f92009-05-13 04:12:56 +00001866 // Convert the array size into a canonical width matching the pointer size for
1867 // the target.
1868 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001869 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001870 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00001871
Chris Lattner23b7eb62007-06-15 23:05:46 +00001872 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001873 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001874
Chris Lattner36f8e652007-01-27 08:31:04 +00001875 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001876 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001877 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001878 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001879
John McCall33ddac02011-01-19 10:06:00 +00001880 // If the element type isn't canonical or has qualifiers, this won't
1881 // be a canonical type either, so fill in the canonical type field.
1882 QualType Canon;
1883 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1884 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00001885 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001886 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00001887 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001888
Chris Lattner36f8e652007-01-27 08:31:04 +00001889 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001890 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001891 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001892 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001893 }
Mike Stump11289f42009-09-09 15:08:12 +00001894
John McCall90d1c2d2009-09-24 23:30:46 +00001895 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001896 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001897 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001898 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001899 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001900}
1901
John McCall06549462011-01-18 08:40:38 +00001902/// getVariableArrayDecayedType - Turns the given type, which may be
1903/// variably-modified, into the corresponding type with all the known
1904/// sizes replaced with [*].
1905QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1906 // Vastly most common case.
1907 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001908
John McCall06549462011-01-18 08:40:38 +00001909 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001910
John McCall06549462011-01-18 08:40:38 +00001911 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00001912 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00001913 switch (ty->getTypeClass()) {
1914#define TYPE(Class, Base)
1915#define ABSTRACT_TYPE(Class, Base)
1916#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1917#include "clang/AST/TypeNodes.def"
1918 llvm_unreachable("didn't desugar past all non-canonical types?");
1919
1920 // These types should never be variably-modified.
1921 case Type::Builtin:
1922 case Type::Complex:
1923 case Type::Vector:
1924 case Type::ExtVector:
1925 case Type::DependentSizedExtVector:
1926 case Type::ObjCObject:
1927 case Type::ObjCInterface:
1928 case Type::ObjCObjectPointer:
1929 case Type::Record:
1930 case Type::Enum:
1931 case Type::UnresolvedUsing:
1932 case Type::TypeOfExpr:
1933 case Type::TypeOf:
1934 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00001935 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00001936 case Type::DependentName:
1937 case Type::InjectedClassName:
1938 case Type::TemplateSpecialization:
1939 case Type::DependentTemplateSpecialization:
1940 case Type::TemplateTypeParm:
1941 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00001942 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00001943 case Type::PackExpansion:
1944 llvm_unreachable("type should never be variably-modified");
1945
1946 // These types can be variably-modified but should never need to
1947 // further decay.
1948 case Type::FunctionNoProto:
1949 case Type::FunctionProto:
1950 case Type::BlockPointer:
1951 case Type::MemberPointer:
1952 return type;
1953
1954 // These types can be variably-modified. All these modifications
1955 // preserve structure except as noted by comments.
1956 // TODO: if we ever care about optimizing VLAs, there are no-op
1957 // optimizations available here.
1958 case Type::Pointer:
1959 result = getPointerType(getVariableArrayDecayedType(
1960 cast<PointerType>(ty)->getPointeeType()));
1961 break;
1962
1963 case Type::LValueReference: {
1964 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1965 result = getLValueReferenceType(
1966 getVariableArrayDecayedType(lv->getPointeeType()),
1967 lv->isSpelledAsLValue());
1968 break;
1969 }
1970
1971 case Type::RValueReference: {
1972 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1973 result = getRValueReferenceType(
1974 getVariableArrayDecayedType(lv->getPointeeType()));
1975 break;
1976 }
1977
Eli Friedman0dfb8892011-10-06 23:00:33 +00001978 case Type::Atomic: {
1979 const AtomicType *at = cast<AtomicType>(ty);
1980 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1981 break;
1982 }
1983
John McCall06549462011-01-18 08:40:38 +00001984 case Type::ConstantArray: {
1985 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1986 result = getConstantArrayType(
1987 getVariableArrayDecayedType(cat->getElementType()),
1988 cat->getSize(),
1989 cat->getSizeModifier(),
1990 cat->getIndexTypeCVRQualifiers());
1991 break;
1992 }
1993
1994 case Type::DependentSizedArray: {
1995 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1996 result = getDependentSizedArrayType(
1997 getVariableArrayDecayedType(dat->getElementType()),
1998 dat->getSizeExpr(),
1999 dat->getSizeModifier(),
2000 dat->getIndexTypeCVRQualifiers(),
2001 dat->getBracketsRange());
2002 break;
2003 }
2004
2005 // Turn incomplete types into [*] types.
2006 case Type::IncompleteArray: {
2007 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2008 result = getVariableArrayType(
2009 getVariableArrayDecayedType(iat->getElementType()),
2010 /*size*/ 0,
2011 ArrayType::Normal,
2012 iat->getIndexTypeCVRQualifiers(),
2013 SourceRange());
2014 break;
2015 }
2016
2017 // Turn VLA types into [*] types.
2018 case Type::VariableArray: {
2019 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2020 result = getVariableArrayType(
2021 getVariableArrayDecayedType(vat->getElementType()),
2022 /*size*/ 0,
2023 ArrayType::Star,
2024 vat->getIndexTypeCVRQualifiers(),
2025 vat->getBracketsRange());
2026 break;
2027 }
2028 }
2029
2030 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002031 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002032}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002033
Steve Naroffcadebd02007-08-30 18:14:25 +00002034/// getVariableArrayType - Returns a non-unique reference to the type for a
2035/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002036QualType ASTContext::getVariableArrayType(QualType EltTy,
2037 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002038 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002039 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002040 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002041 // Since we don't unique expressions, it isn't possible to unique VLA's
2042 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002043 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002044
John McCall33ddac02011-01-19 10:06:00 +00002045 // Be sure to pull qualifiers off the element type.
2046 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2047 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002048 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002049 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002050 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002051 }
2052
John McCall90d1c2d2009-09-24 23:30:46 +00002053 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002054 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002055
2056 VariableArrayTypes.push_back(New);
2057 Types.push_back(New);
2058 return QualType(New, 0);
2059}
2060
Douglas Gregor4619e432008-12-05 23:32:09 +00002061/// getDependentSizedArrayType - Returns a non-unique reference to
2062/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002063/// type.
John McCall33ddac02011-01-19 10:06:00 +00002064QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2065 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002066 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002067 unsigned elementTypeQuals,
2068 SourceRange brackets) const {
2069 assert((!numElements || numElements->isTypeDependent() ||
2070 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002071 "Size must be type- or value-dependent!");
2072
John McCall33ddac02011-01-19 10:06:00 +00002073 // Dependently-sized array types that do not have a specified number
2074 // of elements will have their sizes deduced from a dependent
2075 // initializer. We do no canonicalization here at all, which is okay
2076 // because they can't be used in most locations.
2077 if (!numElements) {
2078 DependentSizedArrayType *newType
2079 = new (*this, TypeAlignment)
2080 DependentSizedArrayType(*this, elementType, QualType(),
2081 numElements, ASM, elementTypeQuals,
2082 brackets);
2083 Types.push_back(newType);
2084 return QualType(newType, 0);
2085 }
2086
2087 // Otherwise, we actually build a new type every time, but we
2088 // also build a canonical type.
2089
2090 SplitQualType canonElementType = getCanonicalType(elementType).split();
2091
2092 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002093 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002094 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002095 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002096 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002097
John McCall33ddac02011-01-19 10:06:00 +00002098 // Look for an existing type with these properties.
2099 DependentSizedArrayType *canonTy =
2100 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002101
John McCall33ddac02011-01-19 10:06:00 +00002102 // If we don't have one, build one.
2103 if (!canonTy) {
2104 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002105 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002106 QualType(), numElements, ASM, elementTypeQuals,
2107 brackets);
2108 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2109 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002110 }
2111
John McCall33ddac02011-01-19 10:06:00 +00002112 // Apply qualifiers from the element type to the array.
2113 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002114 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002115
John McCall33ddac02011-01-19 10:06:00 +00002116 // If we didn't need extra canonicalization for the element type,
2117 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002118 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002119 return canon;
2120
2121 // Otherwise, we need to build a type which follows the spelling
2122 // of the element type.
2123 DependentSizedArrayType *sugaredType
2124 = new (*this, TypeAlignment)
2125 DependentSizedArrayType(*this, elementType, canon, numElements,
2126 ASM, elementTypeQuals, brackets);
2127 Types.push_back(sugaredType);
2128 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002129}
2130
John McCall33ddac02011-01-19 10:06:00 +00002131QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002132 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002133 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002134 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002135 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002136
John McCall33ddac02011-01-19 10:06:00 +00002137 void *insertPos = 0;
2138 if (IncompleteArrayType *iat =
2139 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2140 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002141
2142 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002143 // either, so fill in the canonical type field. We also have to pull
2144 // qualifiers off the element type.
2145 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002146
John McCall33ddac02011-01-19 10:06:00 +00002147 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2148 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002149 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002150 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002151 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002152
2153 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002154 IncompleteArrayType *existing =
2155 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2156 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002157 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002158
John McCall33ddac02011-01-19 10:06:00 +00002159 IncompleteArrayType *newType = new (*this, TypeAlignment)
2160 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002161
John McCall33ddac02011-01-19 10:06:00 +00002162 IncompleteArrayTypes.InsertNode(newType, insertPos);
2163 Types.push_back(newType);
2164 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002165}
2166
Steve Naroff91fcddb2007-07-18 18:00:27 +00002167/// getVectorType - Return the unique reference to a vector type of
2168/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002169QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002170 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002171 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002172
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002173 // Check if we've already instantiated a vector of this type.
2174 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002175 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002176
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002177 void *InsertPos = 0;
2178 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2179 return QualType(VTP, 0);
2180
2181 // If the element type isn't canonical, this won't be a canonical type either,
2182 // so fill in the canonical type field.
2183 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002184 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002185 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002186
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002187 // Get the new insert position for the node we care about.
2188 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002189 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002190 }
John McCall90d1c2d2009-09-24 23:30:46 +00002191 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002192 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002193 VectorTypes.InsertNode(New, InsertPos);
2194 Types.push_back(New);
2195 return QualType(New, 0);
2196}
2197
Nate Begemance4d7fc2008-04-18 23:10:10 +00002198/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002199/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002200QualType
2201ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002202 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002203
Steve Naroff91fcddb2007-07-18 18:00:27 +00002204 // Check if we've already instantiated a vector of this type.
2205 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002206 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002207 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002208 void *InsertPos = 0;
2209 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2210 return QualType(VTP, 0);
2211
2212 // If the element type isn't canonical, this won't be a canonical type either,
2213 // so fill in the canonical type field.
2214 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002215 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002216 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002217
Steve Naroff91fcddb2007-07-18 18:00:27 +00002218 // Get the new insert position for the node we care about.
2219 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002220 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002221 }
John McCall90d1c2d2009-09-24 23:30:46 +00002222 ExtVectorType *New = new (*this, TypeAlignment)
2223 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002224 VectorTypes.InsertNode(New, InsertPos);
2225 Types.push_back(New);
2226 return QualType(New, 0);
2227}
2228
Jay Foad39c79802011-01-12 09:06:06 +00002229QualType
2230ASTContext::getDependentSizedExtVectorType(QualType vecType,
2231 Expr *SizeExpr,
2232 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002233 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002234 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002235 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002236
Douglas Gregor352169a2009-07-31 03:54:25 +00002237 void *InsertPos = 0;
2238 DependentSizedExtVectorType *Canon
2239 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2240 DependentSizedExtVectorType *New;
2241 if (Canon) {
2242 // We already have a canonical version of this array type; use it as
2243 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002244 New = new (*this, TypeAlignment)
2245 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2246 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002247 } else {
2248 QualType CanonVecTy = getCanonicalType(vecType);
2249 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002250 New = new (*this, TypeAlignment)
2251 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2252 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002253
2254 DependentSizedExtVectorType *CanonCheck
2255 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2256 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2257 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002258 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2259 } else {
2260 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2261 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002262 New = new (*this, TypeAlignment)
2263 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002264 }
2265 }
Mike Stump11289f42009-09-09 15:08:12 +00002266
Douglas Gregor758a8692009-06-17 21:51:59 +00002267 Types.push_back(New);
2268 return QualType(New, 0);
2269}
2270
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002271/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002272///
Jay Foad39c79802011-01-12 09:06:06 +00002273QualType
2274ASTContext::getFunctionNoProtoType(QualType ResultTy,
2275 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002276 const CallingConv DefaultCC = Info.getCC();
2277 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2278 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002279 // Unique functions, to guarantee there is only one function of a particular
2280 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002281 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002282 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002283
Chris Lattner47955de2007-01-27 08:37:20 +00002284 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002285 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002286 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002287 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002288
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002289 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002290 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002291 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002292 Canonical =
2293 getFunctionNoProtoType(getCanonicalType(ResultTy),
2294 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002295
Chris Lattner47955de2007-01-27 08:37:20 +00002296 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002297 FunctionNoProtoType *NewIP =
2298 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002299 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002300 }
Mike Stump11289f42009-09-09 15:08:12 +00002301
Roman Divacky65b88cd2011-03-01 17:40:53 +00002302 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002303 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002304 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002305 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002306 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002307 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002308}
2309
2310/// getFunctionType - Return a normal function type with a typed argument
2311/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002312QualType
2313ASTContext::getFunctionType(QualType ResultTy,
2314 const QualType *ArgArray, unsigned NumArgs,
2315 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002316 // Unique functions, to guarantee there is only one function of a particular
2317 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002318 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002319 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002320
2321 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002322 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002323 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002324 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002325
2326 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002327 bool isCanonical =
2328 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2329 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002330 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002331 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002332 isCanonical = false;
2333
Roman Divacky65b88cd2011-03-01 17:40:53 +00002334 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2335 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2336 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002337
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002338 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002339 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002340 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002341 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002342 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002343 CanonicalArgs.reserve(NumArgs);
2344 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002345 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002346
John McCalldb40c7f2010-12-14 08:05:40 +00002347 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002348 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002349 CanonicalEPI.ExceptionSpecType = EST_None;
2350 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002351 CanonicalEPI.ExtInfo
2352 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2353
Chris Lattner76a00cf2008-04-06 22:59:24 +00002354 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002355 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002356 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002357
Chris Lattnerfd4de792007-01-27 01:15:32 +00002358 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002359 FunctionProtoType *NewIP =
2360 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002361 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002362 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002363
John McCall31168b02011-06-15 23:02:42 +00002364 // FunctionProtoType objects are allocated with extra bytes after
2365 // them for three variable size arrays at the end:
2366 // - parameter types
2367 // - exception types
2368 // - consumed-arguments flags
2369 // Instead of the exception types, there could be a noexcept
2370 // expression.
John McCalldb40c7f2010-12-14 08:05:40 +00002371 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002372 NumArgs * sizeof(QualType);
2373 if (EPI.ExceptionSpecType == EST_Dynamic)
2374 Size += EPI.NumExceptions * sizeof(QualType);
2375 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002376 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002377 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002378 Size += 2 * sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002379 }
John McCall31168b02011-06-15 23:02:42 +00002380 if (EPI.ConsumedArguments)
2381 Size += NumArgs * sizeof(bool);
2382
John McCalldb40c7f2010-12-14 08:05:40 +00002383 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002384 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2385 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002386 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002387 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002388 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002389 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002390}
Chris Lattneref51c202006-11-10 07:17:23 +00002391
John McCalle78aac42010-03-10 03:28:59 +00002392#ifndef NDEBUG
2393static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2394 if (!isa<CXXRecordDecl>(D)) return false;
2395 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2396 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2397 return true;
2398 if (RD->getDescribedClassTemplate() &&
2399 !isa<ClassTemplateSpecializationDecl>(RD))
2400 return true;
2401 return false;
2402}
2403#endif
2404
2405/// getInjectedClassNameType - Return the unique reference to the
2406/// injected class name type for the specified templated declaration.
2407QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002408 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002409 assert(NeedsInjectedClassNameType(Decl));
2410 if (Decl->TypeForDecl) {
2411 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002412 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002413 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2414 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2415 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2416 } else {
John McCall424cec92011-01-19 06:33:43 +00002417 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002418 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002419 Decl->TypeForDecl = newType;
2420 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002421 }
2422 return QualType(Decl->TypeForDecl, 0);
2423}
2424
Douglas Gregor83a586e2008-04-13 21:07:44 +00002425/// getTypeDeclType - Return the unique reference to the type for the
2426/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002427QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002428 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002429 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002430
Richard Smithdda56e42011-04-15 14:24:37 +00002431 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002432 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002433
John McCall96f0b5f2010-03-10 06:48:02 +00002434 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2435 "Template type parameter types are always available.");
2436
John McCall81e38502010-02-16 03:57:14 +00002437 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002438 assert(!Record->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002439 "struct/union has previous declaration");
2440 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002441 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002442 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002443 assert(!Enum->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002444 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002445 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002446 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002447 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002448 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2449 Decl->TypeForDecl = newType;
2450 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002451 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002452 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002453
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002454 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002455}
2456
Chris Lattner32d920b2007-01-26 02:01:53 +00002457/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002458/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002459QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002460ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2461 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002462 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002463
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002464 if (Canonical.isNull())
2465 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002466 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002467 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002468 Decl->TypeForDecl = newType;
2469 Types.push_back(newType);
2470 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002471}
2472
Jay Foad39c79802011-01-12 09:06:06 +00002473QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002474 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2475
Douglas Gregorec9fd132012-01-14 16:38:05 +00002476 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002477 if (PrevDecl->TypeForDecl)
2478 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2479
John McCall424cec92011-01-19 06:33:43 +00002480 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2481 Decl->TypeForDecl = newType;
2482 Types.push_back(newType);
2483 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002484}
2485
Jay Foad39c79802011-01-12 09:06:06 +00002486QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002487 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2488
Douglas Gregorec9fd132012-01-14 16:38:05 +00002489 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002490 if (PrevDecl->TypeForDecl)
2491 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2492
John McCall424cec92011-01-19 06:33:43 +00002493 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2494 Decl->TypeForDecl = newType;
2495 Types.push_back(newType);
2496 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002497}
2498
John McCall81904512011-01-06 01:58:22 +00002499QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2500 QualType modifiedType,
2501 QualType equivalentType) {
2502 llvm::FoldingSetNodeID id;
2503 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2504
2505 void *insertPos = 0;
2506 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2507 if (type) return QualType(type, 0);
2508
2509 QualType canon = getCanonicalType(equivalentType);
2510 type = new (*this, TypeAlignment)
2511 AttributedType(canon, attrKind, modifiedType, equivalentType);
2512
2513 Types.push_back(type);
2514 AttributedTypes.InsertNode(type, insertPos);
2515
2516 return QualType(type, 0);
2517}
2518
2519
John McCallcebee162009-10-18 09:09:24 +00002520/// \brief Retrieve a substitution-result type.
2521QualType
2522ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002523 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002524 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002525 && "replacement types must always be canonical");
2526
2527 llvm::FoldingSetNodeID ID;
2528 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2529 void *InsertPos = 0;
2530 SubstTemplateTypeParmType *SubstParm
2531 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2532
2533 if (!SubstParm) {
2534 SubstParm = new (*this, TypeAlignment)
2535 SubstTemplateTypeParmType(Parm, Replacement);
2536 Types.push_back(SubstParm);
2537 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2538 }
2539
2540 return QualType(SubstParm, 0);
2541}
2542
Douglas Gregorada4b792011-01-14 02:55:32 +00002543/// \brief Retrieve a
2544QualType ASTContext::getSubstTemplateTypeParmPackType(
2545 const TemplateTypeParmType *Parm,
2546 const TemplateArgument &ArgPack) {
2547#ifndef NDEBUG
2548 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2549 PEnd = ArgPack.pack_end();
2550 P != PEnd; ++P) {
2551 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2552 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2553 }
2554#endif
2555
2556 llvm::FoldingSetNodeID ID;
2557 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2558 void *InsertPos = 0;
2559 if (SubstTemplateTypeParmPackType *SubstParm
2560 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2561 return QualType(SubstParm, 0);
2562
2563 QualType Canon;
2564 if (!Parm->isCanonicalUnqualified()) {
2565 Canon = getCanonicalType(QualType(Parm, 0));
2566 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2567 ArgPack);
2568 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2569 }
2570
2571 SubstTemplateTypeParmPackType *SubstParm
2572 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2573 ArgPack);
2574 Types.push_back(SubstParm);
2575 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2576 return QualType(SubstParm, 0);
2577}
2578
Douglas Gregoreff93e02009-02-05 23:33:38 +00002579/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002580/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002581/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002582QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002583 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002584 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002585 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002586 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002587 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002588 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002589 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2590
2591 if (TypeParm)
2592 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002593
Chandler Carruth08836322011-05-01 00:51:33 +00002594 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002595 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002596 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002597
2598 TemplateTypeParmType *TypeCheck
2599 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2600 assert(!TypeCheck && "Template type parameter canonical type broken");
2601 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002602 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002603 TypeParm = new (*this, TypeAlignment)
2604 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002605
2606 Types.push_back(TypeParm);
2607 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2608
2609 return QualType(TypeParm, 0);
2610}
2611
John McCalle78aac42010-03-10 03:28:59 +00002612TypeSourceInfo *
2613ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2614 SourceLocation NameLoc,
2615 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002616 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002617 assert(!Name.getAsDependentTemplateName() &&
2618 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002619 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002620
2621 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2622 TemplateSpecializationTypeLoc TL
2623 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002624 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00002625 TL.setTemplateNameLoc(NameLoc);
2626 TL.setLAngleLoc(Args.getLAngleLoc());
2627 TL.setRAngleLoc(Args.getRAngleLoc());
2628 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2629 TL.setArgLocInfo(i, Args[i].getLocInfo());
2630 return DI;
2631}
2632
Mike Stump11289f42009-09-09 15:08:12 +00002633QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002634ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002635 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002636 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002637 assert(!Template.getAsDependentTemplateName() &&
2638 "No dependent template names here!");
2639
John McCall6b51f282009-11-23 01:53:49 +00002640 unsigned NumArgs = Args.size();
2641
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002642 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002643 ArgVec.reserve(NumArgs);
2644 for (unsigned i = 0; i != NumArgs; ++i)
2645 ArgVec.push_back(Args[i].getArgument());
2646
John McCall2408e322010-04-27 00:57:59 +00002647 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002648 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002649}
2650
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002651#ifndef NDEBUG
2652static bool hasAnyPackExpansions(const TemplateArgument *Args,
2653 unsigned NumArgs) {
2654 for (unsigned I = 0; I != NumArgs; ++I)
2655 if (Args[I].isPackExpansion())
2656 return true;
2657
2658 return true;
2659}
2660#endif
2661
John McCall0ad16662009-10-29 08:12:44 +00002662QualType
2663ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002664 const TemplateArgument *Args,
2665 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002666 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002667 assert(!Template.getAsDependentTemplateName() &&
2668 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002669 // Look through qualified template names.
2670 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2671 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002672
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002673 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00002674 Template.getAsTemplateDecl() &&
2675 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00002676 QualType CanonType;
2677 if (!Underlying.isNull())
2678 CanonType = getCanonicalType(Underlying);
2679 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002680 // We can get here with an alias template when the specialization contains
2681 // a pack expansion that does not match up with a parameter pack.
2682 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2683 "Caller must compute aliased type");
2684 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00002685 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2686 NumArgs);
2687 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002688
Douglas Gregora8e02e72009-07-28 23:00:59 +00002689 // Allocate the (non-canonical) template specialization type, but don't
2690 // try to unique it: these types typically have location information that
2691 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002692 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2693 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002694 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002695 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002696 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002697 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2698 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002699
Douglas Gregor8bf42052009-02-09 18:46:07 +00002700 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002701 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002702}
2703
Mike Stump11289f42009-09-09 15:08:12 +00002704QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002705ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2706 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002707 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002708 assert(!Template.getAsDependentTemplateName() &&
2709 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002710
Douglas Gregore29139c2011-03-03 17:04:51 +00002711 // Look through qualified template names.
2712 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2713 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002714
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002715 // Build the canonical template specialization type.
2716 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002717 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002718 CanonArgs.reserve(NumArgs);
2719 for (unsigned I = 0; I != NumArgs; ++I)
2720 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2721
2722 // Determine whether this canonical template specialization type already
2723 // exists.
2724 llvm::FoldingSetNodeID ID;
2725 TemplateSpecializationType::Profile(ID, CanonTemplate,
2726 CanonArgs.data(), NumArgs, *this);
2727
2728 void *InsertPos = 0;
2729 TemplateSpecializationType *Spec
2730 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2731
2732 if (!Spec) {
2733 // Allocate a new canonical template specialization type.
2734 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2735 sizeof(TemplateArgument) * NumArgs),
2736 TypeAlignment);
2737 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2738 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002739 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002740 Types.push_back(Spec);
2741 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2742 }
2743
2744 assert(Spec->isDependentType() &&
2745 "Non-dependent template-id type must have a canonical type");
2746 return QualType(Spec, 0);
2747}
2748
2749QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002750ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2751 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002752 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002753 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002754 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002755
2756 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002757 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002758 if (T)
2759 return QualType(T, 0);
2760
Douglas Gregorc42075a2010-02-04 18:10:26 +00002761 QualType Canon = NamedType;
2762 if (!Canon.isCanonical()) {
2763 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002764 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2765 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002766 (void)CheckT;
2767 }
2768
Abramo Bagnara6150c882010-05-11 21:36:43 +00002769 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002770 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002771 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002772 return QualType(T, 0);
2773}
2774
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002775QualType
Jay Foad39c79802011-01-12 09:06:06 +00002776ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002777 llvm::FoldingSetNodeID ID;
2778 ParenType::Profile(ID, InnerType);
2779
2780 void *InsertPos = 0;
2781 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2782 if (T)
2783 return QualType(T, 0);
2784
2785 QualType Canon = InnerType;
2786 if (!Canon.isCanonical()) {
2787 Canon = getCanonicalType(InnerType);
2788 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2789 assert(!CheckT && "Paren canonical type broken");
2790 (void)CheckT;
2791 }
2792
2793 T = new (*this) ParenType(InnerType, Canon);
2794 Types.push_back(T);
2795 ParenTypes.InsertNode(T, InsertPos);
2796 return QualType(T, 0);
2797}
2798
Douglas Gregor02085352010-03-31 20:19:30 +00002799QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2800 NestedNameSpecifier *NNS,
2801 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002802 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002803 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2804
2805 if (Canon.isNull()) {
2806 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002807 ElaboratedTypeKeyword CanonKeyword = Keyword;
2808 if (Keyword == ETK_None)
2809 CanonKeyword = ETK_Typename;
2810
2811 if (CanonNNS != NNS || CanonKeyword != Keyword)
2812 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002813 }
2814
2815 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002816 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002817
2818 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002819 DependentNameType *T
2820 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002821 if (T)
2822 return QualType(T, 0);
2823
Douglas Gregor02085352010-03-31 20:19:30 +00002824 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002825 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002826 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002827 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002828}
2829
Mike Stump11289f42009-09-09 15:08:12 +00002830QualType
John McCallc392f372010-06-11 00:33:02 +00002831ASTContext::getDependentTemplateSpecializationType(
2832 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002833 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002834 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002835 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002836 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002837 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00002838 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2839 ArgCopy.push_back(Args[I].getArgument());
2840 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2841 ArgCopy.size(),
2842 ArgCopy.data());
2843}
2844
2845QualType
2846ASTContext::getDependentTemplateSpecializationType(
2847 ElaboratedTypeKeyword Keyword,
2848 NestedNameSpecifier *NNS,
2849 const IdentifierInfo *Name,
2850 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002851 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00002852 assert((!NNS || NNS->isDependent()) &&
2853 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00002854
Douglas Gregorc42075a2010-02-04 18:10:26 +00002855 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002856 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2857 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002858
2859 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002860 DependentTemplateSpecializationType *T
2861 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002862 if (T)
2863 return QualType(T, 0);
2864
John McCallc392f372010-06-11 00:33:02 +00002865 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002866
John McCallc392f372010-06-11 00:33:02 +00002867 ElaboratedTypeKeyword CanonKeyword = Keyword;
2868 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2869
2870 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002871 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00002872 for (unsigned I = 0; I != NumArgs; ++I) {
2873 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2874 if (!CanonArgs[I].structurallyEquals(Args[I]))
2875 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002876 }
2877
John McCallc392f372010-06-11 00:33:02 +00002878 QualType Canon;
2879 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2880 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2881 Name, NumArgs,
2882 CanonArgs.data());
2883
2884 // Find the insert position again.
2885 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2886 }
2887
2888 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2889 sizeof(TemplateArgument) * NumArgs),
2890 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002891 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002892 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002893 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002894 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002895 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002896}
2897
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002898QualType ASTContext::getPackExpansionType(QualType Pattern,
2899 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002900 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002901 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002902
2903 assert(Pattern->containsUnexpandedParameterPack() &&
2904 "Pack expansions must expand one or more parameter packs");
2905 void *InsertPos = 0;
2906 PackExpansionType *T
2907 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2908 if (T)
2909 return QualType(T, 0);
2910
2911 QualType Canon;
2912 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00002913 Canon = getCanonicalType(Pattern);
2914 // The canonical type might not contain an unexpanded parameter pack, if it
2915 // contains an alias template specialization which ignores one of its
2916 // parameters.
2917 if (Canon->containsUnexpandedParameterPack()) {
2918 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002919
Richard Smith68eea502012-07-16 00:20:35 +00002920 // Find the insert position again, in case we inserted an element into
2921 // PackExpansionTypes and invalidated our insert position.
2922 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2923 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00002924 }
2925
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002926 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002927 Types.push_back(T);
2928 PackExpansionTypes.InsertNode(T, InsertPos);
2929 return QualType(T, 0);
2930}
2931
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002932/// CmpProtocolNames - Comparison predicate for sorting protocols
2933/// alphabetically.
2934static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2935 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002936 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002937}
2938
John McCall8b07ec22010-05-15 11:32:37 +00002939static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002940 unsigned NumProtocols) {
2941 if (NumProtocols == 0) return true;
2942
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002943 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
2944 return false;
2945
John McCallfc93cf92009-10-22 22:37:11 +00002946 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002947 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
2948 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00002949 return false;
2950 return true;
2951}
2952
2953static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002954 unsigned &NumProtocols) {
2955 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002956
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002957 // Sort protocols, keyed by name.
2958 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2959
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002960 // Canonicalize.
2961 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
2962 Protocols[I] = Protocols[I]->getCanonicalDecl();
2963
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002964 // Remove duplicates.
2965 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2966 NumProtocols = ProtocolsEnd-Protocols;
2967}
2968
John McCall8b07ec22010-05-15 11:32:37 +00002969QualType ASTContext::getObjCObjectType(QualType BaseType,
2970 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002971 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002972 // If the base type is an interface and there aren't any protocols
2973 // to add, then the interface type will do just fine.
2974 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2975 return BaseType;
2976
2977 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002978 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002979 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002980 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002981 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2982 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002983
John McCall8b07ec22010-05-15 11:32:37 +00002984 // Build the canonical type, which has the canonical base type and
2985 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002986 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002987 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2988 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2989 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002990 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002991 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002992 unsigned UniqueCount = NumProtocols;
2993
John McCallfc93cf92009-10-22 22:37:11 +00002994 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002995 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2996 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002997 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002998 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2999 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003000 }
3001
3002 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003003 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3004 }
3005
3006 unsigned Size = sizeof(ObjCObjectTypeImpl);
3007 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3008 void *Mem = Allocate(Size, TypeAlignment);
3009 ObjCObjectTypeImpl *T =
3010 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3011
3012 Types.push_back(T);
3013 ObjCObjectTypes.InsertNode(T, InsertPos);
3014 return QualType(T, 0);
3015}
3016
3017/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3018/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003019QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003020 llvm::FoldingSetNodeID ID;
3021 ObjCObjectPointerType::Profile(ID, ObjectT);
3022
3023 void *InsertPos = 0;
3024 if (ObjCObjectPointerType *QT =
3025 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3026 return QualType(QT, 0);
3027
3028 // Find the canonical object type.
3029 QualType Canonical;
3030 if (!ObjectT.isCanonical()) {
3031 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3032
3033 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003034 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3035 }
3036
Douglas Gregorf85bee62010-02-08 22:59:26 +00003037 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003038 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3039 ObjCObjectPointerType *QType =
3040 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003041
Steve Narofffb4330f2009-06-17 22:40:22 +00003042 Types.push_back(QType);
3043 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003044 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003045}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003046
Douglas Gregor1c283312010-08-11 12:19:30 +00003047/// getObjCInterfaceType - Return the unique reference to the type for the
3048/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003049QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3050 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003051 if (Decl->TypeForDecl)
3052 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003053
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003054 if (PrevDecl) {
3055 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3056 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3057 return QualType(PrevDecl->TypeForDecl, 0);
3058 }
3059
Douglas Gregor7671e532011-12-16 16:34:57 +00003060 // Prefer the definition, if there is one.
3061 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3062 Decl = Def;
3063
Douglas Gregor1c283312010-08-11 12:19:30 +00003064 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3065 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3066 Decl->TypeForDecl = T;
3067 Types.push_back(T);
3068 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003069}
3070
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003071/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3072/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003073/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003074/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003075/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003076QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003077 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003078 if (tofExpr->isTypeDependent()) {
3079 llvm::FoldingSetNodeID ID;
3080 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003081
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003082 void *InsertPos = 0;
3083 DependentTypeOfExprType *Canon
3084 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3085 if (Canon) {
3086 // We already have a "canonical" version of an identical, dependent
3087 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003088 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003089 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003090 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003091 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003092 Canon
3093 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003094 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3095 toe = Canon;
3096 }
3097 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003098 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003099 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003100 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003101 Types.push_back(toe);
3102 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003103}
3104
Steve Naroffa773cd52007-08-01 18:02:17 +00003105/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3106/// TypeOfType AST's. The only motivation to unique these nodes would be
3107/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003108/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003109/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003110QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003111 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003112 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003113 Types.push_back(tot);
3114 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003115}
3116
Anders Carlssonad6bd352009-06-24 21:24:56 +00003117
Anders Carlsson81df7b82009-06-24 19:06:50 +00003118/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3119/// DecltypeType AST's. The only motivation to unique these nodes would be
3120/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003121/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003122/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003123QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003124 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003125
3126 // C++0x [temp.type]p2:
3127 // If an expression e involves a template parameter, decltype(e) denotes a
3128 // unique dependent type. Two such decltype-specifiers refer to the same
3129 // type only if their expressions are equivalent (14.5.6.1).
3130 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003131 llvm::FoldingSetNodeID ID;
3132 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003133
Douglas Gregora21f6c32009-07-30 23:36:40 +00003134 void *InsertPos = 0;
3135 DependentDecltypeType *Canon
3136 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3137 if (Canon) {
3138 // We already have a "canonical" version of an equivalent, dependent
3139 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003140 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003141 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003142 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003143 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003144 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003145 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3146 dt = Canon;
3147 }
3148 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003149 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3150 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003151 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003152 Types.push_back(dt);
3153 return QualType(dt, 0);
3154}
3155
Alexis Hunte852b102011-05-24 22:41:36 +00003156/// getUnaryTransformationType - We don't unique these, since the memory
3157/// savings are minimal and these are rare.
3158QualType ASTContext::getUnaryTransformType(QualType BaseType,
3159 QualType UnderlyingType,
3160 UnaryTransformType::UTTKind Kind)
3161 const {
3162 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003163 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3164 Kind,
3165 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003166 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003167 Types.push_back(Ty);
3168 return QualType(Ty, 0);
3169}
3170
Richard Smithb2bc2e62011-02-21 20:05:19 +00003171/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003172QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00003173 void *InsertPos = 0;
3174 if (!DeducedType.isNull()) {
3175 // Look in the folding set for an existing type.
3176 llvm::FoldingSetNodeID ID;
3177 AutoType::Profile(ID, DeducedType);
3178 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3179 return QualType(AT, 0);
3180 }
3181
3182 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3183 Types.push_back(AT);
3184 if (InsertPos)
3185 AutoTypes.InsertNode(AT, InsertPos);
3186 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003187}
3188
Eli Friedman0dfb8892011-10-06 23:00:33 +00003189/// getAtomicType - Return the uniqued reference to the atomic type for
3190/// the given value type.
3191QualType ASTContext::getAtomicType(QualType T) const {
3192 // Unique pointers, to guarantee there is only one pointer of a particular
3193 // structure.
3194 llvm::FoldingSetNodeID ID;
3195 AtomicType::Profile(ID, T);
3196
3197 void *InsertPos = 0;
3198 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3199 return QualType(AT, 0);
3200
3201 // If the atomic value type isn't canonical, this won't be a canonical type
3202 // either, so fill in the canonical type field.
3203 QualType Canonical;
3204 if (!T.isCanonical()) {
3205 Canonical = getAtomicType(getCanonicalType(T));
3206
3207 // Get the new insert position for the node we care about.
3208 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3209 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3210 }
3211 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3212 Types.push_back(New);
3213 AtomicTypes.InsertNode(New, InsertPos);
3214 return QualType(New, 0);
3215}
3216
Richard Smith02e85f32011-04-14 22:09:26 +00003217/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3218QualType ASTContext::getAutoDeductType() const {
3219 if (AutoDeductTy.isNull())
3220 AutoDeductTy = getAutoType(QualType());
3221 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3222 return AutoDeductTy;
3223}
3224
3225/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3226QualType ASTContext::getAutoRRefDeductType() const {
3227 if (AutoRRefDeductTy.isNull())
3228 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3229 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3230 return AutoRRefDeductTy;
3231}
3232
Chris Lattnerfb072462007-01-23 05:45:31 +00003233/// getTagDeclType - Return the unique reference to the type for the
3234/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003235QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003236 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003237 // FIXME: What is the design on getTagDeclType when it requires casting
3238 // away const? mutable?
3239 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003240}
3241
Mike Stump11289f42009-09-09 15:08:12 +00003242/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3243/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3244/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003245CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003246 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003247}
Chris Lattnerfb072462007-01-23 05:45:31 +00003248
Hans Wennborg27541db2011-10-27 08:29:09 +00003249/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3250CanQualType ASTContext::getIntMaxType() const {
3251 return getFromTargetType(Target->getIntMaxType());
3252}
3253
3254/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3255CanQualType ASTContext::getUIntMaxType() const {
3256 return getFromTargetType(Target->getUIntMaxType());
3257}
3258
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003259/// getSignedWCharType - Return the type of "signed wchar_t".
3260/// Used when in C++, as a GCC extension.
3261QualType ASTContext::getSignedWCharType() const {
3262 // FIXME: derive from "Target" ?
3263 return WCharTy;
3264}
3265
3266/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3267/// Used when in C++, as a GCC extension.
3268QualType ASTContext::getUnsignedWCharType() const {
3269 // FIXME: derive from "Target" ?
3270 return UnsignedIntTy;
3271}
3272
Hans Wennborg27541db2011-10-27 08:29:09 +00003273/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003274/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3275QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003276 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003277}
3278
Chris Lattnera21ad802008-04-02 05:18:44 +00003279//===----------------------------------------------------------------------===//
3280// Type Operators
3281//===----------------------------------------------------------------------===//
3282
Jay Foad39c79802011-01-12 09:06:06 +00003283CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003284 // Push qualifiers into arrays, and then discard any remaining
3285 // qualifiers.
3286 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003287 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003288 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003289 QualType Result;
3290 if (isa<ArrayType>(Ty)) {
3291 Result = getArrayDecayedType(QualType(Ty,0));
3292 } else if (isa<FunctionType>(Ty)) {
3293 Result = getPointerType(QualType(Ty, 0));
3294 } else {
3295 Result = QualType(Ty, 0);
3296 }
3297
3298 return CanQualType::CreateUnsafe(Result);
3299}
3300
John McCall6c9dd522011-01-18 07:41:22 +00003301QualType ASTContext::getUnqualifiedArrayType(QualType type,
3302 Qualifiers &quals) {
3303 SplitQualType splitType = type.getSplitUnqualifiedType();
3304
3305 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3306 // the unqualified desugared type and then drops it on the floor.
3307 // We then have to strip that sugar back off with
3308 // getUnqualifiedDesugaredType(), which is silly.
3309 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003310 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003311
3312 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003313 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003314 quals = splitType.Quals;
3315 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003316 }
3317
John McCall6c9dd522011-01-18 07:41:22 +00003318 // Otherwise, recurse on the array's element type.
3319 QualType elementType = AT->getElementType();
3320 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3321
3322 // If that didn't change the element type, AT has no qualifiers, so we
3323 // can just use the results in splitType.
3324 if (elementType == unqualElementType) {
3325 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003326 quals = splitType.Quals;
3327 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003328 }
3329
3330 // Otherwise, add in the qualifiers from the outermost type, then
3331 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003332 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003333
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003334 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003335 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003336 CAT->getSizeModifier(), 0);
3337 }
3338
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003339 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003340 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003341 }
3342
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003343 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003344 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003345 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003346 VAT->getSizeModifier(),
3347 VAT->getIndexTypeCVRQualifiers(),
3348 VAT->getBracketsRange());
3349 }
3350
3351 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003352 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003353 DSAT->getSizeModifier(), 0,
3354 SourceRange());
3355}
3356
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003357/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3358/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3359/// they point to and return true. If T1 and T2 aren't pointer types
3360/// or pointer-to-member types, or if they are not similar at this
3361/// level, returns false and leaves T1 and T2 unchanged. Top-level
3362/// qualifiers on T1 and T2 are ignored. This function will typically
3363/// be called in a loop that successively "unwraps" pointer and
3364/// pointer-to-member types to compare them at each level.
3365bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3366 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3367 *T2PtrType = T2->getAs<PointerType>();
3368 if (T1PtrType && T2PtrType) {
3369 T1 = T1PtrType->getPointeeType();
3370 T2 = T2PtrType->getPointeeType();
3371 return true;
3372 }
3373
3374 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3375 *T2MPType = T2->getAs<MemberPointerType>();
3376 if (T1MPType && T2MPType &&
3377 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3378 QualType(T2MPType->getClass(), 0))) {
3379 T1 = T1MPType->getPointeeType();
3380 T2 = T2MPType->getPointeeType();
3381 return true;
3382 }
3383
David Blaikiebbafb8a2012-03-11 07:00:24 +00003384 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003385 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3386 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3387 if (T1OPType && T2OPType) {
3388 T1 = T1OPType->getPointeeType();
3389 T2 = T2OPType->getPointeeType();
3390 return true;
3391 }
3392 }
3393
3394 // FIXME: Block pointers, too?
3395
3396 return false;
3397}
3398
Jay Foad39c79802011-01-12 09:06:06 +00003399DeclarationNameInfo
3400ASTContext::getNameForTemplate(TemplateName Name,
3401 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003402 switch (Name.getKind()) {
3403 case TemplateName::QualifiedTemplate:
3404 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003405 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003406 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3407 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003408
John McCalld9dfe3a2011-06-30 08:33:18 +00003409 case TemplateName::OverloadedTemplate: {
3410 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3411 // DNInfo work in progress: CHECKME: what about DNLoc?
3412 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3413 }
3414
3415 case TemplateName::DependentTemplate: {
3416 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003417 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003418 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003419 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3420 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003421 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003422 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3423 // DNInfo work in progress: FIXME: source locations?
3424 DeclarationNameLoc DNLoc;
3425 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3426 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3427 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003428 }
3429 }
3430
John McCalld9dfe3a2011-06-30 08:33:18 +00003431 case TemplateName::SubstTemplateTemplateParm: {
3432 SubstTemplateTemplateParmStorage *subst
3433 = Name.getAsSubstTemplateTemplateParm();
3434 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3435 NameLoc);
3436 }
3437
3438 case TemplateName::SubstTemplateTemplateParmPack: {
3439 SubstTemplateTemplateParmPackStorage *subst
3440 = Name.getAsSubstTemplateTemplateParmPack();
3441 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3442 NameLoc);
3443 }
3444 }
3445
3446 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003447}
3448
Jay Foad39c79802011-01-12 09:06:06 +00003449TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003450 switch (Name.getKind()) {
3451 case TemplateName::QualifiedTemplate:
3452 case TemplateName::Template: {
3453 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003454 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003455 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003456 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3457
3458 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003459 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003460 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003461
John McCalld9dfe3a2011-06-30 08:33:18 +00003462 case TemplateName::OverloadedTemplate:
3463 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003464
John McCalld9dfe3a2011-06-30 08:33:18 +00003465 case TemplateName::DependentTemplate: {
3466 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3467 assert(DTN && "Non-dependent template names must refer to template decls.");
3468 return DTN->CanonicalTemplateName;
3469 }
3470
3471 case TemplateName::SubstTemplateTemplateParm: {
3472 SubstTemplateTemplateParmStorage *subst
3473 = Name.getAsSubstTemplateTemplateParm();
3474 return getCanonicalTemplateName(subst->getReplacement());
3475 }
3476
3477 case TemplateName::SubstTemplateTemplateParmPack: {
3478 SubstTemplateTemplateParmPackStorage *subst
3479 = Name.getAsSubstTemplateTemplateParmPack();
3480 TemplateTemplateParmDecl *canonParameter
3481 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3482 TemplateArgument canonArgPack
3483 = getCanonicalTemplateArgument(subst->getArgumentPack());
3484 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3485 }
3486 }
3487
3488 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003489}
3490
Douglas Gregoradee3e32009-11-11 23:06:43 +00003491bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3492 X = getCanonicalTemplateName(X);
3493 Y = getCanonicalTemplateName(Y);
3494 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3495}
3496
Mike Stump11289f42009-09-09 15:08:12 +00003497TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003498ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003499 switch (Arg.getKind()) {
3500 case TemplateArgument::Null:
3501 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003502
Douglas Gregora8e02e72009-07-28 23:00:59 +00003503 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003504 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003505
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003506 case TemplateArgument::Declaration: {
3507 if (Decl *D = Arg.getAsDecl())
3508 return TemplateArgument(D->getCanonicalDecl());
3509 return TemplateArgument((Decl*)0);
3510 }
Mike Stump11289f42009-09-09 15:08:12 +00003511
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003512 case TemplateArgument::Template:
3513 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003514
3515 case TemplateArgument::TemplateExpansion:
3516 return TemplateArgument(getCanonicalTemplateName(
3517 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003518 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003519
Douglas Gregora8e02e72009-07-28 23:00:59 +00003520 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00003521 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003522
Douglas Gregora8e02e72009-07-28 23:00:59 +00003523 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003524 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003525
Douglas Gregora8e02e72009-07-28 23:00:59 +00003526 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003527 if (Arg.pack_size() == 0)
3528 return Arg;
3529
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003530 TemplateArgument *CanonArgs
3531 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003532 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003533 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003534 AEnd = Arg.pack_end();
3535 A != AEnd; (void)++A, ++Idx)
3536 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003537
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003538 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003539 }
3540 }
3541
3542 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003543 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003544}
3545
Douglas Gregor333489b2009-03-27 23:10:48 +00003546NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003547ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003548 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003549 return 0;
3550
3551 switch (NNS->getKind()) {
3552 case NestedNameSpecifier::Identifier:
3553 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003554 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003555 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3556 NNS->getAsIdentifier());
3557
3558 case NestedNameSpecifier::Namespace:
3559 // A namespace is canonical; build a nested-name-specifier with
3560 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003561 return NestedNameSpecifier::Create(*this, 0,
3562 NNS->getAsNamespace()->getOriginalNamespace());
3563
3564 case NestedNameSpecifier::NamespaceAlias:
3565 // A namespace is canonical; build a nested-name-specifier with
3566 // this namespace and no prefix.
3567 return NestedNameSpecifier::Create(*this, 0,
3568 NNS->getAsNamespaceAlias()->getNamespace()
3569 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003570
3571 case NestedNameSpecifier::TypeSpec:
3572 case NestedNameSpecifier::TypeSpecWithTemplate: {
3573 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003574
3575 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3576 // break it apart into its prefix and identifier, then reconsititute those
3577 // as the canonical nested-name-specifier. This is required to canonicalize
3578 // a dependent nested-name-specifier involving typedefs of dependent-name
3579 // types, e.g.,
3580 // typedef typename T::type T1;
3581 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00003582 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3583 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00003584 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003585
Eli Friedman5358a0a2012-03-03 04:09:56 +00003586 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3587 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3588 // first place?
John McCall33ddac02011-01-19 10:06:00 +00003589 return NestedNameSpecifier::Create(*this, 0, false,
3590 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003591 }
3592
3593 case NestedNameSpecifier::Global:
3594 // The global specifier is canonical and unique.
3595 return NNS;
3596 }
3597
David Blaikie8a40f702012-01-17 06:56:22 +00003598 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00003599}
3600
Chris Lattner7adf0762008-08-04 07:31:14 +00003601
Jay Foad39c79802011-01-12 09:06:06 +00003602const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003603 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003604 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003605 // Handle the common positive case fast.
3606 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3607 return AT;
3608 }
Mike Stump11289f42009-09-09 15:08:12 +00003609
John McCall8ccfcb52009-09-24 19:53:00 +00003610 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003611 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003612 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003613
John McCall8ccfcb52009-09-24 19:53:00 +00003614 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003615 // implements C99 6.7.3p8: "If the specification of an array type includes
3616 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003617
Chris Lattner7adf0762008-08-04 07:31:14 +00003618 // If we get here, we either have type qualifiers on the type, or we have
3619 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003620 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003621
John McCall33ddac02011-01-19 10:06:00 +00003622 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003623 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00003624
Chris Lattner7adf0762008-08-04 07:31:14 +00003625 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00003626 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00003627 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003628 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003629
Chris Lattner7adf0762008-08-04 07:31:14 +00003630 // Otherwise, we have an array and we have qualifiers on it. Push the
3631 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003632 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003633
Chris Lattner7adf0762008-08-04 07:31:14 +00003634 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3635 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3636 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003637 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003638 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3639 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3640 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003641 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003642
Mike Stump11289f42009-09-09 15:08:12 +00003643 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003644 = dyn_cast<DependentSizedArrayType>(ATy))
3645 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003646 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003647 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003648 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003649 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003650 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003651
Chris Lattner7adf0762008-08-04 07:31:14 +00003652 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003653 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003654 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003655 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003656 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003657 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003658}
3659
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003660QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003661 // C99 6.7.5.3p7:
3662 // A declaration of a parameter as "array of type" shall be
3663 // adjusted to "qualified pointer to type", where the type
3664 // qualifiers (if any) are those specified within the [ and ] of
3665 // the array type derivation.
3666 if (T->isArrayType())
3667 return getArrayDecayedType(T);
3668
3669 // C99 6.7.5.3p8:
3670 // A declaration of a parameter as "function returning type"
3671 // shall be adjusted to "pointer to function returning type", as
3672 // in 6.3.2.1.
3673 if (T->isFunctionType())
3674 return getPointerType(T);
3675
3676 return T;
3677}
3678
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003679QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003680 T = getVariableArrayDecayedType(T);
3681 T = getAdjustedParameterType(T);
3682 return T.getUnqualifiedType();
3683}
3684
Chris Lattnera21ad802008-04-02 05:18:44 +00003685/// getArrayDecayedType - Return the properly qualified result of decaying the
3686/// specified array type to a pointer. This operation is non-trivial when
3687/// handling typedefs etc. The canonical type of "T" must be an array type,
3688/// this returns a pointer to a properly qualified element of the array.
3689///
3690/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003691QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003692 // Get the element type with 'getAsArrayType' so that we don't lose any
3693 // typedefs in the element type of the array. This also handles propagation
3694 // of type qualifiers from the array type into the element type if present
3695 // (C99 6.7.3p8).
3696 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3697 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003698
Chris Lattner7adf0762008-08-04 07:31:14 +00003699 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003700
3701 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003702 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003703}
3704
John McCall33ddac02011-01-19 10:06:00 +00003705QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3706 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003707}
3708
John McCall33ddac02011-01-19 10:06:00 +00003709QualType ASTContext::getBaseElementType(QualType type) const {
3710 Qualifiers qs;
3711 while (true) {
3712 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003713 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00003714 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003715
John McCall33ddac02011-01-19 10:06:00 +00003716 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00003717 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003718 }
Mike Stump11289f42009-09-09 15:08:12 +00003719
John McCall33ddac02011-01-19 10:06:00 +00003720 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003721}
3722
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003723/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003724uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003725ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3726 uint64_t ElementCount = 1;
3727 do {
3728 ElementCount *= CA->getSize().getZExtValue();
3729 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3730 } while (CA);
3731 return ElementCount;
3732}
3733
Steve Naroff0af91202007-04-27 21:51:21 +00003734/// getFloatingRank - Return a relative rank for floating point types.
3735/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003736static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003737 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003738 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003739
John McCall9dd450b2009-09-21 23:43:11 +00003740 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3741 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003742 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003743 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00003744 case BuiltinType::Float: return FloatRank;
3745 case BuiltinType::Double: return DoubleRank;
3746 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003747 }
3748}
3749
Mike Stump11289f42009-09-09 15:08:12 +00003750/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3751/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003752/// 'typeDomain' is a real floating point or complex type.
3753/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003754QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3755 QualType Domain) const {
3756 FloatingRank EltRank = getFloatingRank(Size);
3757 if (Domain->isComplexType()) {
3758 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003759 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00003760 case FloatRank: return FloatComplexTy;
3761 case DoubleRank: return DoubleComplexTy;
3762 case LongDoubleRank: return LongDoubleComplexTy;
3763 }
Steve Naroff0af91202007-04-27 21:51:21 +00003764 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003765
3766 assert(Domain->isRealFloatingType() && "Unknown domain!");
3767 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003768 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003769 case FloatRank: return FloatTy;
3770 case DoubleRank: return DoubleTy;
3771 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003772 }
David Blaikief47fa302012-01-17 02:30:50 +00003773 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00003774}
3775
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003776/// getFloatingTypeOrder - Compare the rank of the two specified floating
3777/// point types, ignoring the domain of the type (i.e. 'double' ==
3778/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003779/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003780int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003781 FloatingRank LHSR = getFloatingRank(LHS);
3782 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003783
Chris Lattnerb90739d2008-04-06 23:38:49 +00003784 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003785 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003786 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003787 return 1;
3788 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003789}
3790
Chris Lattner76a00cf2008-04-06 22:59:24 +00003791/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3792/// routine will assert if passed a built-in type that isn't an integer or enum,
3793/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003794unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003795 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003796
Chris Lattner76a00cf2008-04-06 22:59:24 +00003797 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003798 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003799 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003800 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003801 case BuiltinType::Char_S:
3802 case BuiltinType::Char_U:
3803 case BuiltinType::SChar:
3804 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003805 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003806 case BuiltinType::Short:
3807 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003808 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003809 case BuiltinType::Int:
3810 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003811 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003812 case BuiltinType::Long:
3813 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003814 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003815 case BuiltinType::LongLong:
3816 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003817 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003818 case BuiltinType::Int128:
3819 case BuiltinType::UInt128:
3820 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003821 }
3822}
3823
Eli Friedman629ffb92009-08-20 04:21:42 +00003824/// \brief Whether this is a promotable bitfield reference according
3825/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3826///
3827/// \returns the type this bit-field will promote to, or NULL if no
3828/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003829QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003830 if (E->isTypeDependent() || E->isValueDependent())
3831 return QualType();
3832
Eli Friedman629ffb92009-08-20 04:21:42 +00003833 FieldDecl *Field = E->getBitField();
3834 if (!Field)
3835 return QualType();
3836
3837 QualType FT = Field->getType();
3838
Richard Smithcaf33902011-10-10 18:28:20 +00003839 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00003840 uint64_t IntSize = getTypeSize(IntTy);
3841 // GCC extension compatibility: if the bit-field size is less than or equal
3842 // to the size of int, it gets promoted no matter what its type is.
3843 // For instance, unsigned long bf : 4 gets promoted to signed int.
3844 if (BitWidth < IntSize)
3845 return IntTy;
3846
3847 if (BitWidth == IntSize)
3848 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3849
3850 // Types bigger than int are not subject to promotions, and therefore act
3851 // like the base type.
3852 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3853 // is ridiculous.
3854 return QualType();
3855}
3856
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003857/// getPromotedIntegerType - Returns the type that Promotable will
3858/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3859/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003860QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003861 assert(!Promotable.isNull());
3862 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003863 if (const EnumType *ET = Promotable->getAs<EnumType>())
3864 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00003865
3866 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3867 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3868 // (3.9.1) can be converted to a prvalue of the first of the following
3869 // types that can represent all the values of its underlying type:
3870 // int, unsigned int, long int, unsigned long int, long long int, or
3871 // unsigned long long int [...]
3872 // FIXME: Is there some better way to compute this?
3873 if (BT->getKind() == BuiltinType::WChar_S ||
3874 BT->getKind() == BuiltinType::WChar_U ||
3875 BT->getKind() == BuiltinType::Char16 ||
3876 BT->getKind() == BuiltinType::Char32) {
3877 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3878 uint64_t FromSize = getTypeSize(BT);
3879 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3880 LongLongTy, UnsignedLongLongTy };
3881 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3882 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3883 if (FromSize < ToSize ||
3884 (FromSize == ToSize &&
3885 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3886 return PromoteTypes[Idx];
3887 }
3888 llvm_unreachable("char type should fit into long long");
3889 }
3890 }
3891
3892 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003893 if (Promotable->isSignedIntegerType())
3894 return IntTy;
3895 uint64_t PromotableSize = getTypeSize(Promotable);
3896 uint64_t IntSize = getTypeSize(IntTy);
3897 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3898 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3899}
3900
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003901/// \brief Recurses in pointer/array types until it finds an objc retainable
3902/// type and returns its ownership.
3903Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3904 while (!T.isNull()) {
3905 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3906 return T.getObjCLifetime();
3907 if (T->isArrayType())
3908 T = getBaseElementType(T);
3909 else if (const PointerType *PT = T->getAs<PointerType>())
3910 T = PT->getPointeeType();
3911 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00003912 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003913 else
3914 break;
3915 }
3916
3917 return Qualifiers::OCL_None;
3918}
3919
Mike Stump11289f42009-09-09 15:08:12 +00003920/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003921/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003922/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003923int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00003924 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3925 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003926 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003927
Chris Lattner76a00cf2008-04-06 22:59:24 +00003928 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3929 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003930
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003931 unsigned LHSRank = getIntegerRank(LHSC);
3932 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003933
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003934 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3935 if (LHSRank == RHSRank) return 0;
3936 return LHSRank > RHSRank ? 1 : -1;
3937 }
Mike Stump11289f42009-09-09 15:08:12 +00003938
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003939 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3940 if (LHSUnsigned) {
3941 // If the unsigned [LHS] type is larger, return it.
3942 if (LHSRank >= RHSRank)
3943 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003944
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003945 // If the signed type can represent all values of the unsigned type, it
3946 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003947 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003948 return -1;
3949 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003950
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003951 // If the unsigned [RHS] type is larger, return it.
3952 if (RHSRank >= LHSRank)
3953 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003954
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003955 // If the signed type can represent all values of the unsigned type, it
3956 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003957 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003958 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003959}
Anders Carlsson98f07902007-08-17 05:31:46 +00003960
Anders Carlsson6d417272009-11-14 21:45:58 +00003961static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003962CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3963 DeclContext *DC, IdentifierInfo *Id) {
3964 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003965 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003966 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003967 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003968 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003969}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003970
Mike Stump11289f42009-09-09 15:08:12 +00003971// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003972QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003973 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003974 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003975 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003976 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003977 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003978
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003979 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003980
Anders Carlsson98f07902007-08-17 05:31:46 +00003981 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003982 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003983 // int flags;
3984 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003985 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003986 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003987 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003988 FieldTypes[3] = LongTy;
3989
Anders Carlsson98f07902007-08-17 05:31:46 +00003990 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003991 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003992 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003993 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00003994 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003995 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003996 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003997 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003998 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00003999 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004000 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004001 }
4002
Douglas Gregord5058122010-02-11 01:19:42 +00004003 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004004 }
Mike Stump11289f42009-09-09 15:08:12 +00004005
Anders Carlsson98f07902007-08-17 05:31:46 +00004006 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004007}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004008
Douglas Gregor512b0772009-04-23 22:29:11 +00004009void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004010 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004011 assert(Rec && "Invalid CFConstantStringType");
4012 CFConstantStringTypeDecl = Rec->getDecl();
4013}
4014
Jay Foad39c79802011-01-12 09:06:06 +00004015QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004016 if (BlockDescriptorType)
4017 return getTagDeclType(BlockDescriptorType);
4018
4019 RecordDecl *T;
4020 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004021 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004022 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00004023 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004024
4025 QualType FieldTypes[] = {
4026 UnsignedLongTy,
4027 UnsignedLongTy,
4028 };
4029
4030 const char *FieldNames[] = {
4031 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004032 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004033 };
4034
4035 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004036 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00004037 SourceLocation(),
4038 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004039 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00004040 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004041 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004042 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004043 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00004044 T->addDecl(Field);
4045 }
4046
Douglas Gregord5058122010-02-11 01:19:42 +00004047 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004048
4049 BlockDescriptorType = T;
4050
4051 return getTagDeclType(BlockDescriptorType);
4052}
4053
Jay Foad39c79802011-01-12 09:06:06 +00004054QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004055 if (BlockDescriptorExtendedType)
4056 return getTagDeclType(BlockDescriptorExtendedType);
4057
4058 RecordDecl *T;
4059 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004060 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004061 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00004062 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004063
4064 QualType FieldTypes[] = {
4065 UnsignedLongTy,
4066 UnsignedLongTy,
4067 getPointerType(VoidPtrTy),
4068 getPointerType(VoidPtrTy)
4069 };
4070
4071 const char *FieldNames[] = {
4072 "reserved",
4073 "Size",
4074 "CopyFuncPtr",
4075 "DestroyFuncPtr"
4076 };
4077
4078 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004079 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004080 SourceLocation(),
4081 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004082 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004083 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004084 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004085 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004086 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004087 T->addDecl(Field);
4088 }
4089
Douglas Gregord5058122010-02-11 01:19:42 +00004090 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004091
4092 BlockDescriptorExtendedType = T;
4093
4094 return getTagDeclType(BlockDescriptorExtendedType);
4095}
4096
Jay Foad39c79802011-01-12 09:06:06 +00004097bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCall31168b02011-06-15 23:02:42 +00004098 if (Ty->isObjCRetainableType())
Mike Stump94967902009-10-21 18:16:27 +00004099 return true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004100 if (getLangOpts().CPlusPlus) {
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004101 if (const RecordType *RT = Ty->getAs<RecordType>()) {
4102 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntfcaeae42011-05-25 20:50:04 +00004103 return RD->hasConstCopyConstructor();
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004104
4105 }
4106 }
Mike Stump94967902009-10-21 18:16:27 +00004107 return false;
4108}
4109
Jay Foad39c79802011-01-12 09:06:06 +00004110QualType
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004111ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00004112 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00004113 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00004114 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00004115 // unsigned int __flags;
4116 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00004117 // void *__copy_helper; // as needed
4118 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00004119 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00004120 // } *
4121
Mike Stump94967902009-10-21 18:16:27 +00004122 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
4123
4124 // FIXME: Move up
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004125 SmallString<36> Name;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00004126 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
4127 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00004128 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004129 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00004130 T->startDefinition();
4131 QualType Int32Ty = IntTy;
4132 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
4133 QualType FieldTypes[] = {
4134 getPointerType(VoidPtrTy),
4135 getPointerType(getTagDeclType(T)),
4136 Int32Ty,
4137 Int32Ty,
4138 getPointerType(VoidPtrTy),
4139 getPointerType(VoidPtrTy),
4140 Ty
4141 };
4142
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004143 StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00004144 "__isa",
4145 "__forwarding",
4146 "__flags",
4147 "__size",
4148 "__copy_helper",
4149 "__destroy_helper",
4150 DeclName,
4151 };
4152
4153 for (size_t i = 0; i < 7; ++i) {
4154 if (!HasCopyAndDispose && i >=4 && i <= 5)
4155 continue;
4156 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00004157 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00004158 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004159 FieldTypes[i], /*TInfo=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004160 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004161 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004162 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00004163 T->addDecl(Field);
4164 }
4165
Douglas Gregord5058122010-02-11 01:19:42 +00004166 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00004167
4168 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00004169}
4170
Douglas Gregorbab8a962011-09-08 01:46:34 +00004171TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4172 if (!ObjCInstanceTypeDecl)
4173 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4174 getTranslationUnitDecl(),
4175 SourceLocation(),
4176 SourceLocation(),
4177 &Idents.get("instancetype"),
4178 getTrivialTypeSourceInfo(getObjCIdType()));
4179 return ObjCInstanceTypeDecl;
4180}
4181
Anders Carlsson18acd442007-10-29 06:33:42 +00004182// This returns true if a type has been typedefed to BOOL:
4183// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004184static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004185 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004186 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4187 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004188
Anders Carlssond8499822007-10-29 05:01:08 +00004189 return false;
4190}
4191
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004192/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004193/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004194CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004195 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4196 return CharUnits::Zero();
4197
Ken Dyck40775002010-01-11 17:06:35 +00004198 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004199
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004200 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004201 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004202 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004203 // Treat arrays as pointers, since that's how they're passed in.
4204 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004205 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004206 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004207}
4208
4209static inline
4210std::string charUnitsToString(const CharUnits &CU) {
4211 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004212}
4213
John McCall351762c2011-02-07 10:33:21 +00004214/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004215/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004216std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4217 std::string S;
4218
David Chisnall950a9512009-11-17 19:33:30 +00004219 const BlockDecl *Decl = Expr->getBlockDecl();
4220 QualType BlockTy =
4221 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4222 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00004223 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004224 // Compute size of all parameters.
4225 // Start with computing size of a pointer in number of bytes.
4226 // FIXME: There might(should) be a better way of doing this computation!
4227 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004228 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4229 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004230 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004231 E = Decl->param_end(); PI != E; ++PI) {
4232 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004233 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004234 if (sz.isZero())
4235 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004236 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004237 ParmOffset += sz;
4238 }
4239 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004240 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004241 // Block pointer and offset.
4242 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004243
4244 // Argument types.
4245 ParmOffset = PtrSize;
4246 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4247 Decl->param_end(); PI != E; ++PI) {
4248 ParmVarDecl *PVDecl = *PI;
4249 QualType PType = PVDecl->getOriginalType();
4250 if (const ArrayType *AT =
4251 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4252 // Use array's original type only if it has known number of
4253 // elements.
4254 if (!isa<ConstantArrayType>(AT))
4255 PType = PVDecl->getType();
4256 } else if (PType->isFunctionType())
4257 PType = PVDecl->getType();
4258 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004259 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004260 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004261 }
John McCall351762c2011-02-07 10:33:21 +00004262
4263 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004264}
4265
Douglas Gregora9d84932011-05-27 01:19:52 +00004266bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004267 std::string& S) {
4268 // Encode result type.
4269 getObjCEncodingForType(Decl->getResultType(), S);
4270 CharUnits ParmOffset;
4271 // Compute size of all parameters.
4272 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4273 E = Decl->param_end(); PI != E; ++PI) {
4274 QualType PType = (*PI)->getType();
4275 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004276 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004277 continue;
4278
David Chisnall50e4eba2010-12-30 14:05:53 +00004279 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004280 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004281 ParmOffset += sz;
4282 }
4283 S += charUnitsToString(ParmOffset);
4284 ParmOffset = CharUnits::Zero();
4285
4286 // Argument types.
4287 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4288 E = Decl->param_end(); PI != E; ++PI) {
4289 ParmVarDecl *PVDecl = *PI;
4290 QualType PType = PVDecl->getOriginalType();
4291 if (const ArrayType *AT =
4292 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4293 // Use array's original type only if it has known number of
4294 // elements.
4295 if (!isa<ConstantArrayType>(AT))
4296 PType = PVDecl->getType();
4297 } else if (PType->isFunctionType())
4298 PType = PVDecl->getType();
4299 getObjCEncodingForType(PType, S);
4300 S += charUnitsToString(ParmOffset);
4301 ParmOffset += getObjCEncodingTypeSize(PType);
4302 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004303
4304 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004305}
4306
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004307/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4308/// method parameter or return type. If Extended, include class names and
4309/// block object types.
4310void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4311 QualType T, std::string& S,
4312 bool Extended) const {
4313 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4314 getObjCEncodingForTypeQualifier(QT, S);
4315 // Encode parameter type.
4316 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4317 true /*OutermostType*/,
4318 false /*EncodingProperty*/,
4319 false /*StructField*/,
4320 Extended /*EncodeBlockParameters*/,
4321 Extended /*EncodeClassNames*/);
4322}
4323
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004324/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004325/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004326bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004327 std::string& S,
4328 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004329 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004330 // Encode return type.
4331 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4332 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004333 // Compute size of all parameters.
4334 // Start with computing size of a pointer in number of bytes.
4335 // FIXME: There might(should) be a better way of doing this computation!
4336 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004337 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004338 // The first two arguments (self and _cmd) are pointers; account for
4339 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004340 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004341 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004342 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004343 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004344 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004345 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004346 continue;
4347
Ken Dyck40775002010-01-11 17:06:35 +00004348 assert (sz.isPositive() &&
4349 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004350 ParmOffset += sz;
4351 }
Ken Dyck40775002010-01-11 17:06:35 +00004352 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004353 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004354 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004355
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004356 // Argument types.
4357 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004358 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004359 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004360 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004361 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004362 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004363 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4364 // Use array's original type only if it has known number of
4365 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004366 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004367 PType = PVDecl->getType();
4368 } else if (PType->isFunctionType())
4369 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004370 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4371 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004372 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004373 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004374 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004375
4376 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004377}
4378
Daniel Dunbar4932b362008-08-28 04:38:10 +00004379/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004380/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004381/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4382/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004383/// Property attributes are stored as a comma-delimited C string. The simple
4384/// attributes readonly and bycopy are encoded as single characters. The
4385/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4386/// encoded as single characters, followed by an identifier. Property types
4387/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004388/// these attributes are defined by the following enumeration:
4389/// @code
4390/// enum PropertyAttributes {
4391/// kPropertyReadOnly = 'R', // property is read-only.
4392/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4393/// kPropertyByref = '&', // property is a reference to the value last assigned
4394/// kPropertyDynamic = 'D', // property is dynamic
4395/// kPropertyGetter = 'G', // followed by getter selector name
4396/// kPropertySetter = 'S', // followed by setter selector name
4397/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004398/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004399/// kPropertyWeak = 'W' // 'weak' property
4400/// kPropertyStrong = 'P' // property GC'able
4401/// kPropertyNonAtomic = 'N' // property non-atomic
4402/// };
4403/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004404void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004405 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004406 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004407 // Collect information from the property implementation decl(s).
4408 bool Dynamic = false;
4409 ObjCPropertyImplDecl *SynthesizePID = 0;
4410
4411 // FIXME: Duplicated code due to poor abstraction.
4412 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004413 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004414 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4415 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004416 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004417 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004418 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004419 if (PID->getPropertyDecl() == PD) {
4420 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4421 Dynamic = true;
4422 } else {
4423 SynthesizePID = PID;
4424 }
4425 }
4426 }
4427 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004428 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004429 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004430 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004431 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004432 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004433 if (PID->getPropertyDecl() == PD) {
4434 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4435 Dynamic = true;
4436 } else {
4437 SynthesizePID = PID;
4438 }
4439 }
Mike Stump11289f42009-09-09 15:08:12 +00004440 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004441 }
4442 }
4443
4444 // FIXME: This is not very efficient.
4445 S = "T";
4446
4447 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004448 // GCC has some special rules regarding encoding of properties which
4449 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004450 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004451 true /* outermost type */,
4452 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004453
4454 if (PD->isReadOnly()) {
4455 S += ",R";
4456 } else {
4457 switch (PD->getSetterKind()) {
4458 case ObjCPropertyDecl::Assign: break;
4459 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004460 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004461 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004462 }
4463 }
4464
4465 // It really isn't clear at all what this means, since properties
4466 // are "dynamic by default".
4467 if (Dynamic)
4468 S += ",D";
4469
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004470 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4471 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004472
Daniel Dunbar4932b362008-08-28 04:38:10 +00004473 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4474 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004475 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004476 }
4477
4478 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4479 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004480 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004481 }
4482
4483 if (SynthesizePID) {
4484 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4485 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004486 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004487 }
4488
4489 // FIXME: OBJCGC: weak & strong
4490}
4491
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004492/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004493/// Another legacy compatibility encoding: 32-bit longs are encoded as
4494/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004495/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4496///
4497void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004498 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004499 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004500 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004501 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004502 else
Jay Foad39c79802011-01-12 09:06:06 +00004503 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004504 PointeeTy = IntTy;
4505 }
4506 }
4507}
4508
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004509void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004510 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004511 // We follow the behavior of gcc, expanding structures which are
4512 // directly pointed to, and expanding embedded structures. Note that
4513 // these rules are sufficient to prevent recursive encoding of the
4514 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004515 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004516 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004517}
4518
David Chisnallb190a2c2010-06-04 01:10:52 +00004519static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4520 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004521 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnallb190a2c2010-06-04 01:10:52 +00004522 case BuiltinType::Void: return 'v';
4523 case BuiltinType::Bool: return 'B';
4524 case BuiltinType::Char_U:
4525 case BuiltinType::UChar: return 'C';
4526 case BuiltinType::UShort: return 'S';
4527 case BuiltinType::UInt: return 'I';
4528 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004529 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004530 case BuiltinType::UInt128: return 'T';
4531 case BuiltinType::ULongLong: return 'Q';
4532 case BuiltinType::Char_S:
4533 case BuiltinType::SChar: return 'c';
4534 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004535 case BuiltinType::WChar_S:
4536 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004537 case BuiltinType::Int: return 'i';
4538 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004539 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004540 case BuiltinType::LongLong: return 'q';
4541 case BuiltinType::Int128: return 't';
4542 case BuiltinType::Float: return 'f';
4543 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004544 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004545 }
4546}
4547
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004548static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4549 EnumDecl *Enum = ET->getDecl();
4550
4551 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4552 if (!Enum->isFixed())
4553 return 'i';
4554
4555 // The encoding of a fixed enum type matches its fixed underlying type.
4556 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4557}
4558
Jay Foad39c79802011-01-12 09:06:06 +00004559static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004560 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00004561 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004562 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004563 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4564 // The GNU runtime requires more information; bitfields are encoded as b,
4565 // then the offset (in bits) of the first element, then the type of the
4566 // bitfield, then the size in bits. For example, in this structure:
4567 //
4568 // struct
4569 // {
4570 // int integer;
4571 // int flags:2;
4572 // };
4573 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4574 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4575 // information is not especially sensible, but we're stuck with it for
4576 // compatibility with GCC, although providing it breaks anything that
4577 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00004578 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004579 const RecordDecl *RD = FD->getParent();
4580 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004581 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004582 if (const EnumType *ET = T->getAs<EnumType>())
4583 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnall6f0a7d22010-12-26 20:12:30 +00004584 else
Jay Foad39c79802011-01-12 09:06:06 +00004585 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004586 }
Richard Smithcaf33902011-10-10 18:28:20 +00004587 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004588}
4589
Daniel Dunbar07d07852009-10-18 21:17:35 +00004590// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004591void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4592 bool ExpandPointedToStructures,
4593 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004594 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004595 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004596 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004597 bool StructField,
4598 bool EncodeBlockParameters,
4599 bool EncodeClassNames) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004600 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004601 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004602 return EncodeBitField(this, S, T, FD);
4603 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004604 return;
4605 }
Mike Stump11289f42009-09-09 15:08:12 +00004606
John McCall9dd450b2009-09-21 23:43:11 +00004607 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004608 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004609 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004610 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004611 return;
4612 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004613
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004614 // encoding for pointer or r3eference types.
4615 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004616 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004617 if (PT->isObjCSelType()) {
4618 S += ':';
4619 return;
4620 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004621 PointeeTy = PT->getPointeeType();
4622 }
4623 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4624 PointeeTy = RT->getPointeeType();
4625 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004626 bool isReadOnly = false;
4627 // For historical/compatibility reasons, the read-only qualifier of the
4628 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4629 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004630 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004631 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004632 if (OutermostType && T.isConstQualified()) {
4633 isReadOnly = true;
4634 S += 'r';
4635 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004636 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004637 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004638 while (P->getAs<PointerType>())
4639 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004640 if (P.isConstQualified()) {
4641 isReadOnly = true;
4642 S += 'r';
4643 }
4644 }
4645 if (isReadOnly) {
4646 // Another legacy compatibility encoding. Some ObjC qualifier and type
4647 // combinations need to be rearranged.
4648 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004649 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004650 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004651 }
Mike Stump11289f42009-09-09 15:08:12 +00004652
Anders Carlssond8499822007-10-29 05:01:08 +00004653 if (PointeeTy->isCharType()) {
4654 // char pointer types should be encoded as '*' unless it is a
4655 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004656 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004657 S += '*';
4658 return;
4659 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004660 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004661 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4662 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4663 S += '#';
4664 return;
4665 }
4666 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4667 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4668 S += '@';
4669 return;
4670 }
4671 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004672 }
Anders Carlssond8499822007-10-29 05:01:08 +00004673 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004674 getLegacyIntegralTypeEncoding(PointeeTy);
4675
Mike Stump11289f42009-09-09 15:08:12 +00004676 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004677 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004678 return;
4679 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004680
Chris Lattnere7cabb92009-07-13 00:10:46 +00004681 if (const ArrayType *AT =
4682 // Ignore type qualifiers etc.
4683 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004684 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004685 // Incomplete arrays are encoded as a pointer to the array element.
4686 S += '^';
4687
Mike Stump11289f42009-09-09 15:08:12 +00004688 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004689 false, ExpandStructures, FD);
4690 } else {
4691 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004692
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004693 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4694 if (getTypeSize(CAT->getElementType()) == 0)
4695 S += '0';
4696 else
4697 S += llvm::utostr(CAT->getSize().getZExtValue());
4698 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004699 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004700 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4701 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00004702 S += '0';
4703 }
Mike Stump11289f42009-09-09 15:08:12 +00004704
4705 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004706 false, ExpandStructures, FD);
4707 S += ']';
4708 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004709 return;
4710 }
Mike Stump11289f42009-09-09 15:08:12 +00004711
John McCall9dd450b2009-09-21 23:43:11 +00004712 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004713 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004714 return;
4715 }
Mike Stump11289f42009-09-09 15:08:12 +00004716
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004717 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004718 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004719 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004720 // Anonymous structures print as '?'
4721 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4722 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004723 if (ClassTemplateSpecializationDecl *Spec
4724 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4725 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4726 std::string TemplateArgsStr
4727 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004728 TemplateArgs.data(),
4729 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00004730 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004731
4732 S += TemplateArgsStr;
4733 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004734 } else {
4735 S += '?';
4736 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004737 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004738 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004739 if (!RDecl->isUnion()) {
4740 getObjCEncodingForStructureImpl(RDecl, S, FD);
4741 } else {
4742 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4743 FieldEnd = RDecl->field_end();
4744 Field != FieldEnd; ++Field) {
4745 if (FD) {
4746 S += '"';
4747 S += Field->getNameAsString();
4748 S += '"';
4749 }
Mike Stump11289f42009-09-09 15:08:12 +00004750
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004751 // Special case bit-fields.
4752 if (Field->isBitField()) {
4753 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00004754 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004755 } else {
4756 QualType qt = Field->getType();
4757 getLegacyIntegralTypeEncoding(qt);
4758 getObjCEncodingForTypeImpl(qt, S, false, true,
4759 FD, /*OutermostType*/false,
4760 /*EncodingProperty*/false,
4761 /*StructField*/true);
4762 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004763 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004764 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004765 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004766 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004767 return;
4768 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004769
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004770 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004771 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004772 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004773 else
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004774 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004775 return;
4776 }
Mike Stump11289f42009-09-09 15:08:12 +00004777
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004778 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004779 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004780 if (EncodeBlockParameters) {
4781 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4782
4783 S += '<';
4784 // Block return type
4785 getObjCEncodingForTypeImpl(FT->getResultType(), S,
4786 ExpandPointedToStructures, ExpandStructures,
4787 FD,
4788 false /* OutermostType */,
4789 EncodingProperty,
4790 false /* StructField */,
4791 EncodeBlockParameters,
4792 EncodeClassNames);
4793 // Block self
4794 S += "@?";
4795 // Block parameters
4796 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4797 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4798 E = FPT->arg_type_end(); I && (I != E); ++I) {
4799 getObjCEncodingForTypeImpl(*I, S,
4800 ExpandPointedToStructures,
4801 ExpandStructures,
4802 FD,
4803 false /* OutermostType */,
4804 EncodingProperty,
4805 false /* StructField */,
4806 EncodeBlockParameters,
4807 EncodeClassNames);
4808 }
4809 }
4810 S += '>';
4811 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004812 return;
4813 }
Mike Stump11289f42009-09-09 15:08:12 +00004814
John McCall8b07ec22010-05-15 11:32:37 +00004815 // Ignore protocol qualifiers when mangling at this level.
4816 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4817 T = OT->getBaseType();
4818
John McCall8ccfcb52009-09-24 19:53:00 +00004819 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004820 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004821 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004822 S += '{';
4823 const IdentifierInfo *II = OI->getIdentifier();
4824 S += II->getName();
4825 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00004826 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004827 DeepCollectObjCIvars(OI, true, Ivars);
4828 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004829 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004830 if (Field->isBitField())
4831 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004832 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004833 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004834 }
4835 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004836 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004837 }
Mike Stump11289f42009-09-09 15:08:12 +00004838
John McCall9dd450b2009-09-21 23:43:11 +00004839 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004840 if (OPT->isObjCIdType()) {
4841 S += '@';
4842 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004843 }
Mike Stump11289f42009-09-09 15:08:12 +00004844
Steve Narofff0c86112009-10-28 22:03:49 +00004845 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4846 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4847 // Since this is a binary compatibility issue, need to consult with runtime
4848 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004849 S += '#';
4850 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004851 }
Mike Stump11289f42009-09-09 15:08:12 +00004852
Chris Lattnere7cabb92009-07-13 00:10:46 +00004853 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004854 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004855 ExpandPointedToStructures,
4856 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004857 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004858 // Note that we do extended encoding of protocol qualifer list
4859 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004860 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004861 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4862 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004863 S += '<';
4864 S += (*I)->getNameAsString();
4865 S += '>';
4866 }
4867 S += '"';
4868 }
4869 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004870 }
Mike Stump11289f42009-09-09 15:08:12 +00004871
Chris Lattnere7cabb92009-07-13 00:10:46 +00004872 QualType PointeeTy = OPT->getPointeeType();
4873 if (!EncodingProperty &&
4874 isa<TypedefType>(PointeeTy.getTypePtr())) {
4875 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004876 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004877 // {...};
4878 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004879 getObjCEncodingForTypeImpl(PointeeTy, S,
4880 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004881 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004882 return;
4883 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004884
4885 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004886 if (OPT->getInterfaceDecl() &&
4887 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004888 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004889 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004890 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4891 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004892 S += '<';
4893 S += (*I)->getNameAsString();
4894 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004895 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004896 S += '"';
4897 }
4898 return;
4899 }
Mike Stump11289f42009-09-09 15:08:12 +00004900
John McCalla9e6e8d2010-05-17 23:56:34 +00004901 // gcc just blithely ignores member pointers.
4902 // TODO: maybe there should be a mangling for these
4903 if (T->getAs<MemberPointerType>())
4904 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004905
4906 if (T->isVectorType()) {
4907 // This matches gcc's encoding, even though technically it is
4908 // insufficient.
4909 // FIXME. We should do a better job than gcc.
4910 return;
4911 }
4912
David Blaikie83d382b2011-09-23 05:06:16 +00004913 llvm_unreachable("@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004914}
4915
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004916void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4917 std::string &S,
4918 const FieldDecl *FD,
4919 bool includeVBases) const {
4920 assert(RDecl && "Expected non-null RecordDecl");
4921 assert(!RDecl->isUnion() && "Should not be called for unions");
4922 if (!RDecl->getDefinition())
4923 return;
4924
4925 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4926 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4927 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4928
4929 if (CXXRec) {
4930 for (CXXRecordDecl::base_class_iterator
4931 BI = CXXRec->bases_begin(),
4932 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4933 if (!BI->isVirtual()) {
4934 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004935 if (base->isEmpty())
4936 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00004937 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004938 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4939 std::make_pair(offs, base));
4940 }
4941 }
4942 }
4943
4944 unsigned i = 0;
4945 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4946 FieldEnd = RDecl->field_end();
4947 Field != FieldEnd; ++Field, ++i) {
4948 uint64_t offs = layout.getFieldOffset(i);
4949 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00004950 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004951 }
4952
4953 if (CXXRec && includeVBases) {
4954 for (CXXRecordDecl::base_class_iterator
4955 BI = CXXRec->vbases_begin(),
4956 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4957 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004958 if (base->isEmpty())
4959 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00004960 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00004961 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4962 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4963 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004964 }
4965 }
4966
4967 CharUnits size;
4968 if (CXXRec) {
4969 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4970 } else {
4971 size = layout.getSize();
4972 }
4973
4974 uint64_t CurOffs = 0;
4975 std::multimap<uint64_t, NamedDecl *>::iterator
4976 CurLayObj = FieldOrBaseOffsets.begin();
4977
Douglas Gregorf5d6c742012-04-27 22:30:01 +00004978 if (CXXRec && CXXRec->isDynamicClass() &&
4979 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004980 if (FD) {
4981 S += "\"_vptr$";
4982 std::string recname = CXXRec->getNameAsString();
4983 if (recname.empty()) recname = "?";
4984 S += recname;
4985 S += '"';
4986 }
4987 S += "^^?";
4988 CurOffs += getTypeSize(VoidPtrTy);
4989 }
4990
4991 if (!RDecl->hasFlexibleArrayMember()) {
4992 // Mark the end of the structure.
4993 uint64_t offs = toBits(size);
4994 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4995 std::make_pair(offs, (NamedDecl*)0));
4996 }
4997
4998 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4999 assert(CurOffs <= CurLayObj->first);
5000
5001 if (CurOffs < CurLayObj->first) {
5002 uint64_t padding = CurLayObj->first - CurOffs;
5003 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5004 // packing/alignment of members is different that normal, in which case
5005 // the encoding will be out-of-sync with the real layout.
5006 // If the runtime switches to just consider the size of types without
5007 // taking into account alignment, we could make padding explicit in the
5008 // encoding (e.g. using arrays of chars). The encoding strings would be
5009 // longer then though.
5010 CurOffs += padding;
5011 }
5012
5013 NamedDecl *dcl = CurLayObj->second;
5014 if (dcl == 0)
5015 break; // reached end of structure.
5016
5017 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5018 // We expand the bases without their virtual bases since those are going
5019 // in the initial structure. Note that this differs from gcc which
5020 // expands virtual bases each time one is encountered in the hierarchy,
5021 // making the encoding type bigger than it really is.
5022 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005023 assert(!base->isEmpty());
5024 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005025 } else {
5026 FieldDecl *field = cast<FieldDecl>(dcl);
5027 if (FD) {
5028 S += '"';
5029 S += field->getNameAsString();
5030 S += '"';
5031 }
5032
5033 if (field->isBitField()) {
5034 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00005035 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005036 } else {
5037 QualType qt = field->getType();
5038 getLegacyIntegralTypeEncoding(qt);
5039 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5040 /*OutermostType*/false,
5041 /*EncodingProperty*/false,
5042 /*StructField*/true);
5043 CurOffs += getTypeSize(field->getType());
5044 }
5045 }
5046 }
5047}
5048
Mike Stump11289f42009-09-09 15:08:12 +00005049void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005050 std::string& S) const {
5051 if (QT & Decl::OBJC_TQ_In)
5052 S += 'n';
5053 if (QT & Decl::OBJC_TQ_Inout)
5054 S += 'N';
5055 if (QT & Decl::OBJC_TQ_Out)
5056 S += 'o';
5057 if (QT & Decl::OBJC_TQ_Bycopy)
5058 S += 'O';
5059 if (QT & Decl::OBJC_TQ_Byref)
5060 S += 'R';
5061 if (QT & Decl::OBJC_TQ_Oneway)
5062 S += 'V';
5063}
5064
Douglas Gregor3ea72692011-08-12 05:46:01 +00005065TypedefDecl *ASTContext::getObjCIdDecl() const {
5066 if (!ObjCIdDecl) {
5067 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5068 T = getObjCObjectPointerType(T);
5069 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5070 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5071 getTranslationUnitDecl(),
5072 SourceLocation(), SourceLocation(),
5073 &Idents.get("id"), IdInfo);
5074 }
5075
5076 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005077}
5078
Douglas Gregor52e02802011-08-12 06:17:30 +00005079TypedefDecl *ASTContext::getObjCSelDecl() const {
5080 if (!ObjCSelDecl) {
5081 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5082 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5083 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5084 getTranslationUnitDecl(),
5085 SourceLocation(), SourceLocation(),
5086 &Idents.get("SEL"), SelInfo);
5087 }
5088 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005089}
5090
Douglas Gregor0a586182011-08-12 05:59:41 +00005091TypedefDecl *ASTContext::getObjCClassDecl() const {
5092 if (!ObjCClassDecl) {
5093 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5094 T = getObjCObjectPointerType(T);
5095 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5096 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5097 getTranslationUnitDecl(),
5098 SourceLocation(), SourceLocation(),
5099 &Idents.get("Class"), ClassInfo);
5100 }
5101
5102 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005103}
5104
Douglas Gregord53ae832012-01-17 18:09:05 +00005105ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5106 if (!ObjCProtocolClassDecl) {
5107 ObjCProtocolClassDecl
5108 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5109 SourceLocation(),
5110 &Idents.get("Protocol"),
5111 /*PrevDecl=*/0,
5112 SourceLocation(), true);
5113 }
5114
5115 return ObjCProtocolClassDecl;
5116}
5117
Meador Inge5d3fb222012-06-16 03:34:49 +00005118//===----------------------------------------------------------------------===//
5119// __builtin_va_list Construction Functions
5120//===----------------------------------------------------------------------===//
5121
5122static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5123 // typedef char* __builtin_va_list;
5124 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5125 TypeSourceInfo *TInfo
5126 = Context->getTrivialTypeSourceInfo(CharPtrType);
5127
5128 TypedefDecl *VaListTypeDecl
5129 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5130 Context->getTranslationUnitDecl(),
5131 SourceLocation(), SourceLocation(),
5132 &Context->Idents.get("__builtin_va_list"),
5133 TInfo);
5134 return VaListTypeDecl;
5135}
5136
5137static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5138 // typedef void* __builtin_va_list;
5139 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5140 TypeSourceInfo *TInfo
5141 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5142
5143 TypedefDecl *VaListTypeDecl
5144 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5145 Context->getTranslationUnitDecl(),
5146 SourceLocation(), SourceLocation(),
5147 &Context->Idents.get("__builtin_va_list"),
5148 TInfo);
5149 return VaListTypeDecl;
5150}
5151
5152static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5153 // typedef struct __va_list_tag {
5154 RecordDecl *VaListTagDecl;
5155
5156 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5157 Context->getTranslationUnitDecl(),
5158 &Context->Idents.get("__va_list_tag"));
5159 VaListTagDecl->startDefinition();
5160
5161 const size_t NumFields = 5;
5162 QualType FieldTypes[NumFields];
5163 const char *FieldNames[NumFields];
5164
5165 // unsigned char gpr;
5166 FieldTypes[0] = Context->UnsignedCharTy;
5167 FieldNames[0] = "gpr";
5168
5169 // unsigned char fpr;
5170 FieldTypes[1] = Context->UnsignedCharTy;
5171 FieldNames[1] = "fpr";
5172
5173 // unsigned short reserved;
5174 FieldTypes[2] = Context->UnsignedShortTy;
5175 FieldNames[2] = "reserved";
5176
5177 // void* overflow_arg_area;
5178 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5179 FieldNames[3] = "overflow_arg_area";
5180
5181 // void* reg_save_area;
5182 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5183 FieldNames[4] = "reg_save_area";
5184
5185 // Create fields
5186 for (unsigned i = 0; i < NumFields; ++i) {
5187 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5188 SourceLocation(),
5189 SourceLocation(),
5190 &Context->Idents.get(FieldNames[i]),
5191 FieldTypes[i], /*TInfo=*/0,
5192 /*BitWidth=*/0,
5193 /*Mutable=*/false,
5194 ICIS_NoInit);
5195 Field->setAccess(AS_public);
5196 VaListTagDecl->addDecl(Field);
5197 }
5198 VaListTagDecl->completeDefinition();
5199 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005200 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005201
5202 // } __va_list_tag;
5203 TypedefDecl *VaListTagTypedefDecl
5204 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5205 Context->getTranslationUnitDecl(),
5206 SourceLocation(), SourceLocation(),
5207 &Context->Idents.get("__va_list_tag"),
5208 Context->getTrivialTypeSourceInfo(VaListTagType));
5209 QualType VaListTagTypedefType =
5210 Context->getTypedefType(VaListTagTypedefDecl);
5211
5212 // typedef __va_list_tag __builtin_va_list[1];
5213 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5214 QualType VaListTagArrayType
5215 = Context->getConstantArrayType(VaListTagTypedefType,
5216 Size, ArrayType::Normal, 0);
5217 TypeSourceInfo *TInfo
5218 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5219 TypedefDecl *VaListTypedefDecl
5220 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5221 Context->getTranslationUnitDecl(),
5222 SourceLocation(), SourceLocation(),
5223 &Context->Idents.get("__builtin_va_list"),
5224 TInfo);
5225
5226 return VaListTypedefDecl;
5227}
5228
5229static TypedefDecl *
5230CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5231 // typedef struct __va_list_tag {
5232 RecordDecl *VaListTagDecl;
5233 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5234 Context->getTranslationUnitDecl(),
5235 &Context->Idents.get("__va_list_tag"));
5236 VaListTagDecl->startDefinition();
5237
5238 const size_t NumFields = 4;
5239 QualType FieldTypes[NumFields];
5240 const char *FieldNames[NumFields];
5241
5242 // unsigned gp_offset;
5243 FieldTypes[0] = Context->UnsignedIntTy;
5244 FieldNames[0] = "gp_offset";
5245
5246 // unsigned fp_offset;
5247 FieldTypes[1] = Context->UnsignedIntTy;
5248 FieldNames[1] = "fp_offset";
5249
5250 // void* overflow_arg_area;
5251 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5252 FieldNames[2] = "overflow_arg_area";
5253
5254 // void* reg_save_area;
5255 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5256 FieldNames[3] = "reg_save_area";
5257
5258 // Create fields
5259 for (unsigned i = 0; i < NumFields; ++i) {
5260 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5261 VaListTagDecl,
5262 SourceLocation(),
5263 SourceLocation(),
5264 &Context->Idents.get(FieldNames[i]),
5265 FieldTypes[i], /*TInfo=*/0,
5266 /*BitWidth=*/0,
5267 /*Mutable=*/false,
5268 ICIS_NoInit);
5269 Field->setAccess(AS_public);
5270 VaListTagDecl->addDecl(Field);
5271 }
5272 VaListTagDecl->completeDefinition();
5273 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005274 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005275
5276 // } __va_list_tag;
5277 TypedefDecl *VaListTagTypedefDecl
5278 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5279 Context->getTranslationUnitDecl(),
5280 SourceLocation(), SourceLocation(),
5281 &Context->Idents.get("__va_list_tag"),
5282 Context->getTrivialTypeSourceInfo(VaListTagType));
5283 QualType VaListTagTypedefType =
5284 Context->getTypedefType(VaListTagTypedefDecl);
5285
5286 // typedef __va_list_tag __builtin_va_list[1];
5287 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5288 QualType VaListTagArrayType
5289 = Context->getConstantArrayType(VaListTagTypedefType,
5290 Size, ArrayType::Normal,0);
5291 TypeSourceInfo *TInfo
5292 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5293 TypedefDecl *VaListTypedefDecl
5294 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5295 Context->getTranslationUnitDecl(),
5296 SourceLocation(), SourceLocation(),
5297 &Context->Idents.get("__builtin_va_list"),
5298 TInfo);
5299
5300 return VaListTypedefDecl;
5301}
5302
5303static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5304 // typedef int __builtin_va_list[4];
5305 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5306 QualType IntArrayType
5307 = Context->getConstantArrayType(Context->IntTy,
5308 Size, ArrayType::Normal, 0);
5309 TypedefDecl *VaListTypedefDecl
5310 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5311 Context->getTranslationUnitDecl(),
5312 SourceLocation(), SourceLocation(),
5313 &Context->Idents.get("__builtin_va_list"),
5314 Context->getTrivialTypeSourceInfo(IntArrayType));
5315
5316 return VaListTypedefDecl;
5317}
5318
5319static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5320 TargetInfo::BuiltinVaListKind Kind) {
5321 switch (Kind) {
5322 case TargetInfo::CharPtrBuiltinVaList:
5323 return CreateCharPtrBuiltinVaListDecl(Context);
5324 case TargetInfo::VoidPtrBuiltinVaList:
5325 return CreateVoidPtrBuiltinVaListDecl(Context);
5326 case TargetInfo::PowerABIBuiltinVaList:
5327 return CreatePowerABIBuiltinVaListDecl(Context);
5328 case TargetInfo::X86_64ABIBuiltinVaList:
5329 return CreateX86_64ABIBuiltinVaListDecl(Context);
5330 case TargetInfo::PNaClABIBuiltinVaList:
5331 return CreatePNaClABIBuiltinVaListDecl(Context);
5332 }
5333
5334 llvm_unreachable("Unhandled __builtin_va_list type kind");
5335}
5336
5337TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5338 if (!BuiltinVaListDecl)
5339 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5340
5341 return BuiltinVaListDecl;
5342}
5343
Meador Ingecfb60902012-07-01 15:57:25 +00005344QualType ASTContext::getVaListTagType() const {
5345 // Force the creation of VaListTagTy by building the __builtin_va_list
5346 // declaration.
5347 if (VaListTagTy.isNull())
5348 (void) getBuiltinVaListDecl();
5349
5350 return VaListTagTy;
5351}
5352
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005353void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00005354 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00005355 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00005356
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005357 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00005358}
5359
John McCalld28ae272009-12-02 08:04:21 +00005360/// \brief Retrieve the template name that corresponds to a non-empty
5361/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00005362TemplateName
5363ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5364 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00005365 unsigned size = End - Begin;
5366 assert(size > 1 && "set is not overloaded!");
5367
5368 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5369 size * sizeof(FunctionTemplateDecl*));
5370 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5371
5372 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00005373 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00005374 NamedDecl *D = *I;
5375 assert(isa<FunctionTemplateDecl>(D) ||
5376 (isa<UsingShadowDecl>(D) &&
5377 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5378 *Storage++ = D;
5379 }
5380
5381 return TemplateName(OT);
5382}
5383
Douglas Gregordc572a32009-03-30 22:58:21 +00005384/// \brief Retrieve the template name that represents a qualified
5385/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00005386TemplateName
5387ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5388 bool TemplateKeyword,
5389 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00005390 assert(NNS && "Missing nested-name-specifier in qualified template name");
5391
Douglas Gregorc42075a2010-02-04 18:10:26 +00005392 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00005393 llvm::FoldingSetNodeID ID;
5394 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5395
5396 void *InsertPos = 0;
5397 QualifiedTemplateName *QTN =
5398 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5399 if (!QTN) {
5400 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
5401 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5402 }
5403
5404 return TemplateName(QTN);
5405}
5406
5407/// \brief Retrieve the template name that represents a dependent
5408/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00005409TemplateName
5410ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5411 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00005412 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00005413 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00005414
5415 llvm::FoldingSetNodeID ID;
5416 DependentTemplateName::Profile(ID, NNS, Name);
5417
5418 void *InsertPos = 0;
5419 DependentTemplateName *QTN =
5420 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5421
5422 if (QTN)
5423 return TemplateName(QTN);
5424
5425 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5426 if (CanonNNS == NNS) {
5427 QTN = new (*this,4) DependentTemplateName(NNS, Name);
5428 } else {
5429 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
5430 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005431 DependentTemplateName *CheckQTN =
5432 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5433 assert(!CheckQTN && "Dependent type name canonicalization broken");
5434 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00005435 }
5436
5437 DependentTemplateNames.InsertNode(QTN, InsertPos);
5438 return TemplateName(QTN);
5439}
5440
Douglas Gregor71395fa2009-11-04 00:56:37 +00005441/// \brief Retrieve the template name that represents a dependent
5442/// template name such as \c MetaFun::template operator+.
5443TemplateName
5444ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00005445 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00005446 assert((!NNS || NNS->isDependent()) &&
5447 "Nested name specifier must be dependent");
5448
5449 llvm::FoldingSetNodeID ID;
5450 DependentTemplateName::Profile(ID, NNS, Operator);
5451
5452 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00005453 DependentTemplateName *QTN
5454 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005455
5456 if (QTN)
5457 return TemplateName(QTN);
5458
5459 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5460 if (CanonNNS == NNS) {
5461 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
5462 } else {
5463 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
5464 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005465
5466 DependentTemplateName *CheckQTN
5467 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5468 assert(!CheckQTN && "Dependent template name canonicalization broken");
5469 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00005470 }
5471
5472 DependentTemplateNames.InsertNode(QTN, InsertPos);
5473 return TemplateName(QTN);
5474}
5475
Douglas Gregor5590be02011-01-15 06:45:20 +00005476TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00005477ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5478 TemplateName replacement) const {
5479 llvm::FoldingSetNodeID ID;
5480 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5481
5482 void *insertPos = 0;
5483 SubstTemplateTemplateParmStorage *subst
5484 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5485
5486 if (!subst) {
5487 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5488 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5489 }
5490
5491 return TemplateName(subst);
5492}
5493
5494TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00005495ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5496 const TemplateArgument &ArgPack) const {
5497 ASTContext &Self = const_cast<ASTContext &>(*this);
5498 llvm::FoldingSetNodeID ID;
5499 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5500
5501 void *InsertPos = 0;
5502 SubstTemplateTemplateParmPackStorage *Subst
5503 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5504
5505 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00005506 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00005507 ArgPack.pack_size(),
5508 ArgPack.pack_begin());
5509 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5510 }
5511
5512 return TemplateName(Subst);
5513}
5514
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005515/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00005516/// TargetInfo, produce the corresponding type. The unsigned @p Type
5517/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00005518CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005519 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00005520 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005521 case TargetInfo::SignedShort: return ShortTy;
5522 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5523 case TargetInfo::SignedInt: return IntTy;
5524 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5525 case TargetInfo::SignedLong: return LongTy;
5526 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5527 case TargetInfo::SignedLongLong: return LongLongTy;
5528 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5529 }
5530
David Blaikie83d382b2011-09-23 05:06:16 +00005531 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005532}
Ted Kremenek77c51b22008-07-24 23:58:27 +00005533
5534//===----------------------------------------------------------------------===//
5535// Type Predicates.
5536//===----------------------------------------------------------------------===//
5537
Fariborz Jahanian96207692009-02-18 21:49:28 +00005538/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5539/// garbage collection attribute.
5540///
John McCall553d45a2011-01-12 00:34:59 +00005541Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005542 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00005543 return Qualifiers::GCNone;
5544
David Blaikiebbafb8a2012-03-11 07:00:24 +00005545 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00005546 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5547
5548 // Default behaviour under objective-C's gc is for ObjC pointers
5549 // (or pointers to them) be treated as though they were declared
5550 // as __strong.
5551 if (GCAttrs == Qualifiers::GCNone) {
5552 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5553 return Qualifiers::Strong;
5554 else if (Ty->isPointerType())
5555 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5556 } else {
5557 // It's not valid to set GC attributes on anything that isn't a
5558 // pointer.
5559#ifndef NDEBUG
5560 QualType CT = Ty->getCanonicalTypeInternal();
5561 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5562 CT = AT->getElementType();
5563 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5564#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00005565 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00005566 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00005567}
5568
Chris Lattner49af6a42008-04-07 06:51:04 +00005569//===----------------------------------------------------------------------===//
5570// Type Compatibility Testing
5571//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00005572
Mike Stump11289f42009-09-09 15:08:12 +00005573/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005574/// compatible.
5575static bool areCompatVectorTypes(const VectorType *LHS,
5576 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00005577 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00005578 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00005579 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00005580}
5581
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005582bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5583 QualType SecondVec) {
5584 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5585 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5586
5587 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5588 return true;
5589
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005590 // Treat Neon vector types and most AltiVec vector types as if they are the
5591 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005592 const VectorType *First = FirstVec->getAs<VectorType>();
5593 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005594 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005595 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005596 First->getVectorKind() != VectorType::AltiVecPixel &&
5597 First->getVectorKind() != VectorType::AltiVecBool &&
5598 Second->getVectorKind() != VectorType::AltiVecPixel &&
5599 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005600 return true;
5601
5602 return false;
5603}
5604
Steve Naroff8e6aee52009-07-23 01:01:38 +00005605//===----------------------------------------------------------------------===//
5606// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5607//===----------------------------------------------------------------------===//
5608
5609/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5610/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00005611bool
5612ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5613 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00005614 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005615 return true;
5616 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5617 E = rProto->protocol_end(); PI != E; ++PI)
5618 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5619 return true;
5620 return false;
5621}
5622
Steve Naroff8e6aee52009-07-23 01:01:38 +00005623/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5624/// return true if lhs's protocols conform to rhs's protocol; false
5625/// otherwise.
5626bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5627 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5628 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5629 return false;
5630}
5631
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005632/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5633/// Class<p1, ...>.
5634bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5635 QualType rhs) {
5636 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5637 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5638 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5639
5640 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5641 E = lhsQID->qual_end(); I != E; ++I) {
5642 bool match = false;
5643 ObjCProtocolDecl *lhsProto = *I;
5644 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5645 E = rhsOPT->qual_end(); J != E; ++J) {
5646 ObjCProtocolDecl *rhsProto = *J;
5647 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5648 match = true;
5649 break;
5650 }
5651 }
5652 if (!match)
5653 return false;
5654 }
5655 return true;
5656}
5657
Steve Naroff8e6aee52009-07-23 01:01:38 +00005658/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5659/// ObjCQualifiedIDType.
5660bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5661 bool compare) {
5662 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00005663 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005664 lhs->isObjCIdType() || lhs->isObjCClassType())
5665 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005666 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005667 rhs->isObjCIdType() || rhs->isObjCClassType())
5668 return true;
5669
5670 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00005671 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005672
Steve Naroff8e6aee52009-07-23 01:01:38 +00005673 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00005674
Steve Naroff8e6aee52009-07-23 01:01:38 +00005675 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005676 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005677 // make sure we check the class hierarchy.
5678 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5679 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5680 E = lhsQID->qual_end(); I != E; ++I) {
5681 // when comparing an id<P> on lhs with a static type on rhs,
5682 // see if static class implements all of id's protocols, directly or
5683 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005684 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005685 return false;
5686 }
5687 }
5688 // If there are no qualifiers and no interface, we have an 'id'.
5689 return true;
5690 }
Mike Stump11289f42009-09-09 15:08:12 +00005691 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005692 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5693 E = lhsQID->qual_end(); I != E; ++I) {
5694 ObjCProtocolDecl *lhsProto = *I;
5695 bool match = false;
5696
5697 // when comparing an id<P> on lhs with a static type on rhs,
5698 // see if static class implements all of id's protocols, directly or
5699 // through its super class and categories.
5700 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5701 E = rhsOPT->qual_end(); J != E; ++J) {
5702 ObjCProtocolDecl *rhsProto = *J;
5703 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5704 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5705 match = true;
5706 break;
5707 }
5708 }
Mike Stump11289f42009-09-09 15:08:12 +00005709 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005710 // make sure we check the class hierarchy.
5711 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5712 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5713 E = lhsQID->qual_end(); I != E; ++I) {
5714 // when comparing an id<P> on lhs with a static type on rhs,
5715 // see if static class implements all of id's protocols, directly or
5716 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005717 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005718 match = true;
5719 break;
5720 }
5721 }
5722 }
5723 if (!match)
5724 return false;
5725 }
Mike Stump11289f42009-09-09 15:08:12 +00005726
Steve Naroff8e6aee52009-07-23 01:01:38 +00005727 return true;
5728 }
Mike Stump11289f42009-09-09 15:08:12 +00005729
Steve Naroff8e6aee52009-07-23 01:01:38 +00005730 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5731 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5732
Mike Stump11289f42009-09-09 15:08:12 +00005733 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00005734 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005735 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005736 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5737 E = lhsOPT->qual_end(); I != E; ++I) {
5738 ObjCProtocolDecl *lhsProto = *I;
5739 bool match = false;
5740
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005741 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00005742 // see if static class implements all of id's protocols, directly or
5743 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005744 // First, lhs protocols in the qualifier list must be found, direct
5745 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005746 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5747 E = rhsQID->qual_end(); J != E; ++J) {
5748 ObjCProtocolDecl *rhsProto = *J;
5749 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5750 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5751 match = true;
5752 break;
5753 }
5754 }
5755 if (!match)
5756 return false;
5757 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005758
5759 // Static class's protocols, or its super class or category protocols
5760 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5761 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5762 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5763 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5764 // This is rather dubious but matches gcc's behavior. If lhs has
5765 // no type qualifier and its class has no static protocol(s)
5766 // assume that it is mismatch.
5767 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5768 return false;
5769 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5770 LHSInheritedProtocols.begin(),
5771 E = LHSInheritedProtocols.end(); I != E; ++I) {
5772 bool match = false;
5773 ObjCProtocolDecl *lhsProto = (*I);
5774 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5775 E = rhsQID->qual_end(); J != E; ++J) {
5776 ObjCProtocolDecl *rhsProto = *J;
5777 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5778 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5779 match = true;
5780 break;
5781 }
5782 }
5783 if (!match)
5784 return false;
5785 }
5786 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00005787 return true;
5788 }
5789 return false;
5790}
5791
Eli Friedman47f77112008-08-22 00:56:42 +00005792/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005793/// compatible for assignment from RHS to LHS. This handles validation of any
5794/// protocol qualifiers on the LHS or RHS.
5795///
Steve Naroff7cae42b2009-07-10 23:34:53 +00005796bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5797 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00005798 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5799 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5800
Steve Naroff1329fa02009-07-15 18:40:39 +00005801 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00005802 if (LHS->isObjCUnqualifiedIdOrClass() ||
5803 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00005804 return true;
5805
John McCall8b07ec22010-05-15 11:32:37 +00005806 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00005807 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5808 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00005809 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005810
5811 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5812 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5813 QualType(RHSOPT,0));
5814
John McCall8b07ec22010-05-15 11:32:37 +00005815 // If we have 2 user-defined types, fall into that path.
5816 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00005817 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005818
Steve Naroff8e6aee52009-07-23 01:01:38 +00005819 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005820}
5821
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005822/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00005823/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005824/// arguments in block literals. When passed as arguments, passing 'A*' where
5825/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5826/// not OK. For the return type, the opposite is not OK.
5827bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5828 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005829 const ObjCObjectPointerType *RHSOPT,
5830 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005831 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005832 return true;
5833
5834 if (LHSOPT->isObjCBuiltinType()) {
5835 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5836 }
5837
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005838 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005839 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5840 QualType(RHSOPT,0),
5841 false);
5842
5843 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5844 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5845 if (LHS && RHS) { // We have 2 user-defined types.
5846 if (LHS != RHS) {
5847 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005848 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005849 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005850 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005851 }
5852 else
5853 return true;
5854 }
5855 return false;
5856}
5857
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005858/// getIntersectionOfProtocols - This routine finds the intersection of set
5859/// of protocols inherited from two distinct objective-c pointer objects.
5860/// It is used to build composite qualifier list of the composite type of
5861/// the conditional expression involving two objective-c pointer objects.
5862static
5863void getIntersectionOfProtocols(ASTContext &Context,
5864 const ObjCObjectPointerType *LHSOPT,
5865 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005866 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005867
John McCall8b07ec22010-05-15 11:32:37 +00005868 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5869 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5870 assert(LHS->getInterface() && "LHS must have an interface base");
5871 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005872
5873 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5874 unsigned LHSNumProtocols = LHS->getNumProtocols();
5875 if (LHSNumProtocols > 0)
5876 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5877 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005878 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005879 Context.CollectInheritedProtocols(LHS->getInterface(),
5880 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005881 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5882 LHSInheritedProtocols.end());
5883 }
5884
5885 unsigned RHSNumProtocols = RHS->getNumProtocols();
5886 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00005887 ObjCProtocolDecl **RHSProtocols =
5888 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005889 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5890 if (InheritedProtocolSet.count(RHSProtocols[i]))
5891 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00005892 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005893 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005894 Context.CollectInheritedProtocols(RHS->getInterface(),
5895 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005896 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5897 RHSInheritedProtocols.begin(),
5898 E = RHSInheritedProtocols.end(); I != E; ++I)
5899 if (InheritedProtocolSet.count((*I)))
5900 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005901 }
5902}
5903
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005904/// areCommonBaseCompatible - Returns common base class of the two classes if
5905/// one found. Note that this is O'2 algorithm. But it will be called as the
5906/// last type comparison in a ?-exp of ObjC pointer types before a
5907/// warning is issued. So, its invokation is extremely rare.
5908QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00005909 const ObjCObjectPointerType *Lptr,
5910 const ObjCObjectPointerType *Rptr) {
5911 const ObjCObjectType *LHS = Lptr->getObjectType();
5912 const ObjCObjectType *RHS = Rptr->getObjectType();
5913 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5914 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00005915 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005916 return QualType();
5917
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005918 do {
John McCall8b07ec22010-05-15 11:32:37 +00005919 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005920 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005921 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00005922 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5923
5924 QualType Result = QualType(LHS, 0);
5925 if (!Protocols.empty())
5926 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5927 Result = getObjCObjectPointerType(Result);
5928 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005929 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005930 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005931
5932 return QualType();
5933}
5934
John McCall8b07ec22010-05-15 11:32:37 +00005935bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5936 const ObjCObjectType *RHS) {
5937 assert(LHS->getInterface() && "LHS is not an interface type");
5938 assert(RHS->getInterface() && "RHS is not an interface type");
5939
Chris Lattner49af6a42008-04-07 06:51:04 +00005940 // Verify that the base decls are compatible: the RHS must be a subclass of
5941 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00005942 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00005943 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005944
Chris Lattner49af6a42008-04-07 06:51:04 +00005945 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5946 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00005947 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00005948 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005949
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005950 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5951 // more detailed analysis is required.
5952 if (RHS->getNumProtocols() == 0) {
5953 // OK, if LHS is a superclass of RHS *and*
5954 // this superclass is assignment compatible with LHS.
5955 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005956 bool IsSuperClass =
5957 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5958 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005959 // OK if conversion of LHS to SuperClass results in narrowing of types
5960 // ; i.e., SuperClass may implement at least one of the protocols
5961 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5962 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5963 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005964 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005965 // If super class has no protocols, it is not a match.
5966 if (SuperClassInheritedProtocols.empty())
5967 return false;
5968
5969 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5970 LHSPE = LHS->qual_end();
5971 LHSPI != LHSPE; LHSPI++) {
5972 bool SuperImplementsProtocol = false;
5973 ObjCProtocolDecl *LHSProto = (*LHSPI);
5974
5975 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5976 SuperClassInheritedProtocols.begin(),
5977 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5978 ObjCProtocolDecl *SuperClassProto = (*I);
5979 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5980 SuperImplementsProtocol = true;
5981 break;
5982 }
5983 }
5984 if (!SuperImplementsProtocol)
5985 return false;
5986 }
5987 return true;
5988 }
5989 return false;
5990 }
Mike Stump11289f42009-09-09 15:08:12 +00005991
John McCall8b07ec22010-05-15 11:32:37 +00005992 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5993 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00005994 LHSPI != LHSPE; LHSPI++) {
5995 bool RHSImplementsProtocol = false;
5996
5997 // If the RHS doesn't implement the protocol on the left, the types
5998 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00005999 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6000 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00006001 RHSPI != RHSPE; RHSPI++) {
6002 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006003 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00006004 break;
6005 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006006 }
6007 // FIXME: For better diagnostics, consider passing back the protocol name.
6008 if (!RHSImplementsProtocol)
6009 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006010 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006011 // The RHS implements all protocols listed on the LHS.
6012 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006013}
6014
Steve Naroffb7605152009-02-12 17:52:19 +00006015bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6016 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006017 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6018 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006019
Steve Naroff7cae42b2009-07-10 23:34:53 +00006020 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006021 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006022
6023 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6024 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006025}
6026
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006027bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6028 return canAssignObjCInterfaces(
6029 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6030 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6031}
6032
Mike Stump11289f42009-09-09 15:08:12 +00006033/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006034/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006035/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006036/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006037bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6038 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006039 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006040 return hasSameType(LHS, RHS);
6041
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006042 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006043}
6044
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006045bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006046 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006047}
6048
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006049bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6050 return !mergeTypes(LHS, RHS, true).isNull();
6051}
6052
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006053/// mergeTransparentUnionType - if T is a transparent union type and a member
6054/// of T is compatible with SubType, return the merged type, else return
6055/// QualType()
6056QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6057 bool OfBlockPointer,
6058 bool Unqualified) {
6059 if (const RecordType *UT = T->getAsUnionType()) {
6060 RecordDecl *UD = UT->getDecl();
6061 if (UD->hasAttr<TransparentUnionAttr>()) {
6062 for (RecordDecl::field_iterator it = UD->field_begin(),
6063 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00006064 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006065 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6066 if (!MT.isNull())
6067 return MT;
6068 }
6069 }
6070 }
6071
6072 return QualType();
6073}
6074
6075/// mergeFunctionArgumentTypes - merge two types which appear as function
6076/// argument types
6077QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6078 bool OfBlockPointer,
6079 bool Unqualified) {
6080 // GNU extension: two types are compatible if they appear as a function
6081 // argument, one of the types is a transparent union type and the other
6082 // type is compatible with a union member
6083 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6084 Unqualified);
6085 if (!lmerge.isNull())
6086 return lmerge;
6087
6088 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6089 Unqualified);
6090 if (!rmerge.isNull())
6091 return rmerge;
6092
6093 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6094}
6095
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006096QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006097 bool OfBlockPointer,
6098 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006099 const FunctionType *lbase = lhs->getAs<FunctionType>();
6100 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006101 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6102 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006103 bool allLTypes = true;
6104 bool allRTypes = true;
6105
6106 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006107 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006108 if (OfBlockPointer) {
6109 QualType RHS = rbase->getResultType();
6110 QualType LHS = lbase->getResultType();
6111 bool UnqualifiedResult = Unqualified;
6112 if (!UnqualifiedResult)
6113 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006114 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006115 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006116 else
John McCall8c6b56f2010-12-15 01:06:38 +00006117 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6118 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006119 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006120
6121 if (Unqualified)
6122 retType = retType.getUnqualifiedType();
6123
6124 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6125 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6126 if (Unqualified) {
6127 LRetType = LRetType.getUnqualifiedType();
6128 RRetType = RRetType.getUnqualifiedType();
6129 }
6130
6131 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006132 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006133 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006134 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006135
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006136 // FIXME: double check this
6137 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6138 // rbase->getRegParmAttr() != 0 &&
6139 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006140 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6141 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006142
Douglas Gregor8c940862010-01-18 17:14:39 +00006143 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00006144 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00006145 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006146
John McCall8c6b56f2010-12-15 01:06:38 +00006147 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006148 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6149 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006150 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6151 return QualType();
6152
John McCall31168b02011-06-15 23:02:42 +00006153 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6154 return QualType();
6155
Fariborz Jahanian48c69102011-10-05 00:05:34 +00006156 // functypes which return are preferred over those that do not.
6157 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
6158 allLTypes = false;
6159 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
6160 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006161 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6162 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006163
John McCall31168b02011-06-15 23:02:42 +00006164 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006165
Eli Friedman47f77112008-08-22 00:56:42 +00006166 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006167 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6168 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006169 unsigned lproto_nargs = lproto->getNumArgs();
6170 unsigned rproto_nargs = rproto->getNumArgs();
6171
6172 // Compatible functions must have the same number of arguments
6173 if (lproto_nargs != rproto_nargs)
6174 return QualType();
6175
6176 // Variadic and non-variadic functions aren't compatible
6177 if (lproto->isVariadic() != rproto->isVariadic())
6178 return QualType();
6179
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006180 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6181 return QualType();
6182
Fariborz Jahanian97676972011-09-28 21:52:05 +00006183 if (LangOpts.ObjCAutoRefCount &&
6184 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6185 return QualType();
6186
Eli Friedman47f77112008-08-22 00:56:42 +00006187 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006188 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00006189 for (unsigned i = 0; i < lproto_nargs; i++) {
6190 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6191 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006192 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6193 OfBlockPointer,
6194 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006195 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006196
6197 if (Unqualified)
6198 argtype = argtype.getUnqualifiedType();
6199
Eli Friedman47f77112008-08-22 00:56:42 +00006200 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006201 if (Unqualified) {
6202 largtype = largtype.getUnqualifiedType();
6203 rargtype = rargtype.getUnqualifiedType();
6204 }
6205
Chris Lattner465fa322008-10-05 17:34:18 +00006206 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6207 allLTypes = false;
6208 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6209 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006210 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006211
Eli Friedman47f77112008-08-22 00:56:42 +00006212 if (allLTypes) return lhs;
6213 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006214
6215 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6216 EPI.ExtInfo = einfo;
6217 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006218 }
6219
6220 if (lproto) allRTypes = false;
6221 if (rproto) allLTypes = false;
6222
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006223 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006224 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006225 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006226 if (proto->isVariadic()) return QualType();
6227 // Check that the types are compatible with the types that
6228 // would result from default argument promotions (C99 6.7.5.3p15).
6229 // The only types actually affected are promotable integer
6230 // types and floats, which would be passed as a different
6231 // type depending on whether the prototype is visible.
6232 unsigned proto_nargs = proto->getNumArgs();
6233 for (unsigned i = 0; i < proto_nargs; ++i) {
6234 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00006235
6236 // Look at the promotion type of enum types, since that is the type used
6237 // to pass enum values.
6238 if (const EnumType *Enum = argTy->getAs<EnumType>())
6239 argTy = Enum->getDecl()->getPromotionType();
6240
Eli Friedman47f77112008-08-22 00:56:42 +00006241 if (argTy->isPromotableIntegerType() ||
6242 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6243 return QualType();
6244 }
6245
6246 if (allLTypes) return lhs;
6247 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006248
6249 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6250 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00006251 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006252 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006253 }
6254
6255 if (allLTypes) return lhs;
6256 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00006257 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00006258}
6259
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006260QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006261 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006262 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00006263 // C++ [expr]: If an expression initially has the type "reference to T", the
6264 // type is adjusted to "T" prior to any further analysis, the expression
6265 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006266 // expression is an lvalue unless the reference is an rvalue reference and
6267 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00006268 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6269 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006270
6271 if (Unqualified) {
6272 LHS = LHS.getUnqualifiedType();
6273 RHS = RHS.getUnqualifiedType();
6274 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00006275
Eli Friedman47f77112008-08-22 00:56:42 +00006276 QualType LHSCan = getCanonicalType(LHS),
6277 RHSCan = getCanonicalType(RHS);
6278
6279 // If two types are identical, they are compatible.
6280 if (LHSCan == RHSCan)
6281 return LHS;
6282
John McCall8ccfcb52009-09-24 19:53:00 +00006283 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006284 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6285 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00006286 if (LQuals != RQuals) {
6287 // If any of these qualifiers are different, we have a type
6288 // mismatch.
6289 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00006290 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6291 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00006292 return QualType();
6293
6294 // Exactly one GC qualifier difference is allowed: __strong is
6295 // okay if the other type has no GC qualifier but is an Objective
6296 // C object pointer (i.e. implicitly strong by default). We fix
6297 // this by pretending that the unqualified type was actually
6298 // qualified __strong.
6299 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6300 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6301 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6302
6303 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6304 return QualType();
6305
6306 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6307 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6308 }
6309 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6310 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6311 }
Eli Friedman47f77112008-08-22 00:56:42 +00006312 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00006313 }
6314
6315 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00006316
Eli Friedmandcca6332009-06-01 01:22:52 +00006317 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6318 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00006319
Chris Lattnerfd652912008-01-14 05:45:46 +00006320 // We want to consider the two function types to be the same for these
6321 // comparisons, just force one to the other.
6322 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6323 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00006324
6325 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00006326 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6327 LHSClass = Type::ConstantArray;
6328 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6329 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00006330
John McCall8b07ec22010-05-15 11:32:37 +00006331 // ObjCInterfaces are just specialized ObjCObjects.
6332 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6333 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6334
Nate Begemance4d7fc2008-04-18 23:10:10 +00006335 // Canonicalize ExtVector -> Vector.
6336 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6337 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00006338
Chris Lattner95554662008-04-07 05:43:21 +00006339 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006340 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00006341 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00006342 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00006343 // Compatibility is based on the underlying type, not the promotion
6344 // type.
John McCall9dd450b2009-09-21 23:43:11 +00006345 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006346 QualType TINT = ETy->getDecl()->getIntegerType();
6347 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006348 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006349 }
John McCall9dd450b2009-09-21 23:43:11 +00006350 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006351 QualType TINT = ETy->getDecl()->getIntegerType();
6352 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006353 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006354 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006355 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00006356 if (OfBlockPointer && !BlockReturnType) {
6357 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6358 return LHS;
6359 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6360 return RHS;
6361 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006362
Eli Friedman47f77112008-08-22 00:56:42 +00006363 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00006364 }
Eli Friedman47f77112008-08-22 00:56:42 +00006365
Steve Naroffc6edcbd2008-01-09 22:43:08 +00006366 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006367 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006368#define TYPE(Class, Base)
6369#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00006370#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006371#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6372#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6373#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00006374 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006375
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006376 case Type::LValueReference:
6377 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006378 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00006379 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006380
John McCall8b07ec22010-05-15 11:32:37 +00006381 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006382 case Type::IncompleteArray:
6383 case Type::VariableArray:
6384 case Type::FunctionProto:
6385 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00006386 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006387
Chris Lattnerfd652912008-01-14 05:45:46 +00006388 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00006389 {
6390 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006391 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6392 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006393 if (Unqualified) {
6394 LHSPointee = LHSPointee.getUnqualifiedType();
6395 RHSPointee = RHSPointee.getUnqualifiedType();
6396 }
6397 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6398 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006399 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00006400 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006401 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00006402 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006403 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006404 return getPointerType(ResultType);
6405 }
Steve Naroff68e167d2008-12-10 17:49:55 +00006406 case Type::BlockPointer:
6407 {
6408 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006409 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6410 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006411 if (Unqualified) {
6412 LHSPointee = LHSPointee.getUnqualifiedType();
6413 RHSPointee = RHSPointee.getUnqualifiedType();
6414 }
6415 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6416 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00006417 if (ResultType.isNull()) return QualType();
6418 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6419 return LHS;
6420 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6421 return RHS;
6422 return getBlockPointerType(ResultType);
6423 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00006424 case Type::Atomic:
6425 {
6426 // Merge two pointer types, while trying to preserve typedef info
6427 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6428 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6429 if (Unqualified) {
6430 LHSValue = LHSValue.getUnqualifiedType();
6431 RHSValue = RHSValue.getUnqualifiedType();
6432 }
6433 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6434 Unqualified);
6435 if (ResultType.isNull()) return QualType();
6436 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6437 return LHS;
6438 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6439 return RHS;
6440 return getAtomicType(ResultType);
6441 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006442 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00006443 {
6444 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6445 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6446 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6447 return QualType();
6448
6449 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6450 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006451 if (Unqualified) {
6452 LHSElem = LHSElem.getUnqualifiedType();
6453 RHSElem = RHSElem.getUnqualifiedType();
6454 }
6455
6456 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006457 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00006458 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6459 return LHS;
6460 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6461 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00006462 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6463 ArrayType::ArraySizeModifier(), 0);
6464 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6465 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006466 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6467 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00006468 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6469 return LHS;
6470 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6471 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006472 if (LVAT) {
6473 // FIXME: This isn't correct! But tricky to implement because
6474 // the array's size has to be the size of LHS, but the type
6475 // has to be different.
6476 return LHS;
6477 }
6478 if (RVAT) {
6479 // FIXME: This isn't correct! But tricky to implement because
6480 // the array's size has to be the size of RHS, but the type
6481 // has to be different.
6482 return RHS;
6483 }
Eli Friedman3e62c212008-08-22 01:48:21 +00006484 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6485 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00006486 return getIncompleteArrayType(ResultType,
6487 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006488 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006489 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006490 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006491 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006492 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00006493 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00006494 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006495 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00006496 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00006497 case Type::Complex:
6498 // Distinct complex types are incompatible.
6499 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006500 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00006501 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00006502 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6503 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00006504 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00006505 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00006506 case Type::ObjCObject: {
6507 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00006508 // FIXME: This should be type compatibility, e.g. whether
6509 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00006510 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6511 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6512 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00006513 return LHS;
6514
Eli Friedman47f77112008-08-22 00:56:42 +00006515 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00006516 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006517 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006518 if (OfBlockPointer) {
6519 if (canAssignObjCInterfacesInBlockPointer(
6520 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006521 RHS->getAs<ObjCObjectPointerType>(),
6522 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00006523 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006524 return QualType();
6525 }
John McCall9dd450b2009-09-21 23:43:11 +00006526 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6527 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006528 return LHS;
6529
Steve Naroffc68cfcf2008-12-10 22:14:21 +00006530 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00006531 }
Steve Naroff32e44c02007-10-15 20:41:53 +00006532 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006533
David Blaikie8a40f702012-01-17 06:56:22 +00006534 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00006535}
Ted Kremenekfc581a92007-10-31 17:10:13 +00006536
Fariborz Jahanian97676972011-09-28 21:52:05 +00006537bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6538 const FunctionProtoType *FromFunctionType,
6539 const FunctionProtoType *ToFunctionType) {
6540 if (FromFunctionType->hasAnyConsumedArgs() !=
6541 ToFunctionType->hasAnyConsumedArgs())
6542 return false;
6543 FunctionProtoType::ExtProtoInfo FromEPI =
6544 FromFunctionType->getExtProtoInfo();
6545 FunctionProtoType::ExtProtoInfo ToEPI =
6546 ToFunctionType->getExtProtoInfo();
6547 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6548 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6549 ArgIdx != NumArgs; ++ArgIdx) {
6550 if (FromEPI.ConsumedArguments[ArgIdx] !=
6551 ToEPI.ConsumedArguments[ArgIdx])
6552 return false;
6553 }
6554 return true;
6555}
6556
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006557/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6558/// 'RHS' attributes and returns the merged version; including for function
6559/// return types.
6560QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6561 QualType LHSCan = getCanonicalType(LHS),
6562 RHSCan = getCanonicalType(RHS);
6563 // If two types are identical, they are compatible.
6564 if (LHSCan == RHSCan)
6565 return LHS;
6566 if (RHSCan->isFunctionType()) {
6567 if (!LHSCan->isFunctionType())
6568 return QualType();
6569 QualType OldReturnType =
6570 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6571 QualType NewReturnType =
6572 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6573 QualType ResReturnType =
6574 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6575 if (ResReturnType.isNull())
6576 return QualType();
6577 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6578 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6579 // In either case, use OldReturnType to build the new function type.
6580 const FunctionType *F = LHS->getAs<FunctionType>();
6581 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00006582 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6583 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006584 QualType ResultType
6585 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006586 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006587 return ResultType;
6588 }
6589 }
6590 return QualType();
6591 }
6592
6593 // If the qualifiers are different, the types can still be merged.
6594 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6595 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6596 if (LQuals != RQuals) {
6597 // If any of these qualifiers are different, we have a type mismatch.
6598 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6599 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6600 return QualType();
6601
6602 // Exactly one GC qualifier difference is allowed: __strong is
6603 // okay if the other type has no GC qualifier but is an Objective
6604 // C object pointer (i.e. implicitly strong by default). We fix
6605 // this by pretending that the unqualified type was actually
6606 // qualified __strong.
6607 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6608 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6609 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6610
6611 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6612 return QualType();
6613
6614 if (GC_L == Qualifiers::Strong)
6615 return LHS;
6616 if (GC_R == Qualifiers::Strong)
6617 return RHS;
6618 return QualType();
6619 }
6620
6621 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6622 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6623 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6624 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6625 if (ResQT == LHSBaseQT)
6626 return LHS;
6627 if (ResQT == RHSBaseQT)
6628 return RHS;
6629 }
6630 return QualType();
6631}
6632
Chris Lattner4ba0cef2008-04-07 07:01:58 +00006633//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006634// Integer Predicates
6635//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00006636
Jay Foad39c79802011-01-12 09:06:06 +00006637unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00006638 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00006639 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00006640 if (T->isBooleanType())
6641 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00006642 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006643 return (unsigned)getTypeSize(T);
6644}
6645
6646QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006647 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00006648
6649 // Turn <4 x signed int> -> <4 x unsigned int>
6650 if (const VectorType *VTy = T->getAs<VectorType>())
6651 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00006652 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00006653
6654 // For enums, we return the unsigned version of the base type.
6655 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006656 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00006657
6658 const BuiltinType *BTy = T->getAs<BuiltinType>();
6659 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006660 switch (BTy->getKind()) {
6661 case BuiltinType::Char_S:
6662 case BuiltinType::SChar:
6663 return UnsignedCharTy;
6664 case BuiltinType::Short:
6665 return UnsignedShortTy;
6666 case BuiltinType::Int:
6667 return UnsignedIntTy;
6668 case BuiltinType::Long:
6669 return UnsignedLongTy;
6670 case BuiltinType::LongLong:
6671 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00006672 case BuiltinType::Int128:
6673 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006674 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006675 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006676 }
6677}
6678
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00006679ASTMutationListener::~ASTMutationListener() { }
6680
Chris Lattnerecd79c62009-06-14 00:45:47 +00006681
6682//===----------------------------------------------------------------------===//
6683// Builtin Type Computation
6684//===----------------------------------------------------------------------===//
6685
6686/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00006687/// pointer over the consumed characters. This returns the resultant type. If
6688/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6689/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6690/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006691///
6692/// RequiresICE is filled in on return to indicate whether the value is required
6693/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00006694static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00006695 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006696 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00006697 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00006698 // Modifiers.
6699 int HowLong = 0;
6700 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006701 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00006702
Chris Lattnerdc226c22010-10-01 22:42:38 +00006703 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00006704 bool Done = false;
6705 while (!Done) {
6706 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00006707 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00006708 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006709 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00006710 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006711 case 'S':
6712 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6713 assert(!Signed && "Can't use 'S' modifier multiple times!");
6714 Signed = true;
6715 break;
6716 case 'U':
6717 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6718 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6719 Unsigned = true;
6720 break;
6721 case 'L':
6722 assert(HowLong <= 2 && "Can't have LLLL modifier");
6723 ++HowLong;
6724 break;
6725 }
6726 }
6727
6728 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00006729
Chris Lattnerecd79c62009-06-14 00:45:47 +00006730 // Read the base type.
6731 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00006732 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006733 case 'v':
6734 assert(HowLong == 0 && !Signed && !Unsigned &&
6735 "Bad modifiers used with 'v'!");
6736 Type = Context.VoidTy;
6737 break;
6738 case 'f':
6739 assert(HowLong == 0 && !Signed && !Unsigned &&
6740 "Bad modifiers used with 'f'!");
6741 Type = Context.FloatTy;
6742 break;
6743 case 'd':
6744 assert(HowLong < 2 && !Signed && !Unsigned &&
6745 "Bad modifiers used with 'd'!");
6746 if (HowLong)
6747 Type = Context.LongDoubleTy;
6748 else
6749 Type = Context.DoubleTy;
6750 break;
6751 case 's':
6752 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6753 if (Unsigned)
6754 Type = Context.UnsignedShortTy;
6755 else
6756 Type = Context.ShortTy;
6757 break;
6758 case 'i':
6759 if (HowLong == 3)
6760 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6761 else if (HowLong == 2)
6762 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6763 else if (HowLong == 1)
6764 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6765 else
6766 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6767 break;
6768 case 'c':
6769 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6770 if (Signed)
6771 Type = Context.SignedCharTy;
6772 else if (Unsigned)
6773 Type = Context.UnsignedCharTy;
6774 else
6775 Type = Context.CharTy;
6776 break;
6777 case 'b': // boolean
6778 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6779 Type = Context.BoolTy;
6780 break;
6781 case 'z': // size_t.
6782 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6783 Type = Context.getSizeType();
6784 break;
6785 case 'F':
6786 Type = Context.getCFConstantStringType();
6787 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00006788 case 'G':
6789 Type = Context.getObjCIdType();
6790 break;
6791 case 'H':
6792 Type = Context.getObjCSelType();
6793 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006794 case 'a':
6795 Type = Context.getBuiltinVaListType();
6796 assert(!Type.isNull() && "builtin va list type not initialized!");
6797 break;
6798 case 'A':
6799 // This is a "reference" to a va_list; however, what exactly
6800 // this means depends on how va_list is defined. There are two
6801 // different kinds of va_list: ones passed by value, and ones
6802 // passed by reference. An example of a by-value va_list is
6803 // x86, where va_list is a char*. An example of by-ref va_list
6804 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6805 // we want this argument to be a char*&; for x86-64, we want
6806 // it to be a __va_list_tag*.
6807 Type = Context.getBuiltinVaListType();
6808 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006809 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00006810 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006811 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00006812 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006813 break;
6814 case 'V': {
6815 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006816 unsigned NumElements = strtoul(Str, &End, 10);
6817 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006818 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00006819
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006820 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6821 RequiresICE, false);
6822 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00006823
6824 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00006825 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00006826 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006827 break;
6828 }
Douglas Gregorfed66992012-06-07 18:08:25 +00006829 case 'E': {
6830 char *End;
6831
6832 unsigned NumElements = strtoul(Str, &End, 10);
6833 assert(End != Str && "Missing vector size");
6834
6835 Str = End;
6836
6837 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6838 false);
6839 Type = Context.getExtVectorType(ElementType, NumElements);
6840 break;
6841 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006842 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006843 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6844 false);
6845 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006846 Type = Context.getComplexType(ElementType);
6847 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00006848 }
6849 case 'Y' : {
6850 Type = Context.getPointerDiffType();
6851 break;
6852 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00006853 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00006854 Type = Context.getFILEType();
6855 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006856 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006857 return QualType();
6858 }
Mike Stump2adb4da2009-07-28 23:47:15 +00006859 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00006860 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00006861 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00006862 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00006863 else
6864 Type = Context.getjmp_bufType();
6865
Mike Stump2adb4da2009-07-28 23:47:15 +00006866 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006867 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00006868 return QualType();
6869 }
6870 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00006871 case 'K':
6872 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
6873 Type = Context.getucontext_tType();
6874
6875 if (Type.isNull()) {
6876 Error = ASTContext::GE_Missing_ucontext;
6877 return QualType();
6878 }
6879 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00006880 }
Mike Stump11289f42009-09-09 15:08:12 +00006881
Chris Lattnerdc226c22010-10-01 22:42:38 +00006882 // If there are modifiers and if we're allowed to parse them, go for it.
6883 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006884 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00006885 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006886 default: Done = true; --Str; break;
6887 case '*':
6888 case '&': {
6889 // Both pointers and references can have their pointee types
6890 // qualified with an address space.
6891 char *End;
6892 unsigned AddrSpace = strtoul(Str, &End, 10);
6893 if (End != Str && AddrSpace != 0) {
6894 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6895 Str = End;
6896 }
6897 if (c == '*')
6898 Type = Context.getPointerType(Type);
6899 else
6900 Type = Context.getLValueReferenceType(Type);
6901 break;
6902 }
6903 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6904 case 'C':
6905 Type = Type.withConst();
6906 break;
6907 case 'D':
6908 Type = Context.getVolatileType(Type);
6909 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00006910 case 'R':
6911 Type = Type.withRestrict();
6912 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006913 }
6914 }
Chris Lattner84733392010-10-01 07:13:18 +00006915
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006916 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00006917 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00006918
Chris Lattnerecd79c62009-06-14 00:45:47 +00006919 return Type;
6920}
6921
6922/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00006923QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006924 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00006925 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006926 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00006927
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006928 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00006929
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006930 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006931 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006932 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6933 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006934 if (Error != GE_None)
6935 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006936
6937 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6938
Chris Lattnerecd79c62009-06-14 00:45:47 +00006939 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006940 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006941 if (Error != GE_None)
6942 return QualType();
6943
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006944 // If this argument is required to be an IntegerConstantExpression and the
6945 // caller cares, fill in the bitmask we return.
6946 if (RequiresICE && IntegerConstantArgs)
6947 *IntegerConstantArgs |= 1 << ArgTypes.size();
6948
Chris Lattnerecd79c62009-06-14 00:45:47 +00006949 // Do array -> pointer decay. The builtin should use the decayed type.
6950 if (Ty->isArrayType())
6951 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00006952
Chris Lattnerecd79c62009-06-14 00:45:47 +00006953 ArgTypes.push_back(Ty);
6954 }
6955
6956 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6957 "'.' should only occur at end of builtin type list!");
6958
John McCall991eb4b2010-12-21 00:44:39 +00006959 FunctionType::ExtInfo EI;
6960 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6961
6962 bool Variadic = (TypeStr[0] == '.');
6963
6964 // We really shouldn't be making a no-proto type here, especially in C++.
6965 if (ArgTypes.empty() && Variadic)
6966 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00006967
John McCalldb40c7f2010-12-14 08:05:40 +00006968 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00006969 EPI.ExtInfo = EI;
6970 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00006971
6972 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006973}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00006974
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006975GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6976 GVALinkage External = GVA_StrongExternal;
6977
6978 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006979 switch (L) {
6980 case NoLinkage:
6981 case InternalLinkage:
6982 case UniqueExternalLinkage:
6983 return GVA_Internal;
6984
6985 case ExternalLinkage:
6986 switch (FD->getTemplateSpecializationKind()) {
6987 case TSK_Undeclared:
6988 case TSK_ExplicitSpecialization:
6989 External = GVA_StrongExternal;
6990 break;
6991
6992 case TSK_ExplicitInstantiationDefinition:
6993 return GVA_ExplicitTemplateInstantiation;
6994
6995 case TSK_ExplicitInstantiationDeclaration:
6996 case TSK_ImplicitInstantiation:
6997 External = GVA_TemplateInstantiation;
6998 break;
6999 }
7000 }
7001
7002 if (!FD->isInlined())
7003 return External;
7004
David Blaikiebbafb8a2012-03-11 07:00:24 +00007005 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007006 // GNU or C99 inline semantics. Determine whether this symbol should be
7007 // externally visible.
7008 if (FD->isInlineDefinitionExternallyVisible())
7009 return External;
7010
7011 // C99 inline semantics, where the symbol is not externally visible.
7012 return GVA_C99Inline;
7013 }
7014
7015 // C++0x [temp.explicit]p9:
7016 // [ Note: The intent is that an inline function that is the subject of
7017 // an explicit instantiation declaration will still be implicitly
7018 // instantiated when used so that the body can be considered for
7019 // inlining, but that no out-of-line copy of the inline function would be
7020 // generated in the translation unit. -- end note ]
7021 if (FD->getTemplateSpecializationKind()
7022 == TSK_ExplicitInstantiationDeclaration)
7023 return GVA_C99Inline;
7024
7025 return GVA_CXXInline;
7026}
7027
7028GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7029 // If this is a static data member, compute the kind of template
7030 // specialization. Otherwise, this variable is not part of a
7031 // template.
7032 TemplateSpecializationKind TSK = TSK_Undeclared;
7033 if (VD->isStaticDataMember())
7034 TSK = VD->getTemplateSpecializationKind();
7035
7036 Linkage L = VD->getLinkage();
David Blaikiebbafb8a2012-03-11 07:00:24 +00007037 if (L == ExternalLinkage && getLangOpts().CPlusPlus &&
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007038 VD->getType()->getLinkage() == UniqueExternalLinkage)
7039 L = UniqueExternalLinkage;
7040
7041 switch (L) {
7042 case NoLinkage:
7043 case InternalLinkage:
7044 case UniqueExternalLinkage:
7045 return GVA_Internal;
7046
7047 case ExternalLinkage:
7048 switch (TSK) {
7049 case TSK_Undeclared:
7050 case TSK_ExplicitSpecialization:
7051 return GVA_StrongExternal;
7052
7053 case TSK_ExplicitInstantiationDeclaration:
7054 llvm_unreachable("Variable should not be instantiated");
7055 // Fall through to treat this like any other instantiation.
7056
7057 case TSK_ExplicitInstantiationDefinition:
7058 return GVA_ExplicitTemplateInstantiation;
7059
7060 case TSK_ImplicitInstantiation:
7061 return GVA_TemplateInstantiation;
7062 }
7063 }
7064
David Blaikie8a40f702012-01-17 06:56:22 +00007065 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007066}
7067
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007068bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007069 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7070 if (!VD->isFileVarDecl())
7071 return false;
Argyrios Kyrtzidisa98e8612011-09-13 21:35:00 +00007072 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007073 return false;
7074
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007075 // Weak references don't produce any output by themselves.
7076 if (D->hasAttr<WeakRefAttr>())
7077 return false;
7078
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007079 // Aliases and used decls are required.
7080 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7081 return true;
7082
7083 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7084 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007085 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007086 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007087
7088 // Constructors and destructors are required.
7089 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7090 return true;
7091
7092 // The key function for a class is required.
7093 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7094 const CXXRecordDecl *RD = MD->getParent();
7095 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7096 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
7097 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7098 return true;
7099 }
7100 }
7101
7102 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7103
7104 // static, static inline, always_inline, and extern inline functions can
7105 // always be deferred. Normal inline functions can be deferred in C99/C++.
7106 // Implicit template instantiations can also be deferred in C++.
7107 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007108 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007109 return false;
7110 return true;
7111 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007112
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007113 const VarDecl *VD = cast<VarDecl>(D);
7114 assert(VD->isFileVarDecl() && "Expected file scoped var");
7115
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007116 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7117 return false;
7118
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007119 // Structs that have non-trivial constructors or destructors are required.
7120
7121 // FIXME: Handle references.
Alexis Huntf479f1b2011-05-09 18:22:59 +00007122 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007123 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
7124 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Alexis Huntf479f1b2011-05-09 18:22:59 +00007125 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
7126 RD->hasTrivialCopyConstructor() &&
7127 RD->hasTrivialMoveConstructor() &&
7128 RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007129 return true;
7130 }
7131 }
7132
7133 GVALinkage L = GetGVALinkageForVariable(VD);
7134 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
7135 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
7136 return false;
7137 }
7138
7139 return true;
7140}
Charles Davis53c59df2010-08-16 03:33:14 +00007141
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007142CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davis99202b32010-11-09 18:04:24 +00007143 // Pass through to the C++ ABI object
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007144 return ABI->getDefaultMethodCallConv(isVariadic);
7145}
7146
7147CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
7148 if (CC == CC_C && !LangOpts.MRTD && getTargetInfo().getCXXABI() != CXXABI_Microsoft)
7149 return CC_Default;
7150 return CC;
Charles Davis99202b32010-11-09 18:04:24 +00007151}
7152
Jay Foad39c79802011-01-12 09:06:06 +00007153bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007154 // Pass through to the C++ ABI object
7155 return ABI->isNearlyEmpty(RD);
7156}
7157
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007158MangleContext *ASTContext::createMangleContext() {
Douglas Gregore8bbc122011-09-02 00:18:52 +00007159 switch (Target->getCXXABI()) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007160 case CXXABI_ARM:
7161 case CXXABI_Itanium:
7162 return createItaniumMangleContext(*this, getDiagnostics());
7163 case CXXABI_Microsoft:
7164 return createMicrosoftMangleContext(*this, getDiagnostics());
7165 }
David Blaikie83d382b2011-09-23 05:06:16 +00007166 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007167}
7168
Charles Davis53c59df2010-08-16 03:33:14 +00007169CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007170
7171size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00007172 return ASTRecordLayouts.getMemorySize()
7173 + llvm::capacity_in_bytes(ObjCLayouts)
7174 + llvm::capacity_in_bytes(KeyFunctions)
7175 + llvm::capacity_in_bytes(ObjCImpls)
7176 + llvm::capacity_in_bytes(BlockVarCopyInits)
7177 + llvm::capacity_in_bytes(DeclAttrs)
7178 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7179 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7180 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7181 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7182 + llvm::capacity_in_bytes(OverriddenMethods)
7183 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007184 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00007185 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007186}
Ted Kremenek540017e2011-10-06 05:00:56 +00007187
Douglas Gregor63798542012-02-20 19:44:39 +00007188unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7189 CXXRecordDecl *Lambda = CallOperator->getParent();
7190 return LambdaMangleContexts[Lambda->getDeclContext()]
7191 .getManglingNumber(CallOperator);
7192}
7193
7194
Ted Kremenek540017e2011-10-06 05:00:56 +00007195void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7196 ParamIndices[D] = index;
7197}
7198
7199unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7200 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7201 assert(I != ParamIndices.end() &&
7202 "ParmIndices lacks entry set by ParmVarDecl");
7203 return I->second;
7204}