blob: 0ff0e35a433f8e840ed7927a3868a64ee9cdd799 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyckbdc601b2009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Dmitri Gribenko1abee642012-08-02 17:39:44 +000016#include "clang/AST/Comment.h"
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +000017#include "clang/AST/CommentLexer.h"
18#include "clang/AST/CommentSema.h"
19#include "clang/AST/CommentParser.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000020#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000021#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000022#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +000023#include "clang/AST/TypeLoc.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000024#include "clang/AST/Expr.h"
John McCallea1471e2010-05-20 01:18:31 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000026#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +000027#include "clang/AST/ASTMutationListener.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000028#include "clang/AST/RecordLayout.h"
Peter Collingbourne14110472011-01-13 18:57:25 +000029#include "clang/AST/Mangle.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000030#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000031#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000032#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000033#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000034#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000035#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000036#include "llvm/Support/raw_ostream.h"
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +000037#include "llvm/Support/Capacity.h"
Charles Davis071cc7d2010-08-16 03:33:14 +000038#include "CXXABI.h"
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +000039#include <map>
Anders Carlsson29445a02009-07-18 21:19:52 +000040
Reid Spencer5f016e22007-07-11 17:01:13 +000041using namespace clang;
42
Douglas Gregor18274032010-07-03 00:47:00 +000043unsigned ASTContext::NumImplicitDefaultConstructors;
44unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregor22584312010-07-02 23:41:54 +000045unsigned ASTContext::NumImplicitCopyConstructors;
46unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000047unsigned ASTContext::NumImplicitMoveConstructors;
48unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregora376d102010-07-02 21:50:04 +000049unsigned ASTContext::NumImplicitCopyAssignmentOperators;
50unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000051unsigned ASTContext::NumImplicitMoveAssignmentOperators;
52unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor4923aa22010-07-02 20:37:36 +000053unsigned ASTContext::NumImplicitDestructors;
54unsigned ASTContext::NumImplicitDestructorsDeclared;
55
Reid Spencer5f016e22007-07-11 17:01:13 +000056enum FloatingRank {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +000057 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Reid Spencer5f016e22007-07-11 17:01:13 +000058};
59
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +000060RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +000061 if (!CommentsLoaded && ExternalSource) {
62 ExternalSource->ReadComments();
63 CommentsLoaded = true;
64 }
65
66 assert(D);
67
Dmitri Gribenkoc3fee352012-06-28 16:19:39 +000068 // User can not attach documentation to implicit declarations.
69 if (D->isImplicit())
70 return NULL;
71
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +000072 // TODO: handle comments for function parameters properly.
73 if (isa<ParmVarDecl>(D))
74 return NULL;
75
Dmitri Gribenko96b09862012-07-31 22:37:06 +000076 // TODO: we could look up template parameter documentation in the template
77 // documentation.
78 if (isa<TemplateTypeParmDecl>(D) ||
79 isa<NonTypeTemplateParmDecl>(D) ||
80 isa<TemplateTemplateParmDecl>(D))
81 return NULL;
82
Dmitri Gribenko811c8202012-07-06 18:19:34 +000083 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +000084
85 // If there are no comments anywhere, we won't find anything.
86 if (RawComments.empty())
87 return NULL;
88
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +000089 // Find declaration location.
90 // For Objective-C declarations we generally don't expect to have multiple
91 // declarators, thus use declaration starting location as the "declaration
92 // location".
93 // For all other declarations multiple declarators are used quite frequently,
94 // so we use the location of the identifier as the "declaration location".
95 SourceLocation DeclLoc;
96 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko96b09862012-07-31 22:37:06 +000097 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +000098 isa<RedeclarableTemplateDecl>(D) ||
99 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000100 DeclLoc = D->getLocStart();
101 else
102 DeclLoc = D->getLocation();
103
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000104 // If the declaration doesn't map directly to a location in a file, we
105 // can't find the comment.
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000106 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
107 return NULL;
108
109 // Find the comment that occurs just after this declaration.
Dmitri Gribenkoa444f182012-07-17 22:01:09 +0000110 ArrayRef<RawComment *>::iterator Comment;
111 {
112 // When searching for comments during parsing, the comment we are looking
113 // for is usually among the last two comments we parsed -- check them
114 // first.
115 RawComment CommentAtDeclLoc(SourceMgr, SourceRange(DeclLoc));
116 BeforeThanCompare<RawComment> Compare(SourceMgr);
117 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
118 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
119 if (!Found && RawComments.size() >= 2) {
120 MaybeBeforeDecl--;
121 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
122 }
123
124 if (Found) {
125 Comment = MaybeBeforeDecl + 1;
126 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
127 &CommentAtDeclLoc, Compare));
128 } else {
129 // Slow path.
130 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
131 &CommentAtDeclLoc, Compare);
132 }
133 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000134
135 // Decompose the location for the declaration and find the beginning of the
136 // file buffer.
137 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
138
139 // First check whether we have a trailing comment.
140 if (Comment != RawComments.end() &&
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000141 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Dmitri Gribenko9c006762012-07-06 23:27:33 +0000142 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D))) {
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000143 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000144 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000145 // Check that Doxygen trailing comment comes after the declaration, starts
146 // on the same line and in the same file as the declaration.
147 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
148 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
149 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
150 CommentBeginDecomp.second)) {
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000151 return *Comment;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000152 }
153 }
154
155 // The comment just after the declaration was not a trailing comment.
156 // Let's look at the previous comment.
157 if (Comment == RawComments.begin())
158 return NULL;
159 --Comment;
160
161 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000162 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000163 return NULL;
164
165 // Decompose the end of the comment.
166 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000167 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000168
169 // If the comment and the declaration aren't in the same file, then they
170 // aren't related.
171 if (DeclLocDecomp.first != CommentEndDecomp.first)
172 return NULL;
173
174 // Get the corresponding buffer.
175 bool Invalid = false;
176 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
177 &Invalid).data();
178 if (Invalid)
179 return NULL;
180
181 // Extract text between the comment and declaration.
182 StringRef Text(Buffer + CommentEndDecomp.second,
183 DeclLocDecomp.second - CommentEndDecomp.second);
184
Dmitri Gribenko8bdb58a2012-06-27 23:43:37 +0000185 // There should be no other declarations or preprocessor directives between
186 // comment and declaration.
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000187 if (Text.find_first_of(",;{}#@") != StringRef::npos)
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000188 return NULL;
189
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000190 return *Comment;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000191}
192
193const RawComment *ASTContext::getRawCommentForDecl(const Decl *D) const {
194 // Check whether we have cached a comment string for this declaration
195 // already.
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000196 llvm::DenseMap<const Decl *, RawAndParsedComment>::iterator Pos
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000197 = DeclComments.find(D);
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000198 if (Pos != DeclComments.end()) {
199 RawAndParsedComment C = Pos->second;
200 return C.first;
201 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000202
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +0000203 RawComment *RC = getRawCommentForDeclNoCache(D);
Dmitri Gribenko8376f592012-06-28 16:25:36 +0000204 // If we found a comment, it should be a documentation comment.
205 assert(!RC || RC->isDocumentation());
Dmitri Gribenko9bf997e2012-07-06 15:40:08 +0000206 DeclComments[D] =
207 RawAndParsedComment(RC, static_cast<comments::FullComment *>(NULL));
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +0000208 if (RC)
209 RC->setAttached();
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000210 return RC;
211}
212
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000213comments::FullComment *ASTContext::getCommentForDecl(const Decl *D) const {
214 llvm::DenseMap<const Decl *, RawAndParsedComment>::iterator Pos
215 = DeclComments.find(D);
216 const RawComment *RC;
217 if (Pos != DeclComments.end()) {
218 RawAndParsedComment C = Pos->second;
219 if (comments::FullComment *FC = C.second)
220 return FC;
221 RC = C.first;
222 } else
223 RC = getRawCommentForDecl(D);
224
225 if (!RC)
226 return NULL;
227
228 const StringRef RawText = RC->getRawText(SourceMgr);
Dmitri Gribenko477a9f52012-07-27 20:37:06 +0000229 comments::Lexer L(getAllocator(),
230 RC->getSourceRange().getBegin(), comments::CommentOptions(),
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000231 RawText.begin(), RawText.end());
232
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +0000233 comments::Sema S(getAllocator(), getSourceManager(), getDiagnostics());
234 S.setDecl(D);
235 comments::Parser P(L, S, getAllocator(), getSourceManager(),
236 getDiagnostics());
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000237
238 comments::FullComment *FC = P.parseFullComment();
239 DeclComments[D].second = FC;
240 return FC;
241}
242
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000243void
244ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
245 TemplateTemplateParmDecl *Parm) {
246 ID.AddInteger(Parm->getDepth());
247 ID.AddInteger(Parm->getPosition());
Douglas Gregor61c4d282011-01-05 15:48:55 +0000248 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000249
250 TemplateParameterList *Params = Parm->getTemplateParameters();
251 ID.AddInteger(Params->size());
252 for (TemplateParameterList::const_iterator P = Params->begin(),
253 PEnd = Params->end();
254 P != PEnd; ++P) {
255 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
256 ID.AddInteger(0);
257 ID.AddBoolean(TTP->isParameterPack());
258 continue;
259 }
260
261 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
262 ID.AddInteger(1);
Douglas Gregor61c4d282011-01-05 15:48:55 +0000263 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000264 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000265 if (NTTP->isExpandedParameterPack()) {
266 ID.AddBoolean(true);
267 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000268 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
269 QualType T = NTTP->getExpansionType(I);
270 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
271 }
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000272 } else
273 ID.AddBoolean(false);
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000274 continue;
275 }
276
277 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
278 ID.AddInteger(2);
279 Profile(ID, TTP);
280 }
281}
282
283TemplateTemplateParmDecl *
284ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad4ba2a172011-01-12 09:06:06 +0000285 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000286 // Check if we already have a canonical template template parameter.
287 llvm::FoldingSetNodeID ID;
288 CanonicalTemplateTemplateParm::Profile(ID, TTP);
289 void *InsertPos = 0;
290 CanonicalTemplateTemplateParm *Canonical
291 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
292 if (Canonical)
293 return Canonical->getParam();
294
295 // Build a canonical template parameter list.
296 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000297 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000298 CanonParams.reserve(Params->size());
299 for (TemplateParameterList::const_iterator P = Params->begin(),
300 PEnd = Params->end();
301 P != PEnd; ++P) {
302 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
303 CanonParams.push_back(
304 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000305 SourceLocation(),
306 SourceLocation(),
307 TTP->getDepth(),
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000308 TTP->getIndex(), 0, false,
309 TTP->isParameterPack()));
310 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000311 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
312 QualType T = getCanonicalType(NTTP->getType());
313 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
314 NonTypeTemplateParmDecl *Param;
315 if (NTTP->isExpandedParameterPack()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000316 SmallVector<QualType, 2> ExpandedTypes;
317 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000318 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
319 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
320 ExpandedTInfos.push_back(
321 getTrivialTypeSourceInfo(ExpandedTypes.back()));
322 }
323
324 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000325 SourceLocation(),
326 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000327 NTTP->getDepth(),
328 NTTP->getPosition(), 0,
329 T,
330 TInfo,
331 ExpandedTypes.data(),
332 ExpandedTypes.size(),
333 ExpandedTInfos.data());
334 } else {
335 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000336 SourceLocation(),
337 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000338 NTTP->getDepth(),
339 NTTP->getPosition(), 0,
340 T,
341 NTTP->isParameterPack(),
342 TInfo);
343 }
344 CanonParams.push_back(Param);
345
346 } else
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000347 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
348 cast<TemplateTemplateParmDecl>(*P)));
349 }
350
351 TemplateTemplateParmDecl *CanonTTP
352 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
353 SourceLocation(), TTP->getDepth(),
Douglas Gregor61c4d282011-01-05 15:48:55 +0000354 TTP->getPosition(),
355 TTP->isParameterPack(),
356 0,
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000357 TemplateParameterList::Create(*this, SourceLocation(),
358 SourceLocation(),
359 CanonParams.data(),
360 CanonParams.size(),
361 SourceLocation()));
362
363 // Get the new insert position for the node we care about.
364 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
365 assert(Canonical == 0 && "Shouldn't be in the map!");
366 (void)Canonical;
367
368 // Create the canonical template template parameter entry.
369 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
370 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
371 return CanonTTP;
372}
373
Charles Davis071cc7d2010-08-16 03:33:14 +0000374CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000375 if (!LangOpts.CPlusPlus) return 0;
376
Charles Davis20cf7172010-08-19 02:18:14 +0000377 switch (T.getCXXABI()) {
John McCallee79a4c2010-08-21 22:46:04 +0000378 case CXXABI_ARM:
379 return CreateARMCXXABI(*this);
380 case CXXABI_Itanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000381 return CreateItaniumCXXABI(*this);
Charles Davis20cf7172010-08-19 02:18:14 +0000382 case CXXABI_Microsoft:
383 return CreateMicrosoftCXXABI(*this);
384 }
David Blaikie7530c032012-01-17 06:56:22 +0000385 llvm_unreachable("Invalid CXXABI type!");
Charles Davis071cc7d2010-08-16 03:33:14 +0000386}
387
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000388static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000389 const LangOptions &LOpts) {
390 if (LOpts.FakeAddressSpaceMap) {
391 // The fake address space map must have a distinct entry for each
392 // language-specific address space.
393 static const unsigned FakeAddrSpaceMap[] = {
394 1, // opencl_global
395 2, // opencl_local
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +0000396 3, // opencl_constant
397 4, // cuda_device
398 5, // cuda_constant
399 6 // cuda_shared
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000400 };
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000401 return &FakeAddrSpaceMap;
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000402 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000403 return &T.getAddressSpaceMap();
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000404 }
405}
406
Douglas Gregor3e3cd932011-09-01 20:23:19 +0000407ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000408 const TargetInfo *t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000409 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000410 Builtin::Context &builtins,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000411 unsigned size_reserve,
412 bool DelayInitialization)
413 : FunctionProtoTypes(this_()),
414 TemplateSpecializationTypes(this_()),
415 DependentTemplateSpecializationTypes(this_()),
416 SubstTemplateTemplateParmPacks(this_()),
417 GlobalNestedNameSpecifier(0),
418 Int128Decl(0), UInt128Decl(0),
Meador Ingec5613b22012-06-16 03:34:49 +0000419 BuiltinVaListDecl(0),
Douglas Gregora6ea10e2012-01-17 18:09:05 +0000420 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Douglas Gregore97179c2011-09-08 01:46:34 +0000421 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000422 FILEDecl(0),
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +0000423 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
424 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
425 cudaConfigureCallDecl(0),
Douglas Gregore6649772011-12-03 00:30:27 +0000426 NullTypeSourceInfo(QualType()),
427 FirstLocalImport(), LastLocalImport(),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000428 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor30c42402011-09-27 22:38:19 +0000429 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000430 Idents(idents), Selectors(sels),
431 BuiltinInfo(builtins),
432 DeclarationNames(*this),
Douglas Gregor30c42402011-09-27 22:38:19 +0000433 ExternalSource(0), Listener(0),
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000434 Comments(SM), CommentsLoaded(false),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000435 LastSDM(0, 0),
436 UniqueBlockByRefTypeID(0)
437{
Mike Stump1eb44332009-09-09 15:08:12 +0000438 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000439 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000440
441 if (!DelayInitialization) {
442 assert(t && "No target supplied for ASTContext initialization");
443 InitBuiltinTypes(*t);
444 }
Daniel Dunbare91593e2008-08-11 04:54:23 +0000445}
446
Reid Spencer5f016e22007-07-11 17:01:13 +0000447ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000448 // Release the DenseMaps associated with DeclContext objects.
449 // FIXME: Is this the ideal solution?
450 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000451
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000452 // Call all of the deallocation functions.
453 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
454 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor00545312010-05-23 18:26:36 +0000455
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000456 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000457 // because they can contain DenseMaps.
458 for (llvm::DenseMap<const ObjCContainerDecl*,
459 const ASTRecordLayout*>::iterator
460 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
461 // Increment in loop to prevent using deallocated memory.
462 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
463 R->Destroy(*this);
464
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000465 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
466 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
467 // Increment in loop to prevent using deallocated memory.
468 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
469 R->Destroy(*this);
470 }
Douglas Gregor63200642010-08-30 16:49:28 +0000471
472 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
473 AEnd = DeclAttrs.end();
474 A != AEnd; ++A)
475 A->second->~AttrVec();
476}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000477
Douglas Gregor00545312010-05-23 18:26:36 +0000478void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
479 Deallocations.push_back(std::make_pair(Callback, Data));
480}
481
Mike Stump1eb44332009-09-09 15:08:12 +0000482void
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000483ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000484 ExternalSource.reset(Source.take());
485}
486
Reid Spencer5f016e22007-07-11 17:01:13 +0000487void ASTContext::PrintStats() const {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000488 llvm::errs() << "\n*** AST Context Stats:\n";
489 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000490
Douglas Gregordbe833d2009-05-26 14:40:08 +0000491 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000492#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000493#define ABSTRACT_TYPE(Name, Parent)
494#include "clang/AST/TypeNodes.def"
495 0 // Extra
496 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000497
Reid Spencer5f016e22007-07-11 17:01:13 +0000498 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
499 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000500 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000501 }
502
Douglas Gregordbe833d2009-05-26 14:40:08 +0000503 unsigned Idx = 0;
504 unsigned TotalBytes = 0;
505#define TYPE(Name, Parent) \
506 if (counts[Idx]) \
Chandler Carruthcd92a652011-07-04 05:32:14 +0000507 llvm::errs() << " " << counts[Idx] << " " << #Name \
508 << " types\n"; \
Douglas Gregordbe833d2009-05-26 14:40:08 +0000509 TotalBytes += counts[Idx] * sizeof(Name##Type); \
510 ++Idx;
511#define ABSTRACT_TYPE(Name, Parent)
512#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000513
Chandler Carruthcd92a652011-07-04 05:32:14 +0000514 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
515
Douglas Gregor4923aa22010-07-02 20:37:36 +0000516 // Implicit special member functions.
Chandler Carruthcd92a652011-07-04 05:32:14 +0000517 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
518 << NumImplicitDefaultConstructors
519 << " implicit default constructors created\n";
520 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
521 << NumImplicitCopyConstructors
522 << " implicit copy constructors created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000523 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000524 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
525 << NumImplicitMoveConstructors
526 << " implicit move constructors created\n";
527 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
528 << NumImplicitCopyAssignmentOperators
529 << " implicit copy assignment operators created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000530 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000531 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
532 << NumImplicitMoveAssignmentOperators
533 << " implicit move assignment operators created\n";
534 llvm::errs() << NumImplicitDestructorsDeclared << "/"
535 << NumImplicitDestructors
536 << " implicit destructors created\n";
537
Douglas Gregor2cf26342009-04-09 22:27:44 +0000538 if (ExternalSource.get()) {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000539 llvm::errs() << "\n";
Douglas Gregor2cf26342009-04-09 22:27:44 +0000540 ExternalSource->PrintStats();
541 }
Chandler Carruthcd92a652011-07-04 05:32:14 +0000542
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000543 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000544}
545
Douglas Gregor772eeae2011-08-12 06:49:56 +0000546TypedefDecl *ASTContext::getInt128Decl() const {
547 if (!Int128Decl) {
548 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
549 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
550 getTranslationUnitDecl(),
551 SourceLocation(),
552 SourceLocation(),
553 &Idents.get("__int128_t"),
554 TInfo);
555 }
556
557 return Int128Decl;
558}
559
560TypedefDecl *ASTContext::getUInt128Decl() const {
561 if (!UInt128Decl) {
562 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
563 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
564 getTranslationUnitDecl(),
565 SourceLocation(),
566 SourceLocation(),
567 &Idents.get("__uint128_t"),
568 TInfo);
569 }
570
571 return UInt128Decl;
572}
Reid Spencer5f016e22007-07-11 17:01:13 +0000573
John McCalle27ec8a2009-10-23 23:03:21 +0000574void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000575 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000576 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000577 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000578}
579
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000580void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
581 assert((!this->Target || this->Target == &Target) &&
582 "Incorrect target reinitialization");
Reid Spencer5f016e22007-07-11 17:01:13 +0000583 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000584
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000585 this->Target = &Target;
586
587 ABI.reset(createCXXABI(Target));
588 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
589
Reid Spencer5f016e22007-07-11 17:01:13 +0000590 // C99 6.2.5p19.
591 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000592
Reid Spencer5f016e22007-07-11 17:01:13 +0000593 // C99 6.2.5p2.
594 InitBuiltinType(BoolTy, BuiltinType::Bool);
595 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000596 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000597 InitBuiltinType(CharTy, BuiltinType::Char_S);
598 else
599 InitBuiltinType(CharTy, BuiltinType::Char_U);
600 // C99 6.2.5p4.
601 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
602 InitBuiltinType(ShortTy, BuiltinType::Short);
603 InitBuiltinType(IntTy, BuiltinType::Int);
604 InitBuiltinType(LongTy, BuiltinType::Long);
605 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000606
Reid Spencer5f016e22007-07-11 17:01:13 +0000607 // C99 6.2.5p6.
608 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
609 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
610 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
611 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
612 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000613
Reid Spencer5f016e22007-07-11 17:01:13 +0000614 // C99 6.2.5p10.
615 InitBuiltinType(FloatTy, BuiltinType::Float);
616 InitBuiltinType(DoubleTy, BuiltinType::Double);
617 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000618
Chris Lattner2df9ced2009-04-30 02:43:43 +0000619 // GNU extension, 128-bit integers.
620 InitBuiltinType(Int128Ty, BuiltinType::Int128);
621 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
622
Chris Lattner3f59c972010-12-25 23:25:43 +0000623 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedmand3d77cd2011-04-30 19:24:24 +0000624 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattner3f59c972010-12-25 23:25:43 +0000625 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
626 else // -fshort-wchar makes wchar_t be unsigned.
627 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
628 } else // C99
Chris Lattner3a250322009-02-26 23:43:47 +0000629 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000630
James Molloy392da482012-05-04 10:55:22 +0000631 WIntTy = getFromTargetType(Target.getWIntType());
632
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000633 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
634 InitBuiltinType(Char16Ty, BuiltinType::Char16);
635 else // C99
636 Char16Ty = getFromTargetType(Target.getChar16Type());
637
638 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
639 InitBuiltinType(Char32Ty, BuiltinType::Char32);
640 else // C99
641 Char32Ty = getFromTargetType(Target.getChar32Type());
642
Douglas Gregor898574e2008-12-05 23:32:09 +0000643 // Placeholder type for type-dependent expressions whose type is
644 // completely unknown. No code should ever check a type against
645 // DependentTy and users should never see it; however, it is here to
646 // help diagnose failures to properly check for type-dependent
647 // expressions.
648 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000649
John McCall2a984ca2010-10-12 00:20:44 +0000650 // Placeholder type for functions.
651 InitBuiltinType(OverloadTy, BuiltinType::Overload);
652
John McCall864c0412011-04-26 20:42:42 +0000653 // Placeholder type for bound members.
654 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
655
John McCall3c3b7f92011-10-25 17:37:35 +0000656 // Placeholder type for pseudo-objects.
657 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
658
John McCall1de4d4e2011-04-07 08:22:57 +0000659 // "any" type; useful for debugger-like clients.
660 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
661
John McCall0ddaeb92011-10-17 18:09:15 +0000662 // Placeholder type for unbridged ARC casts.
663 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
664
Reid Spencer5f016e22007-07-11 17:01:13 +0000665 // C99 6.2.5p11.
666 FloatComplexTy = getComplexType(FloatTy);
667 DoubleComplexTy = getComplexType(DoubleTy);
668 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000669
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000670 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000671 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
672 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000673 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000674
675 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian93a49942012-04-16 21:03:30 +0000676 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
677 SignedCharTy : BoolTy);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000678
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000679 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000680
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000681 // void * type
682 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000683
684 // nullptr type (C++0x 2.14.7)
685 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000686
687 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
688 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingefb40e3f2012-07-01 15:57:25 +0000689
690 // Builtin type used to help define __builtin_va_list.
691 VaListTagTy = QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000692}
693
David Blaikied6471f72011-09-25 23:23:43 +0000694DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000695 return SourceMgr.getDiagnostics();
696}
697
Douglas Gregor63200642010-08-30 16:49:28 +0000698AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
699 AttrVec *&Result = DeclAttrs[D];
700 if (!Result) {
701 void *Mem = Allocate(sizeof(AttrVec));
702 Result = new (Mem) AttrVec;
703 }
704
705 return *Result;
706}
707
708/// \brief Erase the attributes corresponding to the given declaration.
709void ASTContext::eraseDeclAttrs(const Decl *D) {
710 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
711 if (Pos != DeclAttrs.end()) {
712 Pos->second->~AttrVec();
713 DeclAttrs.erase(Pos);
714 }
715}
716
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000717MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000718ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000719 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000720 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000721 = InstantiatedFromStaticDataMember.find(Var);
722 if (Pos == InstantiatedFromStaticDataMember.end())
723 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000724
Douglas Gregor7caa6822009-07-24 20:34:43 +0000725 return Pos->second;
726}
727
Mike Stump1eb44332009-09-09 15:08:12 +0000728void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000729ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000730 TemplateSpecializationKind TSK,
731 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000732 assert(Inst->isStaticDataMember() && "Not a static data member");
733 assert(Tmpl->isStaticDataMember() && "Not a static data member");
734 assert(!InstantiatedFromStaticDataMember[Inst] &&
735 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000736 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000737 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000738}
739
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000740FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
741 const FunctionDecl *FD){
742 assert(FD && "Specialization is 0");
743 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000744 = ClassScopeSpecializationPattern.find(FD);
745 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000746 return 0;
747
748 return Pos->second;
749}
750
751void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
752 FunctionDecl *Pattern) {
753 assert(FD && "Specialization is 0");
754 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000755 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000756}
757
John McCall7ba107a2009-11-18 02:36:19 +0000758NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000759ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000760 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000761 = InstantiatedFromUsingDecl.find(UUD);
762 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000763 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000764
Anders Carlsson0d8df782009-08-29 19:37:28 +0000765 return Pos->second;
766}
767
768void
John McCalled976492009-12-04 22:46:56 +0000769ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
770 assert((isa<UsingDecl>(Pattern) ||
771 isa<UnresolvedUsingValueDecl>(Pattern) ||
772 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
773 "pattern decl is not a using decl");
774 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
775 InstantiatedFromUsingDecl[Inst] = Pattern;
776}
777
778UsingShadowDecl *
779ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
780 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
781 = InstantiatedFromUsingShadowDecl.find(Inst);
782 if (Pos == InstantiatedFromUsingShadowDecl.end())
783 return 0;
784
785 return Pos->second;
786}
787
788void
789ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
790 UsingShadowDecl *Pattern) {
791 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
792 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000793}
794
Anders Carlssond8b285f2009-09-01 04:26:58 +0000795FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
796 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
797 = InstantiatedFromUnnamedFieldDecl.find(Field);
798 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
799 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000800
Anders Carlssond8b285f2009-09-01 04:26:58 +0000801 return Pos->second;
802}
803
804void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
805 FieldDecl *Tmpl) {
806 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
807 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
808 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
809 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000810
Anders Carlssond8b285f2009-09-01 04:26:58 +0000811 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
812}
813
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000814bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
815 const FieldDecl *LastFD) const {
816 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000817 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000818}
819
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000820bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
821 const FieldDecl *LastFD) const {
822 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000823 FD->getBitWidthValue(*this) == 0 &&
824 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000825}
826
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000827bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
828 const FieldDecl *LastFD) const {
829 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000830 FD->getBitWidthValue(*this) &&
831 LastFD->getBitWidthValue(*this));
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000832}
833
Chad Rosierdd7fddb2011-08-04 23:34:15 +0000834bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000835 const FieldDecl *LastFD) const {
836 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000837 LastFD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000838}
839
Chad Rosierdd7fddb2011-08-04 23:34:15 +0000840bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000841 const FieldDecl *LastFD) const {
842 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000843 FD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000844}
845
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000846ASTContext::overridden_cxx_method_iterator
847ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
848 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
849 = OverriddenMethods.find(Method);
850 if (Pos == OverriddenMethods.end())
851 return 0;
852
853 return Pos->second.begin();
854}
855
856ASTContext::overridden_cxx_method_iterator
857ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
858 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
859 = OverriddenMethods.find(Method);
860 if (Pos == OverriddenMethods.end())
861 return 0;
862
863 return Pos->second.end();
864}
865
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +0000866unsigned
867ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
868 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
869 = OverriddenMethods.find(Method);
870 if (Pos == OverriddenMethods.end())
871 return 0;
872
873 return Pos->second.size();
874}
875
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000876void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
877 const CXXMethodDecl *Overridden) {
878 OverriddenMethods[Method].push_back(Overridden);
879}
880
Douglas Gregore6649772011-12-03 00:30:27 +0000881void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
882 assert(!Import->NextLocalImport && "Import declaration already in the chain");
883 assert(!Import->isFromASTFile() && "Non-local import declaration");
884 if (!FirstLocalImport) {
885 FirstLocalImport = Import;
886 LastLocalImport = Import;
887 return;
888 }
889
890 LastLocalImport->NextLocalImport = Import;
891 LastLocalImport = Import;
892}
893
Chris Lattner464175b2007-07-18 17:52:12 +0000894//===----------------------------------------------------------------------===//
895// Type Sizing and Analysis
896//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000897
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000898/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
899/// scalar floating point type.
900const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000901 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000902 assert(BT && "Not a floating point type!");
903 switch (BT->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000904 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000905 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000906 case BuiltinType::Float: return Target->getFloatFormat();
907 case BuiltinType::Double: return Target->getDoubleFormat();
908 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000909 }
910}
911
Ken Dyck8b752f12010-01-27 17:10:57 +0000912/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000913/// specified decl. Note that bitfields do not have a valid alignment, so
914/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000915/// If @p RefAsPointee, references are treated like their underlying type
916/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +0000917CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000918 unsigned Align = Target->getCharWidth();
Eli Friedmandcdafb62009-02-22 02:56:25 +0000919
John McCall4081a5c2010-10-08 18:24:19 +0000920 bool UseAlignAttrOnly = false;
921 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
922 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +0000923
John McCall4081a5c2010-10-08 18:24:19 +0000924 // __attribute__((aligned)) can increase or decrease alignment
925 // *except* on a struct or struct member, where it only increases
926 // alignment unless 'packed' is also specified.
927 //
Peter Collingbourne82d0b0a2011-09-29 18:04:28 +0000928 // It is an error for alignas to decrease alignment, so we can
John McCall4081a5c2010-10-08 18:24:19 +0000929 // ignore that possibility; Sema should diagnose it.
930 if (isa<FieldDecl>(D)) {
931 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
932 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
933 } else {
934 UseAlignAttrOnly = true;
935 }
936 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +0000937 else if (isa<FieldDecl>(D))
938 UseAlignAttrOnly =
939 D->hasAttr<PackedAttr>() ||
940 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +0000941
John McCallba4f5d52011-01-20 07:57:12 +0000942 // If we're using the align attribute only, just ignore everything
943 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +0000944 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +0000945 // do nothing
946
John McCall4081a5c2010-10-08 18:24:19 +0000947 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +0000948 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000949 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000950 if (RefAsPointee)
951 T = RT->getPointeeType();
952 else
953 T = getPointerType(RT->getPointeeType());
954 }
955 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +0000956 // Adjust alignments of declarations with array type by the
957 // large-array alignment on the target.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000958 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +0000959 const ArrayType *arrayType;
960 if (MinWidth && (arrayType = getAsArrayType(T))) {
961 if (isa<VariableArrayType>(arrayType))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000962 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall3b657512011-01-19 10:06:00 +0000963 else if (isa<ConstantArrayType>(arrayType) &&
964 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000965 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000966
John McCall3b657512011-01-19 10:06:00 +0000967 // Walk through any array types while we're at it.
968 T = getBaseElementType(arrayType);
969 }
Chad Rosier9f1210c2011-07-26 07:03:04 +0000970 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedmandcdafb62009-02-22 02:56:25 +0000971 }
John McCallba4f5d52011-01-20 07:57:12 +0000972
973 // Fields can be subject to extra alignment constraints, like if
974 // the field is packed, the struct is packed, or the struct has a
975 // a max-field-alignment constraint (#pragma pack). So calculate
976 // the actual alignment of the field within the struct, and then
977 // (as we're expected to) constrain that by the alignment of the type.
978 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
979 // So calculate the alignment of the field.
980 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
981
982 // Start with the record's overall alignment.
Ken Dyckdac54c12011-02-15 02:32:40 +0000983 unsigned fieldAlign = toBits(layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +0000984
985 // Use the GCD of that and the offset within the record.
986 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
987 if (offset > 0) {
988 // Alignment is always a power of 2, so the GCD will be a power of 2,
989 // which means we get to do this crazy thing instead of Euclid's.
990 uint64_t lowBitOfOffset = offset & (~offset + 1);
991 if (lowBitOfOffset < fieldAlign)
992 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
993 }
994
995 Align = std::min(Align, fieldAlign);
Charles Davis05f62472010-02-23 04:52:00 +0000996 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000997 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000998
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000999 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001000}
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001001
John McCallea1471e2010-05-20 01:18:31 +00001002std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001003ASTContext::getTypeInfoInChars(const Type *T) const {
John McCallea1471e2010-05-20 01:18:31 +00001004 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001005 return std::make_pair(toCharUnitsFromBits(Info.first),
1006 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +00001007}
1008
1009std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001010ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +00001011 return getTypeInfoInChars(T.getTypePtr());
1012}
1013
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001014std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1015 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1016 if (it != MemoizedTypeInfo.end())
1017 return it->second;
1018
1019 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1020 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1021 return Info;
1022}
1023
1024/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1025/// method does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +00001026///
1027/// FIXME: Pointers into different addr spaces could have different sizes and
1028/// alignment requirements: getPointerInfo should take an AddrSpace, this
1029/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001030std::pair<uint64_t, unsigned>
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001031ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +00001032 uint64_t Width=0;
1033 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +00001034 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001035#define TYPE(Class, Base)
1036#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +00001037#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +00001038#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1039#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +00001040 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +00001041
Chris Lattner692233e2007-07-13 22:27:08 +00001042 case Type::FunctionNoProto:
1043 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +00001044 // GCC extension: alignof(function) = 32 bits
1045 Width = 0;
1046 Align = 32;
1047 break;
1048
Douglas Gregor72564e72009-02-26 23:50:07 +00001049 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +00001050 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +00001051 Width = 0;
1052 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1053 break;
1054
Steve Narofffb22d962007-08-30 01:06:46 +00001055 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001056 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001057
Chris Lattner98be4942008-03-05 18:54:05 +00001058 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001059 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001060 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1061 "Overflow in array type bit size evaluation");
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001062 Width = EltInfo.first*Size;
Chris Lattner030d8842007-07-19 22:06:24 +00001063 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +00001064 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +00001065 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +00001066 }
Nate Begeman213541a2008-04-18 23:10:10 +00001067 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +00001068 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001069 const VectorType *VT = cast<VectorType>(T);
1070 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1071 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +00001072 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +00001073 // If the alignment is not a power of 2, round up to the next power of 2.
1074 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +00001075 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001076 Align = llvm::NextPowerOf2(Align);
1077 Width = llvm::RoundUpToAlignment(Width, Align);
1078 }
Chad Rosierf9e9af72012-07-13 23:57:43 +00001079 // Adjust the alignment based on the target max.
1080 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1081 if (TargetVectorAlign && TargetVectorAlign < Align)
1082 Align = TargetVectorAlign;
Chris Lattner030d8842007-07-19 22:06:24 +00001083 break;
1084 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001085
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001086 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +00001087 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001088 default: llvm_unreachable("Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001089 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +00001090 // GCC extension: alignof(void) = 8 bits.
1091 Width = 0;
1092 Align = 8;
1093 break;
1094
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001095 case BuiltinType::Bool:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001096 Width = Target->getBoolWidth();
1097 Align = Target->getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001098 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001099 case BuiltinType::Char_S:
1100 case BuiltinType::Char_U:
1101 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001102 case BuiltinType::SChar:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001103 Width = Target->getCharWidth();
1104 Align = Target->getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001105 break;
Chris Lattner3f59c972010-12-25 23:25:43 +00001106 case BuiltinType::WChar_S:
1107 case BuiltinType::WChar_U:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001108 Width = Target->getWCharWidth();
1109 Align = Target->getWCharAlign();
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001110 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001111 case BuiltinType::Char16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001112 Width = Target->getChar16Width();
1113 Align = Target->getChar16Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001114 break;
1115 case BuiltinType::Char32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001116 Width = Target->getChar32Width();
1117 Align = Target->getChar32Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001118 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001119 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001120 case BuiltinType::Short:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001121 Width = Target->getShortWidth();
1122 Align = Target->getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001123 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001124 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001125 case BuiltinType::Int:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001126 Width = Target->getIntWidth();
1127 Align = Target->getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001128 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001129 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001130 case BuiltinType::Long:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001131 Width = Target->getLongWidth();
1132 Align = Target->getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001133 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001134 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001135 case BuiltinType::LongLong:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001136 Width = Target->getLongLongWidth();
1137 Align = Target->getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001138 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +00001139 case BuiltinType::Int128:
1140 case BuiltinType::UInt128:
1141 Width = 128;
1142 Align = 128; // int128_t is 128-bit aligned on all targets.
1143 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001144 case BuiltinType::Half:
1145 Width = Target->getHalfWidth();
1146 Align = Target->getHalfAlign();
1147 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001148 case BuiltinType::Float:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001149 Width = Target->getFloatWidth();
1150 Align = Target->getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001151 break;
1152 case BuiltinType::Double:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001153 Width = Target->getDoubleWidth();
1154 Align = Target->getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001155 break;
1156 case BuiltinType::LongDouble:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001157 Width = Target->getLongDoubleWidth();
1158 Align = Target->getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001159 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001160 case BuiltinType::NullPtr:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001161 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1162 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +00001163 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001164 case BuiltinType::ObjCId:
1165 case BuiltinType::ObjCClass:
1166 case BuiltinType::ObjCSel:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001167 Width = Target->getPointerWidth(0);
1168 Align = Target->getPointerAlign(0);
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001169 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001170 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +00001171 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001172 case Type::ObjCObjectPointer:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001173 Width = Target->getPointerWidth(0);
1174 Align = Target->getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001175 break;
Steve Naroff485eeff2008-09-24 15:05:44 +00001176 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001177 unsigned AS = getTargetAddressSpace(
1178 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001179 Width = Target->getPointerWidth(AS);
1180 Align = Target->getPointerAlign(AS);
Steve Naroff485eeff2008-09-24 15:05:44 +00001181 break;
1182 }
Sebastian Redl5d484e82009-11-23 17:18:46 +00001183 case Type::LValueReference:
1184 case Type::RValueReference: {
1185 // alignof and sizeof should never enter this code path here, so we go
1186 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001187 unsigned AS = getTargetAddressSpace(
1188 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001189 Width = Target->getPointerWidth(AS);
1190 Align = Target->getPointerAlign(AS);
Sebastian Redl5d484e82009-11-23 17:18:46 +00001191 break;
1192 }
Chris Lattnerf72a4432008-03-08 08:34:58 +00001193 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001194 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001195 Width = Target->getPointerWidth(AS);
1196 Align = Target->getPointerAlign(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +00001197 break;
1198 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00001199 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +00001200 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001201 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001202 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +00001203 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001204 Align = PtrDiffInfo.second;
1205 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001206 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001207 case Type::Complex: {
1208 // Complex types have the same alignment as their elements, but twice the
1209 // size.
Mike Stump1eb44332009-09-09 15:08:12 +00001210 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +00001211 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001212 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +00001213 Align = EltInfo.second;
1214 break;
1215 }
John McCallc12c5bb2010-05-15 11:32:37 +00001216 case Type::ObjCObject:
1217 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +00001218 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001219 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +00001220 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001221 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001222 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +00001223 break;
1224 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001225 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00001226 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001227 const TagType *TT = cast<TagType>(T);
1228
1229 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +00001230 Width = 8;
1231 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +00001232 break;
1233 }
Mike Stump1eb44332009-09-09 15:08:12 +00001234
Daniel Dunbar1d751182008-11-08 05:48:37 +00001235 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +00001236 return getTypeInfo(ET->getDecl()->getIntegerType());
1237
Daniel Dunbar1d751182008-11-08 05:48:37 +00001238 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +00001239 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001240 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001241 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +00001242 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001243 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001244
Chris Lattner9fcfe922009-10-22 05:17:15 +00001245 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +00001246 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1247 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +00001248
Richard Smith34b41d92011-02-20 03:19:35 +00001249 case Type::Auto: {
1250 const AutoType *A = cast<AutoType>(T);
1251 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +00001252 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +00001253 }
1254
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001255 case Type::Paren:
1256 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1257
Douglas Gregor18857642009-04-30 17:32:17 +00001258 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +00001259 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +00001260 std::pair<uint64_t, unsigned> Info
1261 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +00001262 // If the typedef has an aligned attribute on it, it overrides any computed
1263 // alignment we have. This violates the GCC documentation (which says that
1264 // attribute(aligned) can only round up) but matches its implementation.
1265 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1266 Align = AttrAlign;
1267 else
1268 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +00001269 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001270 break;
Chris Lattner71763312008-04-06 22:05:18 +00001271 }
Douglas Gregor18857642009-04-30 17:32:17 +00001272
1273 case Type::TypeOfExpr:
1274 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1275 .getTypePtr());
1276
1277 case Type::TypeOf:
1278 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1279
Anders Carlsson395b4752009-06-24 19:06:50 +00001280 case Type::Decltype:
1281 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1282 .getTypePtr());
1283
Sean Huntca63c202011-05-24 22:41:36 +00001284 case Type::UnaryTransform:
1285 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1286
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001287 case Type::Elaborated:
1288 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +00001289
John McCall9d156a72011-01-06 01:58:22 +00001290 case Type::Attributed:
1291 return getTypeInfo(
1292 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1293
Richard Smith3e4c6c42011-05-05 21:57:07 +00001294 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00001295 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +00001296 "Cannot request the size of a dependent type");
Richard Smith3e4c6c42011-05-05 21:57:07 +00001297 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1298 // A type alias template specialization may refer to a typedef with the
1299 // aligned attribute on it.
1300 if (TST->isTypeAlias())
1301 return getTypeInfo(TST->getAliasedType().getTypePtr());
1302 else
1303 return getTypeInfo(getCanonicalType(T));
1304 }
1305
Eli Friedmanb001de72011-10-06 23:00:33 +00001306 case Type::Atomic: {
Eli Friedman2be46072011-10-14 20:59:01 +00001307 std::pair<uint64_t, unsigned> Info
1308 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1309 Width = Info.first;
1310 Align = Info.second;
1311 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1312 llvm::isPowerOf2_64(Width)) {
1313 // We can potentially perform lock-free atomic operations for this
1314 // type; promote the alignment appropriately.
1315 // FIXME: We could potentially promote the width here as well...
1316 // is that worthwhile? (Non-struct atomic types generally have
1317 // power-of-two size anyway, but structs might not. Requires a bit
1318 // of implementation work to make sure we zero out the extra bits.)
1319 Align = static_cast<unsigned>(Width);
1320 }
Eli Friedmanb001de72011-10-06 23:00:33 +00001321 }
1322
Douglas Gregor18857642009-04-30 17:32:17 +00001323 }
Mike Stump1eb44332009-09-09 15:08:12 +00001324
Eli Friedman2be46072011-10-14 20:59:01 +00001325 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001326 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001327}
1328
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001329/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1330CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1331 return CharUnits::fromQuantity(BitSize / getCharWidth());
1332}
1333
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001334/// toBits - Convert a size in characters to a size in characters.
1335int64_t ASTContext::toBits(CharUnits CharSize) const {
1336 return CharSize.getQuantity() * getCharWidth();
1337}
1338
Ken Dyckbdc601b2009-12-22 14:23:30 +00001339/// getTypeSizeInChars - Return the size of the specified type, in characters.
1340/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001341CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001342 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001343}
Jay Foad4ba2a172011-01-12 09:06:06 +00001344CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001345 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001346}
1347
Ken Dyck16e20cc2010-01-26 17:25:18 +00001348/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001349/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001350CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001351 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001352}
Jay Foad4ba2a172011-01-12 09:06:06 +00001353CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001354 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001355}
1356
Chris Lattner34ebde42009-01-27 18:08:34 +00001357/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1358/// type for the current target in bits. This can be different than the ABI
1359/// alignment in cases where it is beneficial for performance to overalign
1360/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001361unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001362 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001363
1364 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001365 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001366 T = CT->getElementType().getTypePtr();
1367 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosiercde7a1d2012-03-21 20:20:47 +00001368 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1369 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman1eed6022009-05-25 21:27:19 +00001370 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1371
Chris Lattner34ebde42009-01-27 18:08:34 +00001372 return ABIAlign;
1373}
1374
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001375/// DeepCollectObjCIvars -
1376/// This routine first collects all declared, but not synthesized, ivars in
1377/// super class and then collects all ivars, including those synthesized for
1378/// current class. This routine is used for implementation of current class
1379/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001380///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001381void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1382 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001383 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001384 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1385 DeepCollectObjCIvars(SuperClass, false, Ivars);
1386 if (!leafClass) {
1387 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1388 E = OI->ivar_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001389 Ivars.push_back(*I);
Chad Rosier30601782011-08-17 23:08:45 +00001390 } else {
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001391 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001392 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001393 Iv= Iv->getNextIvar())
1394 Ivars.push_back(Iv);
1395 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001396}
1397
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001398/// CollectInheritedProtocols - Collect all protocols in current class and
1399/// those inherited by it.
1400void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001401 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001402 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001403 // We can use protocol_iterator here instead of
1404 // all_referenced_protocol_iterator since we are walking all categories.
1405 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1406 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001407 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001408 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001409 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001410 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001411 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001412 CollectInheritedProtocols(*P, Protocols);
1413 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001414 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001415
1416 // Categories of this Interface.
1417 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1418 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1419 CollectInheritedProtocols(CDeclChain, Protocols);
1420 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1421 while (SD) {
1422 CollectInheritedProtocols(SD, Protocols);
1423 SD = SD->getSuperClass();
1424 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001425 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001426 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001427 PE = OC->protocol_end(); P != PE; ++P) {
1428 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001429 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001430 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1431 PE = Proto->protocol_end(); P != PE; ++P)
1432 CollectInheritedProtocols(*P, Protocols);
1433 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001434 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001435 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1436 PE = OP->protocol_end(); P != PE; ++P) {
1437 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001438 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001439 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1440 PE = Proto->protocol_end(); P != PE; ++P)
1441 CollectInheritedProtocols(*P, Protocols);
1442 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001443 }
1444}
1445
Jay Foad4ba2a172011-01-12 09:06:06 +00001446unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001447 unsigned count = 0;
1448 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00001449 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1450 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001451 count += CDecl->ivar_size();
1452
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001453 // Count ivar defined in this class's implementation. This
1454 // includes synthesized ivars.
1455 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001456 count += ImplDecl->ivar_size();
1457
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001458 return count;
1459}
1460
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +00001461bool ASTContext::isSentinelNullExpr(const Expr *E) {
1462 if (!E)
1463 return false;
1464
1465 // nullptr_t is always treated as null.
1466 if (E->getType()->isNullPtrType()) return true;
1467
1468 if (E->getType()->isAnyPointerType() &&
1469 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1470 Expr::NPC_ValueDependentIsNull))
1471 return true;
1472
1473 // Unfortunately, __null has type 'int'.
1474 if (isa<GNUNullExpr>(E)) return true;
1475
1476 return false;
1477}
1478
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001479/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1480ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1481 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1482 I = ObjCImpls.find(D);
1483 if (I != ObjCImpls.end())
1484 return cast<ObjCImplementationDecl>(I->second);
1485 return 0;
1486}
1487/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1488ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1489 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1490 I = ObjCImpls.find(D);
1491 if (I != ObjCImpls.end())
1492 return cast<ObjCCategoryImplDecl>(I->second);
1493 return 0;
1494}
1495
1496/// \brief Set the implementation of ObjCInterfaceDecl.
1497void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1498 ObjCImplementationDecl *ImplD) {
1499 assert(IFaceD && ImplD && "Passed null params");
1500 ObjCImpls[IFaceD] = ImplD;
1501}
1502/// \brief Set the implementation of ObjCCategoryDecl.
1503void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1504 ObjCCategoryImplDecl *ImplD) {
1505 assert(CatD && ImplD && "Passed null params");
1506 ObjCImpls[CatD] = ImplD;
1507}
1508
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001509ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1510 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1511 return ID;
1512 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1513 return CD->getClassInterface();
1514 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1515 return IMD->getClassInterface();
1516
1517 return 0;
1518}
1519
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001520/// \brief Get the copy initialization expression of VarDecl,or NULL if
1521/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001522Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001523 assert(VD && "Passed null params");
1524 assert(VD->hasAttr<BlocksAttr>() &&
1525 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001526 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001527 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001528 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1529}
1530
1531/// \brief Set the copy inialization expression of a block var decl.
1532void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1533 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001534 assert(VD->hasAttr<BlocksAttr>() &&
1535 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001536 BlockVarCopyInits[VD] = Init;
1537}
1538
John McCalla93c9342009-12-07 02:54:59 +00001539TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001540 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001541 if (!DataSize)
1542 DataSize = TypeLoc::getFullDataSizeForType(T);
1543 else
1544 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001545 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001546
John McCalla93c9342009-12-07 02:54:59 +00001547 TypeSourceInfo *TInfo =
1548 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1549 new (TInfo) TypeSourceInfo(T);
1550 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001551}
1552
John McCalla93c9342009-12-07 02:54:59 +00001553TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001554 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001555 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001556 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001557 return DI;
1558}
1559
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001560const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001561ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001562 return getObjCLayout(D, 0);
1563}
1564
1565const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001566ASTContext::getASTObjCImplementationLayout(
1567 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001568 return getObjCLayout(D->getClassInterface(), D);
1569}
1570
Chris Lattnera7674d82007-07-13 22:13:22 +00001571//===----------------------------------------------------------------------===//
1572// Type creation/memoization methods
1573//===----------------------------------------------------------------------===//
1574
Jay Foad4ba2a172011-01-12 09:06:06 +00001575QualType
John McCall3b657512011-01-19 10:06:00 +00001576ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1577 unsigned fastQuals = quals.getFastQualifiers();
1578 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001579
1580 // Check if we've already instantiated this type.
1581 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001582 ExtQuals::Profile(ID, baseType, quals);
1583 void *insertPos = 0;
1584 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1585 assert(eq->getQualifiers() == quals);
1586 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001587 }
1588
John McCall3b657512011-01-19 10:06:00 +00001589 // If the base type is not canonical, make the appropriate canonical type.
1590 QualType canon;
1591 if (!baseType->isCanonicalUnqualified()) {
1592 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall200fa532012-02-08 00:46:36 +00001593 canonSplit.Quals.addConsistentQualifiers(quals);
1594 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00001595
1596 // Re-find the insert position.
1597 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1598 }
1599
1600 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1601 ExtQualNodes.InsertNode(eq, insertPos);
1602 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001603}
1604
Jay Foad4ba2a172011-01-12 09:06:06 +00001605QualType
1606ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001607 QualType CanT = getCanonicalType(T);
1608 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001609 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001610
John McCall0953e762009-09-24 19:53:00 +00001611 // If we are composing extended qualifiers together, merge together
1612 // into one ExtQuals node.
1613 QualifierCollector Quals;
1614 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001615
John McCall0953e762009-09-24 19:53:00 +00001616 // If this type already has an address space specified, it cannot get
1617 // another one.
1618 assert(!Quals.hasAddressSpace() &&
1619 "Type cannot be in multiple addr spaces!");
1620 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001621
John McCall0953e762009-09-24 19:53:00 +00001622 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001623}
1624
Chris Lattnerb7d25532009-02-18 22:53:11 +00001625QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001626 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001627 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001628 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001629 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001630
John McCall7f040a92010-12-24 02:08:15 +00001631 if (const PointerType *ptr = T->getAs<PointerType>()) {
1632 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001633 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001634 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1635 return getPointerType(ResultType);
1636 }
1637 }
Mike Stump1eb44332009-09-09 15:08:12 +00001638
John McCall0953e762009-09-24 19:53:00 +00001639 // If we are composing extended qualifiers together, merge together
1640 // into one ExtQuals node.
1641 QualifierCollector Quals;
1642 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001643
John McCall0953e762009-09-24 19:53:00 +00001644 // If this type already has an ObjCGC specified, it cannot get
1645 // another one.
1646 assert(!Quals.hasObjCGCAttr() &&
1647 "Type cannot have multiple ObjCGCs!");
1648 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001649
John McCall0953e762009-09-24 19:53:00 +00001650 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001651}
Chris Lattnera7674d82007-07-13 22:13:22 +00001652
John McCalle6a365d2010-12-19 02:44:49 +00001653const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1654 FunctionType::ExtInfo Info) {
1655 if (T->getExtInfo() == Info)
1656 return T;
1657
1658 QualType Result;
1659 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1660 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1661 } else {
1662 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1663 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1664 EPI.ExtInfo = Info;
1665 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1666 FPT->getNumArgs(), EPI);
1667 }
1668
1669 return cast<FunctionType>(Result.getTypePtr());
1670}
1671
Reid Spencer5f016e22007-07-11 17:01:13 +00001672/// getComplexType - Return the uniqued reference to the type for a complex
1673/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001674QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001675 // Unique pointers, to guarantee there is only one pointer of a particular
1676 // structure.
1677 llvm::FoldingSetNodeID ID;
1678 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001679
Reid Spencer5f016e22007-07-11 17:01:13 +00001680 void *InsertPos = 0;
1681 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1682 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001683
Reid Spencer5f016e22007-07-11 17:01:13 +00001684 // If the pointee type isn't canonical, this won't be a canonical type either,
1685 // so fill in the canonical type field.
1686 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001687 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001688 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001689
Reid Spencer5f016e22007-07-11 17:01:13 +00001690 // Get the new insert position for the node we care about.
1691 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001692 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001693 }
John McCall6b304a02009-09-24 23:30:46 +00001694 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001695 Types.push_back(New);
1696 ComplexTypes.InsertNode(New, InsertPos);
1697 return QualType(New, 0);
1698}
1699
Reid Spencer5f016e22007-07-11 17:01:13 +00001700/// getPointerType - Return the uniqued reference to the type for a pointer to
1701/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001702QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001703 // Unique pointers, to guarantee there is only one pointer of a particular
1704 // structure.
1705 llvm::FoldingSetNodeID ID;
1706 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001707
Reid Spencer5f016e22007-07-11 17:01:13 +00001708 void *InsertPos = 0;
1709 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1710 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001711
Reid Spencer5f016e22007-07-11 17:01:13 +00001712 // If the pointee type isn't canonical, this won't be a canonical type either,
1713 // so fill in the canonical type field.
1714 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001715 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001716 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001717
Reid Spencer5f016e22007-07-11 17:01:13 +00001718 // Get the new insert position for the node we care about.
1719 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001720 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001721 }
John McCall6b304a02009-09-24 23:30:46 +00001722 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001723 Types.push_back(New);
1724 PointerTypes.InsertNode(New, InsertPos);
1725 return QualType(New, 0);
1726}
1727
Mike Stump1eb44332009-09-09 15:08:12 +00001728/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001729/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00001730QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00001731 assert(T->isFunctionType() && "block of function types only");
1732 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001733 // structure.
1734 llvm::FoldingSetNodeID ID;
1735 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001736
Steve Naroff5618bd42008-08-27 16:04:49 +00001737 void *InsertPos = 0;
1738 if (BlockPointerType *PT =
1739 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1740 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001741
1742 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001743 // type either so fill in the canonical type field.
1744 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001745 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001746 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001747
Steve Naroff5618bd42008-08-27 16:04:49 +00001748 // Get the new insert position for the node we care about.
1749 BlockPointerType *NewIP =
1750 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001751 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001752 }
John McCall6b304a02009-09-24 23:30:46 +00001753 BlockPointerType *New
1754 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001755 Types.push_back(New);
1756 BlockPointerTypes.InsertNode(New, InsertPos);
1757 return QualType(New, 0);
1758}
1759
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001760/// getLValueReferenceType - Return the uniqued reference to the type for an
1761/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001762QualType
1763ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00001764 assert(getCanonicalType(T) != OverloadTy &&
1765 "Unresolved overloaded function type");
1766
Reid Spencer5f016e22007-07-11 17:01:13 +00001767 // Unique pointers, to guarantee there is only one pointer of a particular
1768 // structure.
1769 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001770 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001771
1772 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001773 if (LValueReferenceType *RT =
1774 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001775 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001776
John McCall54e14c42009-10-22 22:37:11 +00001777 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1778
Reid Spencer5f016e22007-07-11 17:01:13 +00001779 // If the referencee type isn't canonical, this won't be a canonical type
1780 // either, so fill in the canonical type field.
1781 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001782 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1783 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1784 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001785
Reid Spencer5f016e22007-07-11 17:01:13 +00001786 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001787 LValueReferenceType *NewIP =
1788 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001789 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001790 }
1791
John McCall6b304a02009-09-24 23:30:46 +00001792 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001793 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1794 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001795 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001796 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001797
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001798 return QualType(New, 0);
1799}
1800
1801/// getRValueReferenceType - Return the uniqued reference to the type for an
1802/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001803QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001804 // Unique pointers, to guarantee there is only one pointer of a particular
1805 // structure.
1806 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001807 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001808
1809 void *InsertPos = 0;
1810 if (RValueReferenceType *RT =
1811 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1812 return QualType(RT, 0);
1813
John McCall54e14c42009-10-22 22:37:11 +00001814 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1815
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001816 // If the referencee type isn't canonical, this won't be a canonical type
1817 // either, so fill in the canonical type field.
1818 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001819 if (InnerRef || !T.isCanonical()) {
1820 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1821 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001822
1823 // Get the new insert position for the node we care about.
1824 RValueReferenceType *NewIP =
1825 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001826 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001827 }
1828
John McCall6b304a02009-09-24 23:30:46 +00001829 RValueReferenceType *New
1830 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001831 Types.push_back(New);
1832 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001833 return QualType(New, 0);
1834}
1835
Sebastian Redlf30208a2009-01-24 21:16:55 +00001836/// getMemberPointerType - Return the uniqued reference to the type for a
1837/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00001838QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001839 // Unique pointers, to guarantee there is only one pointer of a particular
1840 // structure.
1841 llvm::FoldingSetNodeID ID;
1842 MemberPointerType::Profile(ID, T, Cls);
1843
1844 void *InsertPos = 0;
1845 if (MemberPointerType *PT =
1846 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1847 return QualType(PT, 0);
1848
1849 // If the pointee or class type isn't canonical, this won't be a canonical
1850 // type either, so fill in the canonical type field.
1851 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001852 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001853 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1854
1855 // Get the new insert position for the node we care about.
1856 MemberPointerType *NewIP =
1857 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001858 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001859 }
John McCall6b304a02009-09-24 23:30:46 +00001860 MemberPointerType *New
1861 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001862 Types.push_back(New);
1863 MemberPointerTypes.InsertNode(New, InsertPos);
1864 return QualType(New, 0);
1865}
1866
Mike Stump1eb44332009-09-09 15:08:12 +00001867/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001868/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001869QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001870 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001871 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001872 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001873 assert((EltTy->isDependentType() ||
1874 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001875 "Constant array of VLAs is illegal!");
1876
Chris Lattner38aeec72009-05-13 04:12:56 +00001877 // Convert the array size into a canonical width matching the pointer size for
1878 // the target.
1879 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001880 ArySize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001881 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00001882
Reid Spencer5f016e22007-07-11 17:01:13 +00001883 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001884 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001885
Reid Spencer5f016e22007-07-11 17:01:13 +00001886 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001887 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001888 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001889 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001890
John McCall3b657512011-01-19 10:06:00 +00001891 // If the element type isn't canonical or has qualifiers, this won't
1892 // be a canonical type either, so fill in the canonical type field.
1893 QualType Canon;
1894 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1895 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00001896 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001897 ASM, IndexTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00001898 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00001899
Reid Spencer5f016e22007-07-11 17:01:13 +00001900 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001901 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001902 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001903 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001904 }
Mike Stump1eb44332009-09-09 15:08:12 +00001905
John McCall6b304a02009-09-24 23:30:46 +00001906 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001907 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001908 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001909 Types.push_back(New);
1910 return QualType(New, 0);
1911}
1912
John McCallce889032011-01-18 08:40:38 +00001913/// getVariableArrayDecayedType - Turns the given type, which may be
1914/// variably-modified, into the corresponding type with all the known
1915/// sizes replaced with [*].
1916QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1917 // Vastly most common case.
1918 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001919
John McCallce889032011-01-18 08:40:38 +00001920 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001921
John McCallce889032011-01-18 08:40:38 +00001922 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00001923 const Type *ty = split.Ty;
John McCallce889032011-01-18 08:40:38 +00001924 switch (ty->getTypeClass()) {
1925#define TYPE(Class, Base)
1926#define ABSTRACT_TYPE(Class, Base)
1927#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1928#include "clang/AST/TypeNodes.def"
1929 llvm_unreachable("didn't desugar past all non-canonical types?");
1930
1931 // These types should never be variably-modified.
1932 case Type::Builtin:
1933 case Type::Complex:
1934 case Type::Vector:
1935 case Type::ExtVector:
1936 case Type::DependentSizedExtVector:
1937 case Type::ObjCObject:
1938 case Type::ObjCInterface:
1939 case Type::ObjCObjectPointer:
1940 case Type::Record:
1941 case Type::Enum:
1942 case Type::UnresolvedUsing:
1943 case Type::TypeOfExpr:
1944 case Type::TypeOf:
1945 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00001946 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00001947 case Type::DependentName:
1948 case Type::InjectedClassName:
1949 case Type::TemplateSpecialization:
1950 case Type::DependentTemplateSpecialization:
1951 case Type::TemplateTypeParm:
1952 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00001953 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00001954 case Type::PackExpansion:
1955 llvm_unreachable("type should never be variably-modified");
1956
1957 // These types can be variably-modified but should never need to
1958 // further decay.
1959 case Type::FunctionNoProto:
1960 case Type::FunctionProto:
1961 case Type::BlockPointer:
1962 case Type::MemberPointer:
1963 return type;
1964
1965 // These types can be variably-modified. All these modifications
1966 // preserve structure except as noted by comments.
1967 // TODO: if we ever care about optimizing VLAs, there are no-op
1968 // optimizations available here.
1969 case Type::Pointer:
1970 result = getPointerType(getVariableArrayDecayedType(
1971 cast<PointerType>(ty)->getPointeeType()));
1972 break;
1973
1974 case Type::LValueReference: {
1975 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1976 result = getLValueReferenceType(
1977 getVariableArrayDecayedType(lv->getPointeeType()),
1978 lv->isSpelledAsLValue());
1979 break;
1980 }
1981
1982 case Type::RValueReference: {
1983 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1984 result = getRValueReferenceType(
1985 getVariableArrayDecayedType(lv->getPointeeType()));
1986 break;
1987 }
1988
Eli Friedmanb001de72011-10-06 23:00:33 +00001989 case Type::Atomic: {
1990 const AtomicType *at = cast<AtomicType>(ty);
1991 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1992 break;
1993 }
1994
John McCallce889032011-01-18 08:40:38 +00001995 case Type::ConstantArray: {
1996 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1997 result = getConstantArrayType(
1998 getVariableArrayDecayedType(cat->getElementType()),
1999 cat->getSize(),
2000 cat->getSizeModifier(),
2001 cat->getIndexTypeCVRQualifiers());
2002 break;
2003 }
2004
2005 case Type::DependentSizedArray: {
2006 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2007 result = getDependentSizedArrayType(
2008 getVariableArrayDecayedType(dat->getElementType()),
2009 dat->getSizeExpr(),
2010 dat->getSizeModifier(),
2011 dat->getIndexTypeCVRQualifiers(),
2012 dat->getBracketsRange());
2013 break;
2014 }
2015
2016 // Turn incomplete types into [*] types.
2017 case Type::IncompleteArray: {
2018 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2019 result = getVariableArrayType(
2020 getVariableArrayDecayedType(iat->getElementType()),
2021 /*size*/ 0,
2022 ArrayType::Normal,
2023 iat->getIndexTypeCVRQualifiers(),
2024 SourceRange());
2025 break;
2026 }
2027
2028 // Turn VLA types into [*] types.
2029 case Type::VariableArray: {
2030 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2031 result = getVariableArrayType(
2032 getVariableArrayDecayedType(vat->getElementType()),
2033 /*size*/ 0,
2034 ArrayType::Star,
2035 vat->getIndexTypeCVRQualifiers(),
2036 vat->getBracketsRange());
2037 break;
2038 }
2039 }
2040
2041 // Apply the top-level qualifiers from the original.
John McCall200fa532012-02-08 00:46:36 +00002042 return getQualifiedType(result, split.Quals);
John McCallce889032011-01-18 08:40:38 +00002043}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002044
Steve Naroffbdbf7b02007-08-30 18:14:25 +00002045/// getVariableArrayType - Returns a non-unique reference to the type for a
2046/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002047QualType ASTContext::getVariableArrayType(QualType EltTy,
2048 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00002049 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002050 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00002051 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002052 // Since we don't unique expressions, it isn't possible to unique VLA's
2053 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00002054 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00002055
John McCall3b657512011-01-19 10:06:00 +00002056 // Be sure to pull qualifiers off the element type.
2057 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2058 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002059 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002060 IndexTypeQuals, Brackets);
John McCall200fa532012-02-08 00:46:36 +00002061 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor715e9c82010-05-23 16:10:32 +00002062 }
2063
John McCall6b304a02009-09-24 23:30:46 +00002064 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002065 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002066
2067 VariableArrayTypes.push_back(New);
2068 Types.push_back(New);
2069 return QualType(New, 0);
2070}
2071
Douglas Gregor898574e2008-12-05 23:32:09 +00002072/// getDependentSizedArrayType - Returns a non-unique reference to
2073/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00002074/// type.
John McCall3b657512011-01-19 10:06:00 +00002075QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2076 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00002077 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002078 unsigned elementTypeQuals,
2079 SourceRange brackets) const {
2080 assert((!numElements || numElements->isTypeDependent() ||
2081 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00002082 "Size must be type- or value-dependent!");
2083
John McCall3b657512011-01-19 10:06:00 +00002084 // Dependently-sized array types that do not have a specified number
2085 // of elements will have their sizes deduced from a dependent
2086 // initializer. We do no canonicalization here at all, which is okay
2087 // because they can't be used in most locations.
2088 if (!numElements) {
2089 DependentSizedArrayType *newType
2090 = new (*this, TypeAlignment)
2091 DependentSizedArrayType(*this, elementType, QualType(),
2092 numElements, ASM, elementTypeQuals,
2093 brackets);
2094 Types.push_back(newType);
2095 return QualType(newType, 0);
2096 }
2097
2098 // Otherwise, we actually build a new type every time, but we
2099 // also build a canonical type.
2100
2101 SplitQualType canonElementType = getCanonicalType(elementType).split();
2102
2103 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00002104 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002105 DependentSizedArrayType::Profile(ID, *this,
John McCall200fa532012-02-08 00:46:36 +00002106 QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002107 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002108
John McCall3b657512011-01-19 10:06:00 +00002109 // Look for an existing type with these properties.
2110 DependentSizedArrayType *canonTy =
2111 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002112
John McCall3b657512011-01-19 10:06:00 +00002113 // If we don't have one, build one.
2114 if (!canonTy) {
2115 canonTy = new (*this, TypeAlignment)
John McCall200fa532012-02-08 00:46:36 +00002116 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002117 QualType(), numElements, ASM, elementTypeQuals,
2118 brackets);
2119 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2120 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002121 }
2122
John McCall3b657512011-01-19 10:06:00 +00002123 // Apply qualifiers from the element type to the array.
2124 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall200fa532012-02-08 00:46:36 +00002125 canonElementType.Quals);
Mike Stump1eb44332009-09-09 15:08:12 +00002126
John McCall3b657512011-01-19 10:06:00 +00002127 // If we didn't need extra canonicalization for the element type,
2128 // then just use that as our result.
John McCall200fa532012-02-08 00:46:36 +00002129 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall3b657512011-01-19 10:06:00 +00002130 return canon;
2131
2132 // Otherwise, we need to build a type which follows the spelling
2133 // of the element type.
2134 DependentSizedArrayType *sugaredType
2135 = new (*this, TypeAlignment)
2136 DependentSizedArrayType(*this, elementType, canon, numElements,
2137 ASM, elementTypeQuals, brackets);
2138 Types.push_back(sugaredType);
2139 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00002140}
2141
John McCall3b657512011-01-19 10:06:00 +00002142QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00002143 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002144 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002145 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002146 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002147
John McCall3b657512011-01-19 10:06:00 +00002148 void *insertPos = 0;
2149 if (IncompleteArrayType *iat =
2150 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2151 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002152
2153 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00002154 // either, so fill in the canonical type field. We also have to pull
2155 // qualifiers off the element type.
2156 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00002157
John McCall3b657512011-01-19 10:06:00 +00002158 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2159 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall200fa532012-02-08 00:46:36 +00002160 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002161 ASM, elementTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002162 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002163
2164 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00002165 IncompleteArrayType *existing =
2166 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2167 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00002168 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00002169
John McCall3b657512011-01-19 10:06:00 +00002170 IncompleteArrayType *newType = new (*this, TypeAlignment)
2171 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002172
John McCall3b657512011-01-19 10:06:00 +00002173 IncompleteArrayTypes.InsertNode(newType, insertPos);
2174 Types.push_back(newType);
2175 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00002176}
2177
Steve Naroff73322922007-07-18 18:00:27 +00002178/// getVectorType - Return the unique reference to a vector type of
2179/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00002180QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00002181 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00002182 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00002183
Reid Spencer5f016e22007-07-11 17:01:13 +00002184 // Check if we've already instantiated a vector of this type.
2185 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00002186 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00002187
Reid Spencer5f016e22007-07-11 17:01:13 +00002188 void *InsertPos = 0;
2189 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2190 return QualType(VTP, 0);
2191
2192 // If the element type isn't canonical, this won't be a canonical type either,
2193 // so fill in the canonical type field.
2194 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00002195 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00002196 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00002197
Reid Spencer5f016e22007-07-11 17:01:13 +00002198 // Get the new insert position for the node we care about.
2199 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002200 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002201 }
John McCall6b304a02009-09-24 23:30:46 +00002202 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00002203 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002204 VectorTypes.InsertNode(New, InsertPos);
2205 Types.push_back(New);
2206 return QualType(New, 0);
2207}
2208
Nate Begeman213541a2008-04-18 23:10:10 +00002209/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00002210/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002211QualType
2212ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00002213 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00002214
Steve Naroff73322922007-07-18 18:00:27 +00002215 // Check if we've already instantiated a vector of this type.
2216 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00002217 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00002218 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00002219 void *InsertPos = 0;
2220 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2221 return QualType(VTP, 0);
2222
2223 // If the element type isn't canonical, this won't be a canonical type either,
2224 // so fill in the canonical type field.
2225 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002226 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002227 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00002228
Steve Naroff73322922007-07-18 18:00:27 +00002229 // Get the new insert position for the node we care about.
2230 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002231 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00002232 }
John McCall6b304a02009-09-24 23:30:46 +00002233 ExtVectorType *New = new (*this, TypeAlignment)
2234 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00002235 VectorTypes.InsertNode(New, InsertPos);
2236 Types.push_back(New);
2237 return QualType(New, 0);
2238}
2239
Jay Foad4ba2a172011-01-12 09:06:06 +00002240QualType
2241ASTContext::getDependentSizedExtVectorType(QualType vecType,
2242 Expr *SizeExpr,
2243 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002244 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00002245 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002246 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002247
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002248 void *InsertPos = 0;
2249 DependentSizedExtVectorType *Canon
2250 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2251 DependentSizedExtVectorType *New;
2252 if (Canon) {
2253 // We already have a canonical version of this array type; use it as
2254 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00002255 New = new (*this, TypeAlignment)
2256 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2257 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002258 } else {
2259 QualType CanonVecTy = getCanonicalType(vecType);
2260 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00002261 New = new (*this, TypeAlignment)
2262 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2263 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002264
2265 DependentSizedExtVectorType *CanonCheck
2266 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2267 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2268 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002269 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2270 } else {
2271 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2272 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00002273 New = new (*this, TypeAlignment)
2274 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002275 }
2276 }
Mike Stump1eb44332009-09-09 15:08:12 +00002277
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002278 Types.push_back(New);
2279 return QualType(New, 0);
2280}
2281
Douglas Gregor72564e72009-02-26 23:50:07 +00002282/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00002283///
Jay Foad4ba2a172011-01-12 09:06:06 +00002284QualType
2285ASTContext::getFunctionNoProtoType(QualType ResultTy,
2286 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00002287 const CallingConv DefaultCC = Info.getCC();
2288 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2289 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00002290 // Unique functions, to guarantee there is only one function of a particular
2291 // structure.
2292 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00002293 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002294
Reid Spencer5f016e22007-07-11 17:01:13 +00002295 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002296 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00002297 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002298 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002299
Reid Spencer5f016e22007-07-11 17:01:13 +00002300 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00002301 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00002302 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00002303 Canonical =
2304 getFunctionNoProtoType(getCanonicalType(ResultTy),
2305 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00002306
Reid Spencer5f016e22007-07-11 17:01:13 +00002307 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002308 FunctionNoProtoType *NewIP =
2309 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002310 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002311 }
Mike Stump1eb44332009-09-09 15:08:12 +00002312
Roman Divackycfe9af22011-03-01 17:40:53 +00002313 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00002314 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00002315 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002316 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00002317 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002318 return QualType(New, 0);
2319}
2320
2321/// getFunctionType - Return a normal function type with a typed argument
2322/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00002323QualType
2324ASTContext::getFunctionType(QualType ResultTy,
2325 const QualType *ArgArray, unsigned NumArgs,
2326 const FunctionProtoType::ExtProtoInfo &EPI) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002327 // Unique functions, to guarantee there is only one function of a particular
2328 // structure.
2329 llvm::FoldingSetNodeID ID;
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002330 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00002331
2332 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002333 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00002334 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002335 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002336
2337 // Determine whether the type being created is already canonical or not.
Richard Smitheefb3d52012-02-10 09:58:53 +00002338 bool isCanonical =
2339 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2340 !EPI.HasTrailingReturn;
Reid Spencer5f016e22007-07-11 17:01:13 +00002341 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002342 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002343 isCanonical = false;
2344
Roman Divackycfe9af22011-03-01 17:40:53 +00002345 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2346 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2347 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002348
Reid Spencer5f016e22007-07-11 17:01:13 +00002349 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002350 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002351 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002352 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002353 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002354 CanonicalArgs.reserve(NumArgs);
2355 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002356 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002357
John McCalle23cf432010-12-14 08:05:40 +00002358 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +00002359 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002360 CanonicalEPI.ExceptionSpecType = EST_None;
2361 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002362 CanonicalEPI.ExtInfo
2363 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2364
Chris Lattnerf52ab252008-04-06 22:59:24 +00002365 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00002366 CanonicalArgs.data(), NumArgs,
John McCalle23cf432010-12-14 08:05:40 +00002367 CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002368
Reid Spencer5f016e22007-07-11 17:01:13 +00002369 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002370 FunctionProtoType *NewIP =
2371 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002372 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002373 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002374
John McCallf85e1932011-06-15 23:02:42 +00002375 // FunctionProtoType objects are allocated with extra bytes after
2376 // them for three variable size arrays at the end:
2377 // - parameter types
2378 // - exception types
2379 // - consumed-arguments flags
2380 // Instead of the exception types, there could be a noexcept
Richard Smithb9d0b762012-07-27 04:22:15 +00002381 // expression, or information used to resolve the exception
2382 // specification.
John McCalle23cf432010-12-14 08:05:40 +00002383 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002384 NumArgs * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002385 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redl60618fa2011-03-12 11:50:43 +00002386 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002387 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002388 Size += sizeof(Expr*);
Richard Smithe6975e92012-04-17 00:58:00 +00002389 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smith13bffc52012-04-19 00:08:28 +00002390 Size += 2 * sizeof(FunctionDecl*);
Richard Smithb9d0b762012-07-27 04:22:15 +00002391 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2392 Size += sizeof(FunctionDecl*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002393 }
John McCallf85e1932011-06-15 23:02:42 +00002394 if (EPI.ConsumedArguments)
2395 Size += NumArgs * sizeof(bool);
2396
John McCalle23cf432010-12-14 08:05:40 +00002397 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002398 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2399 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002400 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002401 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002402 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002403 return QualType(FTP, 0);
2404}
2405
John McCall3cb0ebd2010-03-10 03:28:59 +00002406#ifndef NDEBUG
2407static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2408 if (!isa<CXXRecordDecl>(D)) return false;
2409 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2410 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2411 return true;
2412 if (RD->getDescribedClassTemplate() &&
2413 !isa<ClassTemplateSpecializationDecl>(RD))
2414 return true;
2415 return false;
2416}
2417#endif
2418
2419/// getInjectedClassNameType - Return the unique reference to the
2420/// injected class name type for the specified templated declaration.
2421QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002422 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002423 assert(NeedsInjectedClassNameType(Decl));
2424 if (Decl->TypeForDecl) {
2425 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregoref96ee02012-01-14 16:38:05 +00002426 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002427 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2428 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2429 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2430 } else {
John McCallf4c73712011-01-19 06:33:43 +00002431 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002432 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002433 Decl->TypeForDecl = newType;
2434 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002435 }
2436 return QualType(Decl->TypeForDecl, 0);
2437}
2438
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002439/// getTypeDeclType - Return the unique reference to the type for the
2440/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002441QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002442 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002443 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002444
Richard Smith162e1c12011-04-15 14:24:37 +00002445 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002446 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002447
John McCallbecb8d52010-03-10 06:48:02 +00002448 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2449 "Template type parameter types are always available.");
2450
John McCall19c85762010-02-16 03:57:14 +00002451 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002452 assert(!Record->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002453 "struct/union has previous declaration");
2454 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002455 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002456 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002457 assert(!Enum->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002458 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002459 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002460 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002461 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002462 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2463 Decl->TypeForDecl = newType;
2464 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002465 } else
John McCallbecb8d52010-03-10 06:48:02 +00002466 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002467
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002468 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002469}
2470
Reid Spencer5f016e22007-07-11 17:01:13 +00002471/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002472/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002473QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002474ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2475 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002476 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002477
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002478 if (Canonical.isNull())
2479 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002480 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002481 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002482 Decl->TypeForDecl = newType;
2483 Types.push_back(newType);
2484 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002485}
2486
Jay Foad4ba2a172011-01-12 09:06:06 +00002487QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002488 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2489
Douglas Gregoref96ee02012-01-14 16:38:05 +00002490 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002491 if (PrevDecl->TypeForDecl)
2492 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2493
John McCallf4c73712011-01-19 06:33:43 +00002494 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2495 Decl->TypeForDecl = newType;
2496 Types.push_back(newType);
2497 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002498}
2499
Jay Foad4ba2a172011-01-12 09:06:06 +00002500QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002501 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2502
Douglas Gregoref96ee02012-01-14 16:38:05 +00002503 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002504 if (PrevDecl->TypeForDecl)
2505 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2506
John McCallf4c73712011-01-19 06:33:43 +00002507 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2508 Decl->TypeForDecl = newType;
2509 Types.push_back(newType);
2510 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002511}
2512
John McCall9d156a72011-01-06 01:58:22 +00002513QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2514 QualType modifiedType,
2515 QualType equivalentType) {
2516 llvm::FoldingSetNodeID id;
2517 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2518
2519 void *insertPos = 0;
2520 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2521 if (type) return QualType(type, 0);
2522
2523 QualType canon = getCanonicalType(equivalentType);
2524 type = new (*this, TypeAlignment)
2525 AttributedType(canon, attrKind, modifiedType, equivalentType);
2526
2527 Types.push_back(type);
2528 AttributedTypes.InsertNode(type, insertPos);
2529
2530 return QualType(type, 0);
2531}
2532
2533
John McCall49a832b2009-10-18 09:09:24 +00002534/// \brief Retrieve a substitution-result type.
2535QualType
2536ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002537 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002538 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002539 && "replacement types must always be canonical");
2540
2541 llvm::FoldingSetNodeID ID;
2542 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2543 void *InsertPos = 0;
2544 SubstTemplateTypeParmType *SubstParm
2545 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2546
2547 if (!SubstParm) {
2548 SubstParm = new (*this, TypeAlignment)
2549 SubstTemplateTypeParmType(Parm, Replacement);
2550 Types.push_back(SubstParm);
2551 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2552 }
2553
2554 return QualType(SubstParm, 0);
2555}
2556
Douglas Gregorc3069d62011-01-14 02:55:32 +00002557/// \brief Retrieve a
2558QualType ASTContext::getSubstTemplateTypeParmPackType(
2559 const TemplateTypeParmType *Parm,
2560 const TemplateArgument &ArgPack) {
2561#ifndef NDEBUG
2562 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2563 PEnd = ArgPack.pack_end();
2564 P != PEnd; ++P) {
2565 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2566 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2567 }
2568#endif
2569
2570 llvm::FoldingSetNodeID ID;
2571 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2572 void *InsertPos = 0;
2573 if (SubstTemplateTypeParmPackType *SubstParm
2574 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2575 return QualType(SubstParm, 0);
2576
2577 QualType Canon;
2578 if (!Parm->isCanonicalUnqualified()) {
2579 Canon = getCanonicalType(QualType(Parm, 0));
2580 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2581 ArgPack);
2582 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2583 }
2584
2585 SubstTemplateTypeParmPackType *SubstParm
2586 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2587 ArgPack);
2588 Types.push_back(SubstParm);
2589 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2590 return QualType(SubstParm, 0);
2591}
2592
Douglas Gregorfab9d672009-02-05 23:33:38 +00002593/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00002594/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002595/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00002596QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002597 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002598 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00002599 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002600 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002601 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002602 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00002603 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2604
2605 if (TypeParm)
2606 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002607
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002608 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002609 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002610 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002611
2612 TemplateTypeParmType *TypeCheck
2613 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2614 assert(!TypeCheck && "Template type parameter canonical type broken");
2615 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002616 } else
John McCall6b304a02009-09-24 23:30:46 +00002617 TypeParm = new (*this, TypeAlignment)
2618 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002619
2620 Types.push_back(TypeParm);
2621 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2622
2623 return QualType(TypeParm, 0);
2624}
2625
John McCall3cb0ebd2010-03-10 03:28:59 +00002626TypeSourceInfo *
2627ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2628 SourceLocation NameLoc,
2629 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002630 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002631 assert(!Name.getAsDependentTemplateName() &&
2632 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002633 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00002634
2635 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2636 TemplateSpecializationTypeLoc TL
2637 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002638 TL.setTemplateKeywordLoc(SourceLocation());
John McCall3cb0ebd2010-03-10 03:28:59 +00002639 TL.setTemplateNameLoc(NameLoc);
2640 TL.setLAngleLoc(Args.getLAngleLoc());
2641 TL.setRAngleLoc(Args.getRAngleLoc());
2642 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2643 TL.setArgLocInfo(i, Args[i].getLocInfo());
2644 return DI;
2645}
2646
Mike Stump1eb44332009-09-09 15:08:12 +00002647QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00002648ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00002649 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002650 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002651 assert(!Template.getAsDependentTemplateName() &&
2652 "No dependent template names here!");
2653
John McCalld5532b62009-11-23 01:53:49 +00002654 unsigned NumArgs = Args.size();
2655
Chris Lattner5f9e2722011-07-23 10:55:15 +00002656 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00002657 ArgVec.reserve(NumArgs);
2658 for (unsigned i = 0; i != NumArgs; ++i)
2659 ArgVec.push_back(Args[i].getArgument());
2660
John McCall31f17ec2010-04-27 00:57:59 +00002661 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002662 Underlying);
John McCall833ca992009-10-29 08:12:44 +00002663}
2664
Douglas Gregorb70126a2012-02-03 17:16:23 +00002665#ifndef NDEBUG
2666static bool hasAnyPackExpansions(const TemplateArgument *Args,
2667 unsigned NumArgs) {
2668 for (unsigned I = 0; I != NumArgs; ++I)
2669 if (Args[I].isPackExpansion())
2670 return true;
2671
2672 return true;
2673}
2674#endif
2675
John McCall833ca992009-10-29 08:12:44 +00002676QualType
2677ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002678 const TemplateArgument *Args,
2679 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002680 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002681 assert(!Template.getAsDependentTemplateName() &&
2682 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002683 // Look through qualified template names.
2684 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2685 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002686
Douglas Gregorb70126a2012-02-03 17:16:23 +00002687 bool IsTypeAlias =
Richard Smith3e4c6c42011-05-05 21:57:07 +00002688 Template.getAsTemplateDecl() &&
2689 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00002690 QualType CanonType;
2691 if (!Underlying.isNull())
2692 CanonType = getCanonicalType(Underlying);
2693 else {
Douglas Gregorb70126a2012-02-03 17:16:23 +00002694 // We can get here with an alias template when the specialization contains
2695 // a pack expansion that does not match up with a parameter pack.
2696 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2697 "Caller must compute aliased type");
2698 IsTypeAlias = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00002699 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2700 NumArgs);
2701 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00002702
Douglas Gregor1275ae02009-07-28 23:00:59 +00002703 // Allocate the (non-canonical) template specialization type, but don't
2704 // try to unique it: these types typically have location information that
2705 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00002706 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2707 sizeof(TemplateArgument) * NumArgs +
Douglas Gregorb70126a2012-02-03 17:16:23 +00002708 (IsTypeAlias? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00002709 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002710 TemplateSpecializationType *Spec
Douglas Gregorb70126a2012-02-03 17:16:23 +00002711 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2712 IsTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00002713
Douglas Gregor55f6b142009-02-09 18:46:07 +00002714 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002715 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00002716}
2717
Mike Stump1eb44332009-09-09 15:08:12 +00002718QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002719ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2720 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002721 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002722 assert(!Template.getAsDependentTemplateName() &&
2723 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002724
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002725 // Look through qualified template names.
2726 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2727 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002728
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002729 // Build the canonical template specialization type.
2730 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002731 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002732 CanonArgs.reserve(NumArgs);
2733 for (unsigned I = 0; I != NumArgs; ++I)
2734 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2735
2736 // Determine whether this canonical template specialization type already
2737 // exists.
2738 llvm::FoldingSetNodeID ID;
2739 TemplateSpecializationType::Profile(ID, CanonTemplate,
2740 CanonArgs.data(), NumArgs, *this);
2741
2742 void *InsertPos = 0;
2743 TemplateSpecializationType *Spec
2744 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2745
2746 if (!Spec) {
2747 // Allocate a new canonical template specialization type.
2748 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2749 sizeof(TemplateArgument) * NumArgs),
2750 TypeAlignment);
2751 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2752 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002753 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002754 Types.push_back(Spec);
2755 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2756 }
2757
2758 assert(Spec->isDependentType() &&
2759 "Non-dependent template-id type must have a canonical type");
2760 return QualType(Spec, 0);
2761}
2762
2763QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002764ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2765 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00002766 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00002767 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002768 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002769
2770 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002771 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002772 if (T)
2773 return QualType(T, 0);
2774
Douglas Gregor789b1f62010-02-04 18:10:26 +00002775 QualType Canon = NamedType;
2776 if (!Canon.isCanonical()) {
2777 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002778 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2779 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00002780 (void)CheckT;
2781 }
2782
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002783 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002784 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002785 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002786 return QualType(T, 0);
2787}
2788
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002789QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00002790ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002791 llvm::FoldingSetNodeID ID;
2792 ParenType::Profile(ID, InnerType);
2793
2794 void *InsertPos = 0;
2795 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2796 if (T)
2797 return QualType(T, 0);
2798
2799 QualType Canon = InnerType;
2800 if (!Canon.isCanonical()) {
2801 Canon = getCanonicalType(InnerType);
2802 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2803 assert(!CheckT && "Paren canonical type broken");
2804 (void)CheckT;
2805 }
2806
2807 T = new (*this) ParenType(InnerType, Canon);
2808 Types.push_back(T);
2809 ParenTypes.InsertNode(T, InsertPos);
2810 return QualType(T, 0);
2811}
2812
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002813QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2814 NestedNameSpecifier *NNS,
2815 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002816 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00002817 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2818
2819 if (Canon.isNull()) {
2820 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002821 ElaboratedTypeKeyword CanonKeyword = Keyword;
2822 if (Keyword == ETK_None)
2823 CanonKeyword = ETK_Typename;
2824
2825 if (CanonNNS != NNS || CanonKeyword != Keyword)
2826 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002827 }
2828
2829 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002830 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002831
2832 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002833 DependentNameType *T
2834 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00002835 if (T)
2836 return QualType(T, 0);
2837
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002838 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00002839 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00002840 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002841 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002842}
2843
Mike Stump1eb44332009-09-09 15:08:12 +00002844QualType
John McCall33500952010-06-11 00:33:02 +00002845ASTContext::getDependentTemplateSpecializationType(
2846 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002847 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00002848 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002849 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00002850 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00002851 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00002852 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2853 ArgCopy.push_back(Args[I].getArgument());
2854 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2855 ArgCopy.size(),
2856 ArgCopy.data());
2857}
2858
2859QualType
2860ASTContext::getDependentTemplateSpecializationType(
2861 ElaboratedTypeKeyword Keyword,
2862 NestedNameSpecifier *NNS,
2863 const IdentifierInfo *Name,
2864 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00002865 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00002866 assert((!NNS || NNS->isDependent()) &&
2867 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00002868
Douglas Gregor789b1f62010-02-04 18:10:26 +00002869 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00002870 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2871 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002872
2873 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00002874 DependentTemplateSpecializationType *T
2875 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002876 if (T)
2877 return QualType(T, 0);
2878
John McCall33500952010-06-11 00:33:02 +00002879 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002880
John McCall33500952010-06-11 00:33:02 +00002881 ElaboratedTypeKeyword CanonKeyword = Keyword;
2882 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2883
2884 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002885 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00002886 for (unsigned I = 0; I != NumArgs; ++I) {
2887 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2888 if (!CanonArgs[I].structurallyEquals(Args[I]))
2889 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00002890 }
2891
John McCall33500952010-06-11 00:33:02 +00002892 QualType Canon;
2893 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2894 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2895 Name, NumArgs,
2896 CanonArgs.data());
2897
2898 // Find the insert position again.
2899 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2900 }
2901
2902 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2903 sizeof(TemplateArgument) * NumArgs),
2904 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00002905 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00002906 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00002907 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00002908 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002909 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002910}
2911
Douglas Gregorcded4f62011-01-14 17:04:44 +00002912QualType ASTContext::getPackExpansionType(QualType Pattern,
2913 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00002914 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002915 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002916
2917 assert(Pattern->containsUnexpandedParameterPack() &&
2918 "Pack expansions must expand one or more parameter packs");
2919 void *InsertPos = 0;
2920 PackExpansionType *T
2921 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2922 if (T)
2923 return QualType(T, 0);
2924
2925 QualType Canon;
2926 if (!Pattern.isCanonical()) {
Richard Smithd8672ef2012-07-16 00:20:35 +00002927 Canon = getCanonicalType(Pattern);
2928 // The canonical type might not contain an unexpanded parameter pack, if it
2929 // contains an alias template specialization which ignores one of its
2930 // parameters.
2931 if (Canon->containsUnexpandedParameterPack()) {
2932 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002933
Richard Smithd8672ef2012-07-16 00:20:35 +00002934 // Find the insert position again, in case we inserted an element into
2935 // PackExpansionTypes and invalidated our insert position.
2936 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2937 }
Douglas Gregor7536dd52010-12-20 02:24:11 +00002938 }
2939
Douglas Gregorcded4f62011-01-14 17:04:44 +00002940 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002941 Types.push_back(T);
2942 PackExpansionTypes.InsertNode(T, InsertPos);
2943 return QualType(T, 0);
2944}
2945
Chris Lattner88cb27a2008-04-07 04:56:42 +00002946/// CmpProtocolNames - Comparison predicate for sorting protocols
2947/// alphabetically.
2948static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2949 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002950 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002951}
2952
John McCallc12c5bb2010-05-15 11:32:37 +00002953static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00002954 unsigned NumProtocols) {
2955 if (NumProtocols == 0) return true;
2956
Douglas Gregor61cc2962012-01-02 02:00:30 +00002957 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
2958 return false;
2959
John McCall54e14c42009-10-22 22:37:11 +00002960 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregor61cc2962012-01-02 02:00:30 +00002961 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
2962 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCall54e14c42009-10-22 22:37:11 +00002963 return false;
2964 return true;
2965}
2966
2967static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002968 unsigned &NumProtocols) {
2969 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002970
Chris Lattner88cb27a2008-04-07 04:56:42 +00002971 // Sort protocols, keyed by name.
2972 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2973
Douglas Gregor61cc2962012-01-02 02:00:30 +00002974 // Canonicalize.
2975 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
2976 Protocols[I] = Protocols[I]->getCanonicalDecl();
2977
Chris Lattner88cb27a2008-04-07 04:56:42 +00002978 // Remove duplicates.
2979 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2980 NumProtocols = ProtocolsEnd-Protocols;
2981}
2982
John McCallc12c5bb2010-05-15 11:32:37 +00002983QualType ASTContext::getObjCObjectType(QualType BaseType,
2984 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00002985 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002986 // If the base type is an interface and there aren't any protocols
2987 // to add, then the interface type will do just fine.
2988 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2989 return BaseType;
2990
2991 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002992 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002993 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002994 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002995 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2996 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002997
John McCallc12c5bb2010-05-15 11:32:37 +00002998 // Build the canonical type, which has the canonical base type and
2999 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00003000 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00003001 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3002 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3003 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003004 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00003005 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003006 unsigned UniqueCount = NumProtocols;
3007
John McCall54e14c42009-10-22 22:37:11 +00003008 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00003009 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3010 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00003011 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00003012 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3013 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003014 }
3015
3016 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00003017 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3018 }
3019
3020 unsigned Size = sizeof(ObjCObjectTypeImpl);
3021 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3022 void *Mem = Allocate(Size, TypeAlignment);
3023 ObjCObjectTypeImpl *T =
3024 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3025
3026 Types.push_back(T);
3027 ObjCObjectTypes.InsertNode(T, InsertPos);
3028 return QualType(T, 0);
3029}
3030
3031/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3032/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003033QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003034 llvm::FoldingSetNodeID ID;
3035 ObjCObjectPointerType::Profile(ID, ObjectT);
3036
3037 void *InsertPos = 0;
3038 if (ObjCObjectPointerType *QT =
3039 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3040 return QualType(QT, 0);
3041
3042 // Find the canonical object type.
3043 QualType Canonical;
3044 if (!ObjectT.isCanonical()) {
3045 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3046
3047 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00003048 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3049 }
3050
Douglas Gregorfd6a0882010-02-08 22:59:26 +00003051 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00003052 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3053 ObjCObjectPointerType *QType =
3054 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00003055
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003056 Types.push_back(QType);
3057 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00003058 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003059}
Chris Lattner88cb27a2008-04-07 04:56:42 +00003060
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003061/// getObjCInterfaceType - Return the unique reference to the type for the
3062/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregor0af55012011-12-16 03:12:41 +00003063QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3064 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003065 if (Decl->TypeForDecl)
3066 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003067
Douglas Gregor0af55012011-12-16 03:12:41 +00003068 if (PrevDecl) {
3069 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3070 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3071 return QualType(PrevDecl->TypeForDecl, 0);
3072 }
3073
Douglas Gregor8d2dbbf2011-12-16 16:34:57 +00003074 // Prefer the definition, if there is one.
3075 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3076 Decl = Def;
3077
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003078 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3079 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3080 Decl->TypeForDecl = T;
3081 Types.push_back(T);
3082 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00003083}
3084
Douglas Gregor72564e72009-02-26 23:50:07 +00003085/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3086/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00003087/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00003088/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003089/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003090QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003091 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00003092 if (tofExpr->isTypeDependent()) {
3093 llvm::FoldingSetNodeID ID;
3094 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00003095
Douglas Gregorb1975722009-07-30 23:18:24 +00003096 void *InsertPos = 0;
3097 DependentTypeOfExprType *Canon
3098 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3099 if (Canon) {
3100 // We already have a "canonical" version of an identical, dependent
3101 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00003102 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00003103 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003104 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00003105 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003106 Canon
3107 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00003108 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3109 toe = Canon;
3110 }
3111 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003112 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00003113 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00003114 }
Steve Naroff9752f252007-08-01 18:02:17 +00003115 Types.push_back(toe);
3116 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003117}
3118
Steve Naroff9752f252007-08-01 18:02:17 +00003119/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3120/// TypeOfType AST's. The only motivation to unique these nodes would be
3121/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003122/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003123/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003124QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00003125 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00003126 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00003127 Types.push_back(tot);
3128 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003129}
3130
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00003131
Anders Carlsson395b4752009-06-24 19:06:50 +00003132/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3133/// DecltypeType AST's. The only motivation to unique these nodes would be
3134/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003135/// an issue. This doesn't effect the type checker, since it operates
David Blaikie39e02032011-11-06 22:28:03 +00003136/// on canonical types (which are always unique).
Douglas Gregorf8af9822012-02-12 18:42:33 +00003137QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003138 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00003139
3140 // C++0x [temp.type]p2:
3141 // If an expression e involves a template parameter, decltype(e) denotes a
3142 // unique dependent type. Two such decltype-specifiers refer to the same
3143 // type only if their expressions are equivalent (14.5.6.1).
3144 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003145 llvm::FoldingSetNodeID ID;
3146 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00003147
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003148 void *InsertPos = 0;
3149 DependentDecltypeType *Canon
3150 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3151 if (Canon) {
3152 // We already have a "canonical" version of an equivalent, dependent
3153 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00003154 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003155 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003156 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003157 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003158 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003159 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3160 dt = Canon;
3161 }
3162 } else {
Douglas Gregorf8af9822012-02-12 18:42:33 +00003163 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3164 getCanonicalType(UnderlyingType));
Douglas Gregordd0257c2009-07-08 00:03:05 +00003165 }
Anders Carlsson395b4752009-06-24 19:06:50 +00003166 Types.push_back(dt);
3167 return QualType(dt, 0);
3168}
3169
Sean Huntca63c202011-05-24 22:41:36 +00003170/// getUnaryTransformationType - We don't unique these, since the memory
3171/// savings are minimal and these are rare.
3172QualType ASTContext::getUnaryTransformType(QualType BaseType,
3173 QualType UnderlyingType,
3174 UnaryTransformType::UTTKind Kind)
3175 const {
3176 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00003177 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3178 Kind,
3179 UnderlyingType->isDependentType() ?
Peter Collingbourne12fc4b02012-03-05 16:02:06 +00003180 QualType() : getCanonicalType(UnderlyingType));
Sean Huntca63c202011-05-24 22:41:36 +00003181 Types.push_back(Ty);
3182 return QualType(Ty, 0);
3183}
3184
Richard Smith483b9f32011-02-21 20:05:19 +00003185/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith34b41d92011-02-20 03:19:35 +00003186QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smith483b9f32011-02-21 20:05:19 +00003187 void *InsertPos = 0;
3188 if (!DeducedType.isNull()) {
3189 // Look in the folding set for an existing type.
3190 llvm::FoldingSetNodeID ID;
3191 AutoType::Profile(ID, DeducedType);
3192 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3193 return QualType(AT, 0);
3194 }
3195
3196 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3197 Types.push_back(AT);
3198 if (InsertPos)
3199 AutoTypes.InsertNode(AT, InsertPos);
3200 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00003201}
3202
Eli Friedmanb001de72011-10-06 23:00:33 +00003203/// getAtomicType - Return the uniqued reference to the atomic type for
3204/// the given value type.
3205QualType ASTContext::getAtomicType(QualType T) const {
3206 // Unique pointers, to guarantee there is only one pointer of a particular
3207 // structure.
3208 llvm::FoldingSetNodeID ID;
3209 AtomicType::Profile(ID, T);
3210
3211 void *InsertPos = 0;
3212 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3213 return QualType(AT, 0);
3214
3215 // If the atomic value type isn't canonical, this won't be a canonical type
3216 // either, so fill in the canonical type field.
3217 QualType Canonical;
3218 if (!T.isCanonical()) {
3219 Canonical = getAtomicType(getCanonicalType(T));
3220
3221 // Get the new insert position for the node we care about.
3222 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3223 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3224 }
3225 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3226 Types.push_back(New);
3227 AtomicTypes.InsertNode(New, InsertPos);
3228 return QualType(New, 0);
3229}
3230
Richard Smithad762fc2011-04-14 22:09:26 +00003231/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3232QualType ASTContext::getAutoDeductType() const {
3233 if (AutoDeductTy.isNull())
3234 AutoDeductTy = getAutoType(QualType());
3235 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3236 return AutoDeductTy;
3237}
3238
3239/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3240QualType ASTContext::getAutoRRefDeductType() const {
3241 if (AutoRRefDeductTy.isNull())
3242 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3243 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3244 return AutoRRefDeductTy;
3245}
3246
Reid Spencer5f016e22007-07-11 17:01:13 +00003247/// getTagDeclType - Return the unique reference to the type for the
3248/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00003249QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00003250 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00003251 // FIXME: What is the design on getTagDeclType when it requires casting
3252 // away const? mutable?
3253 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003254}
3255
Mike Stump1eb44332009-09-09 15:08:12 +00003256/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3257/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3258/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00003259CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003260 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00003261}
3262
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003263/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3264CanQualType ASTContext::getIntMaxType() const {
3265 return getFromTargetType(Target->getIntMaxType());
3266}
3267
3268/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3269CanQualType ASTContext::getUIntMaxType() const {
3270 return getFromTargetType(Target->getUIntMaxType());
3271}
3272
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00003273/// getSignedWCharType - Return the type of "signed wchar_t".
3274/// Used when in C++, as a GCC extension.
3275QualType ASTContext::getSignedWCharType() const {
3276 // FIXME: derive from "Target" ?
3277 return WCharTy;
3278}
3279
3280/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3281/// Used when in C++, as a GCC extension.
3282QualType ASTContext::getUnsignedWCharType() const {
3283 // FIXME: derive from "Target" ?
3284 return UnsignedIntTy;
3285}
3286
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003287/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattner8b9023b2007-07-13 03:05:23 +00003288/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3289QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003290 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00003291}
3292
Chris Lattnere6327742008-04-02 05:18:44 +00003293//===----------------------------------------------------------------------===//
3294// Type Operators
3295//===----------------------------------------------------------------------===//
3296
Jay Foad4ba2a172011-01-12 09:06:06 +00003297CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00003298 // Push qualifiers into arrays, and then discard any remaining
3299 // qualifiers.
3300 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003301 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00003302 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00003303 QualType Result;
3304 if (isa<ArrayType>(Ty)) {
3305 Result = getArrayDecayedType(QualType(Ty,0));
3306 } else if (isa<FunctionType>(Ty)) {
3307 Result = getPointerType(QualType(Ty, 0));
3308 } else {
3309 Result = QualType(Ty, 0);
3310 }
3311
3312 return CanQualType::CreateUnsafe(Result);
3313}
3314
John McCall62c28c82011-01-18 07:41:22 +00003315QualType ASTContext::getUnqualifiedArrayType(QualType type,
3316 Qualifiers &quals) {
3317 SplitQualType splitType = type.getSplitUnqualifiedType();
3318
3319 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3320 // the unqualified desugared type and then drops it on the floor.
3321 // We then have to strip that sugar back off with
3322 // getUnqualifiedDesugaredType(), which is silly.
3323 const ArrayType *AT =
John McCall200fa532012-02-08 00:46:36 +00003324 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall62c28c82011-01-18 07:41:22 +00003325
3326 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00003327 if (!AT) {
John McCall200fa532012-02-08 00:46:36 +00003328 quals = splitType.Quals;
3329 return QualType(splitType.Ty, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003330 }
3331
John McCall62c28c82011-01-18 07:41:22 +00003332 // Otherwise, recurse on the array's element type.
3333 QualType elementType = AT->getElementType();
3334 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3335
3336 // If that didn't change the element type, AT has no qualifiers, so we
3337 // can just use the results in splitType.
3338 if (elementType == unqualElementType) {
3339 assert(quals.empty()); // from the recursive call
John McCall200fa532012-02-08 00:46:36 +00003340 quals = splitType.Quals;
3341 return QualType(splitType.Ty, 0);
John McCall62c28c82011-01-18 07:41:22 +00003342 }
3343
3344 // Otherwise, add in the qualifiers from the outermost type, then
3345 // build the type back up.
John McCall200fa532012-02-08 00:46:36 +00003346 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003347
Douglas Gregor9dadd942010-05-17 18:45:21 +00003348 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003349 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003350 CAT->getSizeModifier(), 0);
3351 }
3352
Douglas Gregor9dadd942010-05-17 18:45:21 +00003353 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003354 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003355 }
3356
Douglas Gregor9dadd942010-05-17 18:45:21 +00003357 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003358 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003359 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003360 VAT->getSizeModifier(),
3361 VAT->getIndexTypeCVRQualifiers(),
3362 VAT->getBracketsRange());
3363 }
3364
3365 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003366 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003367 DSAT->getSizeModifier(), 0,
3368 SourceRange());
3369}
3370
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003371/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3372/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3373/// they point to and return true. If T1 and T2 aren't pointer types
3374/// or pointer-to-member types, or if they are not similar at this
3375/// level, returns false and leaves T1 and T2 unchanged. Top-level
3376/// qualifiers on T1 and T2 are ignored. This function will typically
3377/// be called in a loop that successively "unwraps" pointer and
3378/// pointer-to-member types to compare them at each level.
3379bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3380 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3381 *T2PtrType = T2->getAs<PointerType>();
3382 if (T1PtrType && T2PtrType) {
3383 T1 = T1PtrType->getPointeeType();
3384 T2 = T2PtrType->getPointeeType();
3385 return true;
3386 }
3387
3388 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3389 *T2MPType = T2->getAs<MemberPointerType>();
3390 if (T1MPType && T2MPType &&
3391 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3392 QualType(T2MPType->getClass(), 0))) {
3393 T1 = T1MPType->getPointeeType();
3394 T2 = T2MPType->getPointeeType();
3395 return true;
3396 }
3397
David Blaikie4e4d0842012-03-11 07:00:24 +00003398 if (getLangOpts().ObjC1) {
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003399 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3400 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3401 if (T1OPType && T2OPType) {
3402 T1 = T1OPType->getPointeeType();
3403 T2 = T2OPType->getPointeeType();
3404 return true;
3405 }
3406 }
3407
3408 // FIXME: Block pointers, too?
3409
3410 return false;
3411}
3412
Jay Foad4ba2a172011-01-12 09:06:06 +00003413DeclarationNameInfo
3414ASTContext::getNameForTemplate(TemplateName Name,
3415 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003416 switch (Name.getKind()) {
3417 case TemplateName::QualifiedTemplate:
3418 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003419 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003420 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3421 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003422
John McCall14606042011-06-30 08:33:18 +00003423 case TemplateName::OverloadedTemplate: {
3424 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3425 // DNInfo work in progress: CHECKME: what about DNLoc?
3426 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3427 }
3428
3429 case TemplateName::DependentTemplate: {
3430 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003431 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003432 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003433 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3434 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003435 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003436 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3437 // DNInfo work in progress: FIXME: source locations?
3438 DeclarationNameLoc DNLoc;
3439 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3440 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3441 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003442 }
3443 }
3444
John McCall14606042011-06-30 08:33:18 +00003445 case TemplateName::SubstTemplateTemplateParm: {
3446 SubstTemplateTemplateParmStorage *subst
3447 = Name.getAsSubstTemplateTemplateParm();
3448 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3449 NameLoc);
3450 }
3451
3452 case TemplateName::SubstTemplateTemplateParmPack: {
3453 SubstTemplateTemplateParmPackStorage *subst
3454 = Name.getAsSubstTemplateTemplateParmPack();
3455 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3456 NameLoc);
3457 }
3458 }
3459
3460 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003461}
3462
Jay Foad4ba2a172011-01-12 09:06:06 +00003463TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003464 switch (Name.getKind()) {
3465 case TemplateName::QualifiedTemplate:
3466 case TemplateName::Template: {
3467 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003468 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003469 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003470 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3471
3472 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003473 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003474 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003475
John McCall14606042011-06-30 08:33:18 +00003476 case TemplateName::OverloadedTemplate:
3477 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003478
John McCall14606042011-06-30 08:33:18 +00003479 case TemplateName::DependentTemplate: {
3480 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3481 assert(DTN && "Non-dependent template names must refer to template decls.");
3482 return DTN->CanonicalTemplateName;
3483 }
3484
3485 case TemplateName::SubstTemplateTemplateParm: {
3486 SubstTemplateTemplateParmStorage *subst
3487 = Name.getAsSubstTemplateTemplateParm();
3488 return getCanonicalTemplateName(subst->getReplacement());
3489 }
3490
3491 case TemplateName::SubstTemplateTemplateParmPack: {
3492 SubstTemplateTemplateParmPackStorage *subst
3493 = Name.getAsSubstTemplateTemplateParmPack();
3494 TemplateTemplateParmDecl *canonParameter
3495 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3496 TemplateArgument canonArgPack
3497 = getCanonicalTemplateArgument(subst->getArgumentPack());
3498 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3499 }
3500 }
3501
3502 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003503}
3504
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003505bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3506 X = getCanonicalTemplateName(X);
3507 Y = getCanonicalTemplateName(Y);
3508 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3509}
3510
Mike Stump1eb44332009-09-09 15:08:12 +00003511TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003512ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003513 switch (Arg.getKind()) {
3514 case TemplateArgument::Null:
3515 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003516
Douglas Gregor1275ae02009-07-28 23:00:59 +00003517 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003518 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003519
Douglas Gregord2008e22012-04-06 22:40:38 +00003520 case TemplateArgument::Declaration: {
3521 if (Decl *D = Arg.getAsDecl())
3522 return TemplateArgument(D->getCanonicalDecl());
3523 return TemplateArgument((Decl*)0);
3524 }
Mike Stump1eb44332009-09-09 15:08:12 +00003525
Douglas Gregor788cd062009-11-11 01:00:40 +00003526 case TemplateArgument::Template:
3527 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00003528
3529 case TemplateArgument::TemplateExpansion:
3530 return TemplateArgument(getCanonicalTemplateName(
3531 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00003532 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00003533
Douglas Gregor1275ae02009-07-28 23:00:59 +00003534 case TemplateArgument::Integral:
Benjamin Kramer85524372012-06-07 15:09:51 +00003535 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003536
Douglas Gregor1275ae02009-07-28 23:00:59 +00003537 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00003538 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003539
Douglas Gregor1275ae02009-07-28 23:00:59 +00003540 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00003541 if (Arg.pack_size() == 0)
3542 return Arg;
3543
Douglas Gregor910f8002010-11-07 23:05:16 +00003544 TemplateArgument *CanonArgs
3545 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00003546 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003547 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003548 AEnd = Arg.pack_end();
3549 A != AEnd; (void)++A, ++Idx)
3550 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00003551
Douglas Gregor910f8002010-11-07 23:05:16 +00003552 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00003553 }
3554 }
3555
3556 // Silence GCC warning
David Blaikieb219cfc2011-09-23 05:06:16 +00003557 llvm_unreachable("Unhandled template argument kind");
Douglas Gregor1275ae02009-07-28 23:00:59 +00003558}
3559
Douglas Gregord57959a2009-03-27 23:10:48 +00003560NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00003561ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00003562 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00003563 return 0;
3564
3565 switch (NNS->getKind()) {
3566 case NestedNameSpecifier::Identifier:
3567 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00003568 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00003569 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3570 NNS->getAsIdentifier());
3571
3572 case NestedNameSpecifier::Namespace:
3573 // A namespace is canonical; build a nested-name-specifier with
3574 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00003575 return NestedNameSpecifier::Create(*this, 0,
3576 NNS->getAsNamespace()->getOriginalNamespace());
3577
3578 case NestedNameSpecifier::NamespaceAlias:
3579 // A namespace is canonical; build a nested-name-specifier with
3580 // this namespace and no prefix.
3581 return NestedNameSpecifier::Create(*this, 0,
3582 NNS->getAsNamespaceAlias()->getNamespace()
3583 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00003584
3585 case NestedNameSpecifier::TypeSpec:
3586 case NestedNameSpecifier::TypeSpecWithTemplate: {
3587 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00003588
3589 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3590 // break it apart into its prefix and identifier, then reconsititute those
3591 // as the canonical nested-name-specifier. This is required to canonicalize
3592 // a dependent nested-name-specifier involving typedefs of dependent-name
3593 // types, e.g.,
3594 // typedef typename T::type T1;
3595 // typedef typename T1::type T2;
Eli Friedman16412ef2012-03-03 04:09:56 +00003596 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3597 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor264bf662010-11-04 00:09:33 +00003598 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor264bf662010-11-04 00:09:33 +00003599
Eli Friedman16412ef2012-03-03 04:09:56 +00003600 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3601 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3602 // first place?
John McCall3b657512011-01-19 10:06:00 +00003603 return NestedNameSpecifier::Create(*this, 0, false,
3604 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00003605 }
3606
3607 case NestedNameSpecifier::Global:
3608 // The global specifier is canonical and unique.
3609 return NNS;
3610 }
3611
David Blaikie7530c032012-01-17 06:56:22 +00003612 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregord57959a2009-03-27 23:10:48 +00003613}
3614
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003615
Jay Foad4ba2a172011-01-12 09:06:06 +00003616const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003617 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003618 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003619 // Handle the common positive case fast.
3620 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3621 return AT;
3622 }
Mike Stump1eb44332009-09-09 15:08:12 +00003623
John McCall0953e762009-09-24 19:53:00 +00003624 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00003625 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003626 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003627
John McCall0953e762009-09-24 19:53:00 +00003628 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003629 // implements C99 6.7.3p8: "If the specification of an array type includes
3630 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00003631
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003632 // If we get here, we either have type qualifiers on the type, or we have
3633 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00003634 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00003635
John McCall3b657512011-01-19 10:06:00 +00003636 SplitQualType split = T.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00003637 Qualifiers qs = split.Quals;
Mike Stump1eb44332009-09-09 15:08:12 +00003638
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003639 // If we have a simple case, just return now.
John McCall200fa532012-02-08 00:46:36 +00003640 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall3b657512011-01-19 10:06:00 +00003641 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003642 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00003643
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003644 // Otherwise, we have an array and we have qualifiers on it. Push the
3645 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00003646 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00003647
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003648 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3649 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3650 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003651 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003652 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3653 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3654 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003655 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00003656
Mike Stump1eb44332009-09-09 15:08:12 +00003657 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00003658 = dyn_cast<DependentSizedArrayType>(ATy))
3659 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00003660 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003661 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00003662 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003663 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003664 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00003665
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003666 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003667 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003668 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003669 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003670 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003671 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00003672}
3673
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00003674QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00003675 // C99 6.7.5.3p7:
3676 // A declaration of a parameter as "array of type" shall be
3677 // adjusted to "qualified pointer to type", where the type
3678 // qualifiers (if any) are those specified within the [ and ] of
3679 // the array type derivation.
3680 if (T->isArrayType())
3681 return getArrayDecayedType(T);
3682
3683 // C99 6.7.5.3p8:
3684 // A declaration of a parameter as "function returning type"
3685 // shall be adjusted to "pointer to function returning type", as
3686 // in 6.3.2.1.
3687 if (T->isFunctionType())
3688 return getPointerType(T);
3689
3690 return T;
3691}
3692
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00003693QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00003694 T = getVariableArrayDecayedType(T);
3695 T = getAdjustedParameterType(T);
3696 return T.getUnqualifiedType();
3697}
3698
Chris Lattnere6327742008-04-02 05:18:44 +00003699/// getArrayDecayedType - Return the properly qualified result of decaying the
3700/// specified array type to a pointer. This operation is non-trivial when
3701/// handling typedefs etc. The canonical type of "T" must be an array type,
3702/// this returns a pointer to a properly qualified element of the array.
3703///
3704/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00003705QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003706 // Get the element type with 'getAsArrayType' so that we don't lose any
3707 // typedefs in the element type of the array. This also handles propagation
3708 // of type qualifiers from the array type into the element type if present
3709 // (C99 6.7.3p8).
3710 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3711 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00003712
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003713 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00003714
3715 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00003716 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00003717}
3718
John McCall3b657512011-01-19 10:06:00 +00003719QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3720 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00003721}
3722
John McCall3b657512011-01-19 10:06:00 +00003723QualType ASTContext::getBaseElementType(QualType type) const {
3724 Qualifiers qs;
3725 while (true) {
3726 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00003727 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall3b657512011-01-19 10:06:00 +00003728 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00003729
John McCall3b657512011-01-19 10:06:00 +00003730 type = array->getElementType();
John McCall200fa532012-02-08 00:46:36 +00003731 qs.addConsistentQualifiers(split.Quals);
John McCall3b657512011-01-19 10:06:00 +00003732 }
Mike Stump1eb44332009-09-09 15:08:12 +00003733
John McCall3b657512011-01-19 10:06:00 +00003734 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00003735}
3736
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003737/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00003738uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003739ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3740 uint64_t ElementCount = 1;
3741 do {
3742 ElementCount *= CA->getSize().getZExtValue();
3743 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3744 } while (CA);
3745 return ElementCount;
3746}
3747
Reid Spencer5f016e22007-07-11 17:01:13 +00003748/// getFloatingRank - Return a relative rank for floating point types.
3749/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00003750static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00003751 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00003752 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00003753
John McCall183700f2009-09-21 23:43:11 +00003754 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3755 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003756 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00003757 case BuiltinType::Half: return HalfRank;
Reid Spencer5f016e22007-07-11 17:01:13 +00003758 case BuiltinType::Float: return FloatRank;
3759 case BuiltinType::Double: return DoubleRank;
3760 case BuiltinType::LongDouble: return LongDoubleRank;
3761 }
3762}
3763
Mike Stump1eb44332009-09-09 15:08:12 +00003764/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3765/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00003766/// 'typeDomain' is a real floating point or complex type.
3767/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00003768QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3769 QualType Domain) const {
3770 FloatingRank EltRank = getFloatingRank(Size);
3771 if (Domain->isComplexType()) {
3772 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00003773 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Narofff1448a02007-08-27 01:27:54 +00003774 case FloatRank: return FloatComplexTy;
3775 case DoubleRank: return DoubleComplexTy;
3776 case LongDoubleRank: return LongDoubleComplexTy;
3777 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003778 }
Chris Lattner1361b112008-04-06 23:58:54 +00003779
3780 assert(Domain->isRealFloatingType() && "Unknown domain!");
3781 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00003782 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattner1361b112008-04-06 23:58:54 +00003783 case FloatRank: return FloatTy;
3784 case DoubleRank: return DoubleTy;
3785 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00003786 }
David Blaikie561d3ab2012-01-17 02:30:50 +00003787 llvm_unreachable("getFloatingRank(): illegal value for rank");
Reid Spencer5f016e22007-07-11 17:01:13 +00003788}
3789
Chris Lattner7cfeb082008-04-06 23:55:33 +00003790/// getFloatingTypeOrder - Compare the rank of the two specified floating
3791/// point types, ignoring the domain of the type (i.e. 'double' ==
3792/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003793/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003794int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00003795 FloatingRank LHSR = getFloatingRank(LHS);
3796 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00003797
Chris Lattnera75cea32008-04-06 23:38:49 +00003798 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003799 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00003800 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003801 return 1;
3802 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003803}
3804
Chris Lattnerf52ab252008-04-06 22:59:24 +00003805/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3806/// routine will assert if passed a built-in type that isn't an integer or enum,
3807/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00003808unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00003809 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00003810
Chris Lattnerf52ab252008-04-06 22:59:24 +00003811 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003812 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattner7cfeb082008-04-06 23:55:33 +00003813 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003814 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003815 case BuiltinType::Char_S:
3816 case BuiltinType::Char_U:
3817 case BuiltinType::SChar:
3818 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003819 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003820 case BuiltinType::Short:
3821 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003822 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003823 case BuiltinType::Int:
3824 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003825 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003826 case BuiltinType::Long:
3827 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003828 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003829 case BuiltinType::LongLong:
3830 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003831 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00003832 case BuiltinType::Int128:
3833 case BuiltinType::UInt128:
3834 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00003835 }
3836}
3837
Eli Friedman04e83572009-08-20 04:21:42 +00003838/// \brief Whether this is a promotable bitfield reference according
3839/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3840///
3841/// \returns the type this bit-field will promote to, or NULL if no
3842/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00003843QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00003844 if (E->isTypeDependent() || E->isValueDependent())
3845 return QualType();
3846
Eli Friedman04e83572009-08-20 04:21:42 +00003847 FieldDecl *Field = E->getBitField();
3848 if (!Field)
3849 return QualType();
3850
3851 QualType FT = Field->getType();
3852
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003853 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman04e83572009-08-20 04:21:42 +00003854 uint64_t IntSize = getTypeSize(IntTy);
3855 // GCC extension compatibility: if the bit-field size is less than or equal
3856 // to the size of int, it gets promoted no matter what its type is.
3857 // For instance, unsigned long bf : 4 gets promoted to signed int.
3858 if (BitWidth < IntSize)
3859 return IntTy;
3860
3861 if (BitWidth == IntSize)
3862 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3863
3864 // Types bigger than int are not subject to promotions, and therefore act
3865 // like the base type.
3866 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3867 // is ridiculous.
3868 return QualType();
3869}
3870
Eli Friedmana95d7572009-08-19 07:44:53 +00003871/// getPromotedIntegerType - Returns the type that Promotable will
3872/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3873/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003874QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00003875 assert(!Promotable.isNull());
3876 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00003877 if (const EnumType *ET = Promotable->getAs<EnumType>())
3878 return ET->getDecl()->getPromotionType();
Eli Friedman68a2dc42011-10-26 07:22:48 +00003879
3880 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3881 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3882 // (3.9.1) can be converted to a prvalue of the first of the following
3883 // types that can represent all the values of its underlying type:
3884 // int, unsigned int, long int, unsigned long int, long long int, or
3885 // unsigned long long int [...]
3886 // FIXME: Is there some better way to compute this?
3887 if (BT->getKind() == BuiltinType::WChar_S ||
3888 BT->getKind() == BuiltinType::WChar_U ||
3889 BT->getKind() == BuiltinType::Char16 ||
3890 BT->getKind() == BuiltinType::Char32) {
3891 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3892 uint64_t FromSize = getTypeSize(BT);
3893 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3894 LongLongTy, UnsignedLongLongTy };
3895 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3896 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3897 if (FromSize < ToSize ||
3898 (FromSize == ToSize &&
3899 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3900 return PromoteTypes[Idx];
3901 }
3902 llvm_unreachable("char type should fit into long long");
3903 }
3904 }
3905
3906 // At this point, we should have a signed or unsigned integer type.
Eli Friedmana95d7572009-08-19 07:44:53 +00003907 if (Promotable->isSignedIntegerType())
3908 return IntTy;
3909 uint64_t PromotableSize = getTypeSize(Promotable);
3910 uint64_t IntSize = getTypeSize(IntTy);
3911 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3912 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3913}
3914
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003915/// \brief Recurses in pointer/array types until it finds an objc retainable
3916/// type and returns its ownership.
3917Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3918 while (!T.isNull()) {
3919 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3920 return T.getObjCLifetime();
3921 if (T->isArrayType())
3922 T = getBaseElementType(T);
3923 else if (const PointerType *PT = T->getAs<PointerType>())
3924 T = PT->getPointeeType();
3925 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00003926 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003927 else
3928 break;
3929 }
3930
3931 return Qualifiers::OCL_None;
3932}
3933
Mike Stump1eb44332009-09-09 15:08:12 +00003934/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00003935/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003936/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003937int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00003938 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3939 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00003940 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003941
Chris Lattnerf52ab252008-04-06 22:59:24 +00003942 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3943 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00003944
Chris Lattner7cfeb082008-04-06 23:55:33 +00003945 unsigned LHSRank = getIntegerRank(LHSC);
3946 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00003947
Chris Lattner7cfeb082008-04-06 23:55:33 +00003948 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3949 if (LHSRank == RHSRank) return 0;
3950 return LHSRank > RHSRank ? 1 : -1;
3951 }
Mike Stump1eb44332009-09-09 15:08:12 +00003952
Chris Lattner7cfeb082008-04-06 23:55:33 +00003953 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3954 if (LHSUnsigned) {
3955 // If the unsigned [LHS] type is larger, return it.
3956 if (LHSRank >= RHSRank)
3957 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00003958
Chris Lattner7cfeb082008-04-06 23:55:33 +00003959 // If the signed type can represent all values of the unsigned type, it
3960 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003961 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003962 return -1;
3963 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00003964
Chris Lattner7cfeb082008-04-06 23:55:33 +00003965 // If the unsigned [RHS] type is larger, return it.
3966 if (RHSRank >= LHSRank)
3967 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00003968
Chris Lattner7cfeb082008-04-06 23:55:33 +00003969 // If the signed type can represent all values of the unsigned type, it
3970 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003971 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003972 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003973}
Anders Carlsson71993dd2007-08-17 05:31:46 +00003974
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003975static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003976CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3977 DeclContext *DC, IdentifierInfo *Id) {
3978 SourceLocation Loc;
David Blaikie4e4d0842012-03-11 07:00:24 +00003979 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003980 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003981 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003982 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003983}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003984
Mike Stump1eb44332009-09-09 15:08:12 +00003985// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00003986QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00003987 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003988 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003989 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003990 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00003991 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003992
Anders Carlssonf06273f2007-11-19 00:25:30 +00003993 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00003994
Anders Carlsson71993dd2007-08-17 05:31:46 +00003995 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00003996 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00003997 // int flags;
3998 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00003999 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00004000 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00004001 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00004002 FieldTypes[3] = LongTy;
4003
Anders Carlsson71993dd2007-08-17 05:31:46 +00004004 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00004005 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00004006 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004007 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00004008 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00004009 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00004010 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004011 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004012 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004013 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004014 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00004015 }
4016
Douglas Gregor838db382010-02-11 01:19:42 +00004017 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00004018 }
Mike Stump1eb44332009-09-09 15:08:12 +00004019
Anders Carlsson71993dd2007-08-17 05:31:46 +00004020 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00004021}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004022
Douglas Gregor319ac892009-04-23 22:29:11 +00004023void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004024 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00004025 assert(Rec && "Invalid CFConstantStringType");
4026 CFConstantStringTypeDecl = Rec->getDecl();
4027}
4028
Jay Foad4ba2a172011-01-12 09:06:06 +00004029QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00004030 if (BlockDescriptorType)
4031 return getTagDeclType(BlockDescriptorType);
4032
4033 RecordDecl *T;
4034 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004035 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004036 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00004037 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004038
4039 QualType FieldTypes[] = {
4040 UnsignedLongTy,
4041 UnsignedLongTy,
4042 };
4043
4044 const char *FieldNames[] = {
4045 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00004046 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00004047 };
4048
4049 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004050 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00004051 SourceLocation(),
4052 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004053 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00004054 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004055 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004056 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004057 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00004058 T->addDecl(Field);
4059 }
4060
Douglas Gregor838db382010-02-11 01:19:42 +00004061 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004062
4063 BlockDescriptorType = T;
4064
4065 return getTagDeclType(BlockDescriptorType);
4066}
4067
Jay Foad4ba2a172011-01-12 09:06:06 +00004068QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00004069 if (BlockDescriptorExtendedType)
4070 return getTagDeclType(BlockDescriptorExtendedType);
4071
4072 RecordDecl *T;
4073 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004074 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004075 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00004076 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004077
4078 QualType FieldTypes[] = {
4079 UnsignedLongTy,
4080 UnsignedLongTy,
4081 getPointerType(VoidPtrTy),
4082 getPointerType(VoidPtrTy)
4083 };
4084
4085 const char *FieldNames[] = {
4086 "reserved",
4087 "Size",
4088 "CopyFuncPtr",
4089 "DestroyFuncPtr"
4090 };
4091
4092 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004093 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00004094 SourceLocation(),
4095 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004096 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00004097 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004098 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004099 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004100 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00004101 T->addDecl(Field);
4102 }
4103
Douglas Gregor838db382010-02-11 01:19:42 +00004104 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004105
4106 BlockDescriptorExtendedType = T;
4107
4108 return getTagDeclType(BlockDescriptorExtendedType);
4109}
4110
Jay Foad4ba2a172011-01-12 09:06:06 +00004111bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCallf85e1932011-06-15 23:02:42 +00004112 if (Ty->isObjCRetainableType())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004113 return true;
David Blaikie4e4d0842012-03-11 07:00:24 +00004114 if (getLangOpts().CPlusPlus) {
Fariborz Jahaniane38be612010-11-17 00:21:28 +00004115 if (const RecordType *RT = Ty->getAs<RecordType>()) {
4116 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Huntffe37fd2011-05-25 20:50:04 +00004117 return RD->hasConstCopyConstructor();
Fariborz Jahaniane38be612010-11-17 00:21:28 +00004118
4119 }
4120 }
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004121 return false;
4122}
4123
Jay Foad4ba2a172011-01-12 09:06:06 +00004124QualType
Chris Lattner5f9e2722011-07-23 10:55:15 +00004125ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004126 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00004127 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004128 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00004129 // unsigned int __flags;
4130 // unsigned int __size;
Eli Friedmana7e68452010-08-22 01:00:03 +00004131 // void *__copy_helper; // as needed
4132 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004133 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00004134 // } *
4135
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004136 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
4137
4138 // FIXME: Move up
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00004139 SmallString<36> Name;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00004140 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
4141 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004142 RecordDecl *T;
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004143 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004144 T->startDefinition();
4145 QualType Int32Ty = IntTy;
4146 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
4147 QualType FieldTypes[] = {
4148 getPointerType(VoidPtrTy),
4149 getPointerType(getTagDeclType(T)),
4150 Int32Ty,
4151 Int32Ty,
4152 getPointerType(VoidPtrTy),
4153 getPointerType(VoidPtrTy),
4154 Ty
4155 };
4156
Chris Lattner5f9e2722011-07-23 10:55:15 +00004157 StringRef FieldNames[] = {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004158 "__isa",
4159 "__forwarding",
4160 "__flags",
4161 "__size",
4162 "__copy_helper",
4163 "__destroy_helper",
4164 DeclName,
4165 };
4166
4167 for (size_t i = 0; i < 7; ++i) {
4168 if (!HasCopyAndDispose && i >=4 && i <= 5)
4169 continue;
4170 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004171 SourceLocation(),
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004172 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004173 FieldTypes[i], /*TInfo=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004174 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004175 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004176 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004177 T->addDecl(Field);
4178 }
4179
Douglas Gregor838db382010-02-11 01:19:42 +00004180 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004181
4182 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00004183}
4184
Douglas Gregore97179c2011-09-08 01:46:34 +00004185TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4186 if (!ObjCInstanceTypeDecl)
4187 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4188 getTranslationUnitDecl(),
4189 SourceLocation(),
4190 SourceLocation(),
4191 &Idents.get("instancetype"),
4192 getTrivialTypeSourceInfo(getObjCIdType()));
4193 return ObjCInstanceTypeDecl;
4194}
4195
Anders Carlssone8c49532007-10-29 06:33:42 +00004196// This returns true if a type has been typedefed to BOOL:
4197// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00004198static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00004199 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00004200 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4201 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00004202
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004203 return false;
4204}
4205
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004206/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004207/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00004208CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00004209 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4210 return CharUnits::Zero();
4211
Ken Dyck199c3d62010-01-11 17:06:35 +00004212 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00004213
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004214 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004215 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004216 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004217 // Treat arrays as pointers, since that's how they're passed in.
4218 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004219 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004220 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00004221}
4222
4223static inline
4224std::string charUnitsToString(const CharUnits &CU) {
4225 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004226}
4227
John McCall6b5a61b2011-02-07 10:33:21 +00004228/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00004229/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00004230std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4231 std::string S;
4232
David Chisnall5e530af2009-11-17 19:33:30 +00004233 const BlockDecl *Decl = Expr->getBlockDecl();
4234 QualType BlockTy =
4235 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4236 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00004237 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00004238 // Compute size of all parameters.
4239 // Start with computing size of a pointer in number of bytes.
4240 // FIXME: There might(should) be a better way of doing this computation!
4241 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004242 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4243 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00004244 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00004245 E = Decl->param_end(); PI != E; ++PI) {
4246 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004247 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahanian075a5432012-06-30 00:48:59 +00004248 if (sz.isZero())
4249 continue;
Ken Dyck199c3d62010-01-11 17:06:35 +00004250 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00004251 ParmOffset += sz;
4252 }
4253 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00004254 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00004255 // Block pointer and offset.
4256 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00004257
4258 // Argument types.
4259 ParmOffset = PtrSize;
4260 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4261 Decl->param_end(); PI != E; ++PI) {
4262 ParmVarDecl *PVDecl = *PI;
4263 QualType PType = PVDecl->getOriginalType();
4264 if (const ArrayType *AT =
4265 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4266 // Use array's original type only if it has known number of
4267 // elements.
4268 if (!isa<ConstantArrayType>(AT))
4269 PType = PVDecl->getType();
4270 } else if (PType->isFunctionType())
4271 PType = PVDecl->getType();
4272 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004273 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004274 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00004275 }
John McCall6b5a61b2011-02-07 10:33:21 +00004276
4277 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00004278}
4279
Douglas Gregorf968d832011-05-27 01:19:52 +00004280bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00004281 std::string& S) {
4282 // Encode result type.
4283 getObjCEncodingForType(Decl->getResultType(), S);
4284 CharUnits ParmOffset;
4285 // Compute size of all parameters.
4286 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4287 E = Decl->param_end(); PI != E; ++PI) {
4288 QualType PType = (*PI)->getType();
4289 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004290 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004291 continue;
4292
David Chisnall5389f482010-12-30 14:05:53 +00004293 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00004294 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00004295 ParmOffset += sz;
4296 }
4297 S += charUnitsToString(ParmOffset);
4298 ParmOffset = CharUnits::Zero();
4299
4300 // Argument types.
4301 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4302 E = Decl->param_end(); PI != E; ++PI) {
4303 ParmVarDecl *PVDecl = *PI;
4304 QualType PType = PVDecl->getOriginalType();
4305 if (const ArrayType *AT =
4306 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4307 // Use array's original type only if it has known number of
4308 // elements.
4309 if (!isa<ConstantArrayType>(AT))
4310 PType = PVDecl->getType();
4311 } else if (PType->isFunctionType())
4312 PType = PVDecl->getType();
4313 getObjCEncodingForType(PType, S);
4314 S += charUnitsToString(ParmOffset);
4315 ParmOffset += getObjCEncodingTypeSize(PType);
4316 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004317
4318 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004319}
4320
Bob Wilsondc8dab62011-11-30 01:57:58 +00004321/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4322/// method parameter or return type. If Extended, include class names and
4323/// block object types.
4324void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4325 QualType T, std::string& S,
4326 bool Extended) const {
4327 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4328 getObjCEncodingForTypeQualifier(QT, S);
4329 // Encode parameter type.
4330 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4331 true /*OutermostType*/,
4332 false /*EncodingProperty*/,
4333 false /*StructField*/,
4334 Extended /*EncodeBlockParameters*/,
4335 Extended /*EncodeClassNames*/);
4336}
4337
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004338/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004339/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004340bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004341 std::string& S,
4342 bool Extended) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004343 // FIXME: This is not very efficient.
Bob Wilsondc8dab62011-11-30 01:57:58 +00004344 // Encode return type.
4345 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4346 Decl->getResultType(), S, Extended);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004347 // Compute size of all parameters.
4348 // Start with computing size of a pointer in number of bytes.
4349 // FIXME: There might(should) be a better way of doing this computation!
4350 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004351 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004352 // The first two arguments (self and _cmd) are pointers; account for
4353 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004354 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004355 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004356 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004357 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004358 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004359 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004360 continue;
4361
Ken Dyck199c3d62010-01-11 17:06:35 +00004362 assert (sz.isPositive() &&
4363 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004364 ParmOffset += sz;
4365 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004366 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004367 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004368 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004369
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004370 // Argument types.
4371 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004372 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004373 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004374 const ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004375 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004376 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004377 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4378 // Use array's original type only if it has known number of
4379 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004380 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004381 PType = PVDecl->getType();
4382 } else if (PType->isFunctionType())
4383 PType = PVDecl->getType();
Bob Wilsondc8dab62011-11-30 01:57:58 +00004384 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4385 PType, S, Extended);
Ken Dyck199c3d62010-01-11 17:06:35 +00004386 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004387 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004388 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004389
4390 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004391}
4392
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004393/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004394/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004395/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4396/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004397/// Property attributes are stored as a comma-delimited C string. The simple
4398/// attributes readonly and bycopy are encoded as single characters. The
4399/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4400/// encoded as single characters, followed by an identifier. Property types
4401/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004402/// these attributes are defined by the following enumeration:
4403/// @code
4404/// enum PropertyAttributes {
4405/// kPropertyReadOnly = 'R', // property is read-only.
4406/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4407/// kPropertyByref = '&', // property is a reference to the value last assigned
4408/// kPropertyDynamic = 'D', // property is dynamic
4409/// kPropertyGetter = 'G', // followed by getter selector name
4410/// kPropertySetter = 'S', // followed by setter selector name
4411/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson0d4cb852012-03-22 17:48:02 +00004412/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004413/// kPropertyWeak = 'W' // 'weak' property
4414/// kPropertyStrong = 'P' // property GC'able
4415/// kPropertyNonAtomic = 'N' // property non-atomic
4416/// };
4417/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004418void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004419 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004420 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004421 // Collect information from the property implementation decl(s).
4422 bool Dynamic = false;
4423 ObjCPropertyImplDecl *SynthesizePID = 0;
4424
4425 // FIXME: Duplicated code due to poor abstraction.
4426 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004427 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004428 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4429 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004430 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004431 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004432 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-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 }
4440 }
4441 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004442 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004443 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004444 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004445 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004446 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004447 if (PID->getPropertyDecl() == PD) {
4448 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4449 Dynamic = true;
4450 } else {
4451 SynthesizePID = PID;
4452 }
4453 }
Mike Stump1eb44332009-09-09 15:08:12 +00004454 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004455 }
4456 }
4457
4458 // FIXME: This is not very efficient.
4459 S = "T";
4460
4461 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004462 // GCC has some special rules regarding encoding of properties which
4463 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004464 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004465 true /* outermost type */,
4466 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004467
4468 if (PD->isReadOnly()) {
4469 S += ",R";
4470 } else {
4471 switch (PD->getSetterKind()) {
4472 case ObjCPropertyDecl::Assign: break;
4473 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004474 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00004475 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004476 }
4477 }
4478
4479 // It really isn't clear at all what this means, since properties
4480 // are "dynamic by default".
4481 if (Dynamic)
4482 S += ",D";
4483
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004484 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4485 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004486
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004487 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4488 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004489 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004490 }
4491
4492 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4493 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004494 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004495 }
4496
4497 if (SynthesizePID) {
4498 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4499 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004500 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004501 }
4502
4503 // FIXME: OBJCGC: weak & strong
4504}
4505
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004506/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00004507/// Another legacy compatibility encoding: 32-bit longs are encoded as
4508/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004509/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4510///
4511void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00004512 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00004513 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00004514 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004515 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004516 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004517 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004518 PointeeTy = IntTy;
4519 }
4520 }
4521}
4522
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004523void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00004524 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004525 // We follow the behavior of gcc, expanding structures which are
4526 // directly pointed to, and expanding embedded structures. Note that
4527 // these rules are sufficient to prevent recursive encoding of the
4528 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00004529 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00004530 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004531}
4532
David Chisnall64fd7e82010-06-04 01:10:52 +00004533static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4534 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004535 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnall64fd7e82010-06-04 01:10:52 +00004536 case BuiltinType::Void: return 'v';
4537 case BuiltinType::Bool: return 'B';
4538 case BuiltinType::Char_U:
4539 case BuiltinType::UChar: return 'C';
4540 case BuiltinType::UShort: return 'S';
4541 case BuiltinType::UInt: return 'I';
4542 case BuiltinType::ULong:
Jay Foad4ba2a172011-01-12 09:06:06 +00004543 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004544 case BuiltinType::UInt128: return 'T';
4545 case BuiltinType::ULongLong: return 'Q';
4546 case BuiltinType::Char_S:
4547 case BuiltinType::SChar: return 'c';
4548 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00004549 case BuiltinType::WChar_S:
4550 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00004551 case BuiltinType::Int: return 'i';
4552 case BuiltinType::Long:
Jay Foad4ba2a172011-01-12 09:06:06 +00004553 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004554 case BuiltinType::LongLong: return 'q';
4555 case BuiltinType::Int128: return 't';
4556 case BuiltinType::Float: return 'f';
4557 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00004558 case BuiltinType::LongDouble: return 'D';
David Chisnall64fd7e82010-06-04 01:10:52 +00004559 }
4560}
4561
Douglas Gregor5471bc82011-09-08 17:18:35 +00004562static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4563 EnumDecl *Enum = ET->getDecl();
4564
4565 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4566 if (!Enum->isFixed())
4567 return 'i';
4568
4569 // The encoding of a fixed enum type matches its fixed underlying type.
4570 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4571}
4572
Jay Foad4ba2a172011-01-12 09:06:06 +00004573static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00004574 QualType T, const FieldDecl *FD) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004575 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004576 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00004577 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4578 // The GNU runtime requires more information; bitfields are encoded as b,
4579 // then the offset (in bits) of the first element, then the type of the
4580 // bitfield, then the size in bits. For example, in this structure:
4581 //
4582 // struct
4583 // {
4584 // int integer;
4585 // int flags:2;
4586 // };
4587 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4588 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4589 // information is not especially sensible, but we're stuck with it for
4590 // compatibility with GCC, although providing it breaks anything that
4591 // actually uses runtime introspection and wants to work on both runtimes...
John McCall260611a2012-06-20 06:18:46 +00004592 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnall64fd7e82010-06-04 01:10:52 +00004593 const RecordDecl *RD = FD->getParent();
4594 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00004595 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor5471bc82011-09-08 17:18:35 +00004596 if (const EnumType *ET = T->getAs<EnumType>())
4597 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnallc7ff82c2010-12-26 20:12:30 +00004598 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004599 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnall64fd7e82010-06-04 01:10:52 +00004600 }
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004601 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004602}
4603
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00004604// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004605void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4606 bool ExpandPointedToStructures,
4607 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00004608 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004609 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004610 bool EncodingProperty,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004611 bool StructField,
4612 bool EncodeBlockParameters,
4613 bool EncodeClassNames) const {
David Chisnall64fd7e82010-06-04 01:10:52 +00004614 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004615 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004616 return EncodeBitField(this, S, T, FD);
4617 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004618 return;
4619 }
Mike Stump1eb44332009-09-09 15:08:12 +00004620
John McCall183700f2009-09-21 23:43:11 +00004621 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004622 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00004623 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004624 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004625 return;
4626 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00004627
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004628 // encoding for pointer or r3eference types.
4629 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004630 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00004631 if (PT->isObjCSelType()) {
4632 S += ':';
4633 return;
4634 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004635 PointeeTy = PT->getPointeeType();
4636 }
4637 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4638 PointeeTy = RT->getPointeeType();
4639 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004640 bool isReadOnly = false;
4641 // For historical/compatibility reasons, the read-only qualifier of the
4642 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4643 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00004644 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00004645 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004646 if (OutermostType && T.isConstQualified()) {
4647 isReadOnly = true;
4648 S += 'r';
4649 }
Mike Stump9fdbab32009-07-31 02:02:20 +00004650 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004651 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004652 while (P->getAs<PointerType>())
4653 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004654 if (P.isConstQualified()) {
4655 isReadOnly = true;
4656 S += 'r';
4657 }
4658 }
4659 if (isReadOnly) {
4660 // Another legacy compatibility encoding. Some ObjC qualifier and type
4661 // combinations need to be rearranged.
4662 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00004663 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00004664 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004665 }
Mike Stump1eb44332009-09-09 15:08:12 +00004666
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004667 if (PointeeTy->isCharType()) {
4668 // char pointer types should be encoded as '*' unless it is a
4669 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00004670 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004671 S += '*';
4672 return;
4673 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004674 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00004675 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4676 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4677 S += '#';
4678 return;
4679 }
4680 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4681 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4682 S += '@';
4683 return;
4684 }
4685 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004686 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004687 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004688 getLegacyIntegralTypeEncoding(PointeeTy);
4689
Mike Stump1eb44332009-09-09 15:08:12 +00004690 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004691 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004692 return;
4693 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004694
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004695 if (const ArrayType *AT =
4696 // Ignore type qualifiers etc.
4697 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004698 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00004699 // Incomplete arrays are encoded as a pointer to the array element.
4700 S += '^';
4701
Mike Stump1eb44332009-09-09 15:08:12 +00004702 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004703 false, ExpandStructures, FD);
4704 } else {
4705 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00004706
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004707 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4708 if (getTypeSize(CAT->getElementType()) == 0)
4709 S += '0';
4710 else
4711 S += llvm::utostr(CAT->getSize().getZExtValue());
4712 } else {
Anders Carlsson559a8332009-02-22 01:38:57 +00004713 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004714 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4715 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00004716 S += '0';
4717 }
Mike Stump1eb44332009-09-09 15:08:12 +00004718
4719 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004720 false, ExpandStructures, FD);
4721 S += ']';
4722 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004723 return;
4724 }
Mike Stump1eb44332009-09-09 15:08:12 +00004725
John McCall183700f2009-09-21 23:43:11 +00004726 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00004727 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004728 return;
4729 }
Mike Stump1eb44332009-09-09 15:08:12 +00004730
Ted Kremenek6217b802009-07-29 21:53:49 +00004731 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004732 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004733 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004734 // Anonymous structures print as '?'
4735 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4736 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004737 if (ClassTemplateSpecializationDecl *Spec
4738 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4739 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4740 std::string TemplateArgsStr
4741 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00004742 TemplateArgs.data(),
4743 TemplateArgs.size(),
Douglas Gregor30c42402011-09-27 22:38:19 +00004744 (*this).getPrintingPolicy());
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004745
4746 S += TemplateArgsStr;
4747 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004748 } else {
4749 S += '?';
4750 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004751 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004752 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004753 if (!RDecl->isUnion()) {
4754 getObjCEncodingForStructureImpl(RDecl, S, FD);
4755 } else {
4756 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4757 FieldEnd = RDecl->field_end();
4758 Field != FieldEnd; ++Field) {
4759 if (FD) {
4760 S += '"';
4761 S += Field->getNameAsString();
4762 S += '"';
4763 }
Mike Stump1eb44332009-09-09 15:08:12 +00004764
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004765 // Special case bit-fields.
4766 if (Field->isBitField()) {
4767 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie581deb32012-06-06 20:45:41 +00004768 *Field);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004769 } else {
4770 QualType qt = Field->getType();
4771 getLegacyIntegralTypeEncoding(qt);
4772 getObjCEncodingForTypeImpl(qt, S, false, true,
4773 FD, /*OutermostType*/false,
4774 /*EncodingProperty*/false,
4775 /*StructField*/true);
4776 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004777 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004778 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00004779 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004780 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004781 return;
4782 }
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004783
Douglas Gregor5471bc82011-09-08 17:18:35 +00004784 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004785 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004786 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004787 else
Douglas Gregor5471bc82011-09-08 17:18:35 +00004788 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004789 return;
4790 }
Mike Stump1eb44332009-09-09 15:08:12 +00004791
Bob Wilsondc8dab62011-11-30 01:57:58 +00004792 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00004793 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilsondc8dab62011-11-30 01:57:58 +00004794 if (EncodeBlockParameters) {
4795 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4796
4797 S += '<';
4798 // Block return type
4799 getObjCEncodingForTypeImpl(FT->getResultType(), S,
4800 ExpandPointedToStructures, ExpandStructures,
4801 FD,
4802 false /* OutermostType */,
4803 EncodingProperty,
4804 false /* StructField */,
4805 EncodeBlockParameters,
4806 EncodeClassNames);
4807 // Block self
4808 S += "@?";
4809 // Block parameters
4810 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4811 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4812 E = FPT->arg_type_end(); I && (I != E); ++I) {
4813 getObjCEncodingForTypeImpl(*I, S,
4814 ExpandPointedToStructures,
4815 ExpandStructures,
4816 FD,
4817 false /* OutermostType */,
4818 EncodingProperty,
4819 false /* StructField */,
4820 EncodeBlockParameters,
4821 EncodeClassNames);
4822 }
4823 }
4824 S += '>';
4825 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004826 return;
4827 }
Mike Stump1eb44332009-09-09 15:08:12 +00004828
John McCallc12c5bb2010-05-15 11:32:37 +00004829 // Ignore protocol qualifiers when mangling at this level.
4830 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4831 T = OT->getBaseType();
4832
John McCall0953e762009-09-24 19:53:00 +00004833 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004834 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00004835 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004836 S += '{';
4837 const IdentifierInfo *II = OI->getIdentifier();
4838 S += II->getName();
4839 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00004840 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004841 DeepCollectObjCIvars(OI, true, Ivars);
4842 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00004843 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004844 if (Field->isBitField())
4845 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004846 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004847 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004848 }
4849 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004850 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004851 }
Mike Stump1eb44332009-09-09 15:08:12 +00004852
John McCall183700f2009-09-21 23:43:11 +00004853 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004854 if (OPT->isObjCIdType()) {
4855 S += '@';
4856 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004857 }
Mike Stump1eb44332009-09-09 15:08:12 +00004858
Steve Naroff27d20a22009-10-28 22:03:49 +00004859 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4860 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4861 // Since this is a binary compatibility issue, need to consult with runtime
4862 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00004863 S += '#';
4864 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004865 }
Mike Stump1eb44332009-09-09 15:08:12 +00004866
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004867 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004868 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00004869 ExpandPointedToStructures,
4870 ExpandStructures, FD);
Bob Wilsondc8dab62011-11-30 01:57:58 +00004871 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff14108da2009-07-10 23:34:53 +00004872 // Note that we do extended encoding of protocol qualifer list
4873 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00004874 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004875 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4876 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00004877 S += '<';
4878 S += (*I)->getNameAsString();
4879 S += '>';
4880 }
4881 S += '"';
4882 }
4883 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004884 }
Mike Stump1eb44332009-09-09 15:08:12 +00004885
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004886 QualType PointeeTy = OPT->getPointeeType();
4887 if (!EncodingProperty &&
4888 isa<TypedefType>(PointeeTy.getTypePtr())) {
4889 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00004890 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004891 // {...};
4892 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00004893 getObjCEncodingForTypeImpl(PointeeTy, S,
4894 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004895 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00004896 return;
4897 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004898
4899 S += '@';
Bob Wilsondc8dab62011-11-30 01:57:58 +00004900 if (OPT->getInterfaceDecl() &&
4901 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004902 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00004903 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004904 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4905 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004906 S += '<';
4907 S += (*I)->getNameAsString();
4908 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00004909 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004910 S += '"';
4911 }
4912 return;
4913 }
Mike Stump1eb44332009-09-09 15:08:12 +00004914
John McCall532ec7b2010-05-17 23:56:34 +00004915 // gcc just blithely ignores member pointers.
4916 // TODO: maybe there should be a mangling for these
4917 if (T->getAs<MemberPointerType>())
4918 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004919
4920 if (T->isVectorType()) {
4921 // This matches gcc's encoding, even though technically it is
4922 // insufficient.
4923 // FIXME. We should do a better job than gcc.
4924 return;
4925 }
4926
David Blaikieb219cfc2011-09-23 05:06:16 +00004927 llvm_unreachable("@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004928}
4929
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004930void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4931 std::string &S,
4932 const FieldDecl *FD,
4933 bool includeVBases) const {
4934 assert(RDecl && "Expected non-null RecordDecl");
4935 assert(!RDecl->isUnion() && "Should not be called for unions");
4936 if (!RDecl->getDefinition())
4937 return;
4938
4939 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4940 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4941 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4942
4943 if (CXXRec) {
4944 for (CXXRecordDecl::base_class_iterator
4945 BI = CXXRec->bases_begin(),
4946 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4947 if (!BI->isVirtual()) {
4948 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004949 if (base->isEmpty())
4950 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00004951 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004952 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4953 std::make_pair(offs, base));
4954 }
4955 }
4956 }
4957
4958 unsigned i = 0;
4959 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4960 FieldEnd = RDecl->field_end();
4961 Field != FieldEnd; ++Field, ++i) {
4962 uint64_t offs = layout.getFieldOffset(i);
4963 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie581deb32012-06-06 20:45:41 +00004964 std::make_pair(offs, *Field));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004965 }
4966
4967 if (CXXRec && includeVBases) {
4968 for (CXXRecordDecl::base_class_iterator
4969 BI = CXXRec->vbases_begin(),
4970 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4971 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004972 if (base->isEmpty())
4973 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00004974 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis19aa8602011-09-26 18:14:24 +00004975 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4976 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4977 std::make_pair(offs, base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004978 }
4979 }
4980
4981 CharUnits size;
4982 if (CXXRec) {
4983 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4984 } else {
4985 size = layout.getSize();
4986 }
4987
4988 uint64_t CurOffs = 0;
4989 std::multimap<uint64_t, NamedDecl *>::iterator
4990 CurLayObj = FieldOrBaseOffsets.begin();
4991
Douglas Gregor58db7a52012-04-27 22:30:01 +00004992 if (CXXRec && CXXRec->isDynamicClass() &&
4993 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004994 if (FD) {
4995 S += "\"_vptr$";
4996 std::string recname = CXXRec->getNameAsString();
4997 if (recname.empty()) recname = "?";
4998 S += recname;
4999 S += '"';
5000 }
5001 S += "^^?";
5002 CurOffs += getTypeSize(VoidPtrTy);
5003 }
5004
5005 if (!RDecl->hasFlexibleArrayMember()) {
5006 // Mark the end of the structure.
5007 uint64_t offs = toBits(size);
5008 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5009 std::make_pair(offs, (NamedDecl*)0));
5010 }
5011
5012 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5013 assert(CurOffs <= CurLayObj->first);
5014
5015 if (CurOffs < CurLayObj->first) {
5016 uint64_t padding = CurLayObj->first - CurOffs;
5017 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5018 // packing/alignment of members is different that normal, in which case
5019 // the encoding will be out-of-sync with the real layout.
5020 // If the runtime switches to just consider the size of types without
5021 // taking into account alignment, we could make padding explicit in the
5022 // encoding (e.g. using arrays of chars). The encoding strings would be
5023 // longer then though.
5024 CurOffs += padding;
5025 }
5026
5027 NamedDecl *dcl = CurLayObj->second;
5028 if (dcl == 0)
5029 break; // reached end of structure.
5030
5031 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5032 // We expand the bases without their virtual bases since those are going
5033 // in the initial structure. Note that this differs from gcc which
5034 // expands virtual bases each time one is encountered in the hierarchy,
5035 // making the encoding type bigger than it really is.
5036 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005037 assert(!base->isEmpty());
5038 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005039 } else {
5040 FieldDecl *field = cast<FieldDecl>(dcl);
5041 if (FD) {
5042 S += '"';
5043 S += field->getNameAsString();
5044 S += '"';
5045 }
5046
5047 if (field->isBitField()) {
5048 EncodeBitField(this, S, field->getType(), field);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005049 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005050 } else {
5051 QualType qt = field->getType();
5052 getLegacyIntegralTypeEncoding(qt);
5053 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5054 /*OutermostType*/false,
5055 /*EncodingProperty*/false,
5056 /*StructField*/true);
5057 CurOffs += getTypeSize(field->getType());
5058 }
5059 }
5060 }
5061}
5062
Mike Stump1eb44332009-09-09 15:08:12 +00005063void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00005064 std::string& S) const {
5065 if (QT & Decl::OBJC_TQ_In)
5066 S += 'n';
5067 if (QT & Decl::OBJC_TQ_Inout)
5068 S += 'N';
5069 if (QT & Decl::OBJC_TQ_Out)
5070 S += 'o';
5071 if (QT & Decl::OBJC_TQ_Bycopy)
5072 S += 'O';
5073 if (QT & Decl::OBJC_TQ_Byref)
5074 S += 'R';
5075 if (QT & Decl::OBJC_TQ_Oneway)
5076 S += 'V';
5077}
5078
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00005079TypedefDecl *ASTContext::getObjCIdDecl() const {
5080 if (!ObjCIdDecl) {
5081 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5082 T = getObjCObjectPointerType(T);
5083 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5084 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5085 getTranslationUnitDecl(),
5086 SourceLocation(), SourceLocation(),
5087 &Idents.get("id"), IdInfo);
5088 }
5089
5090 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00005091}
5092
Douglas Gregor7a27ea52011-08-12 06:17:30 +00005093TypedefDecl *ASTContext::getObjCSelDecl() const {
5094 if (!ObjCSelDecl) {
5095 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5096 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5097 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5098 getTranslationUnitDecl(),
5099 SourceLocation(), SourceLocation(),
5100 &Idents.get("SEL"), SelInfo);
5101 }
5102 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00005103}
5104
Douglas Gregor79d67262011-08-12 05:59:41 +00005105TypedefDecl *ASTContext::getObjCClassDecl() const {
5106 if (!ObjCClassDecl) {
5107 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5108 T = getObjCObjectPointerType(T);
5109 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5110 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5111 getTranslationUnitDecl(),
5112 SourceLocation(), SourceLocation(),
5113 &Idents.get("Class"), ClassInfo);
5114 }
5115
5116 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00005117}
5118
Douglas Gregora6ea10e2012-01-17 18:09:05 +00005119ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5120 if (!ObjCProtocolClassDecl) {
5121 ObjCProtocolClassDecl
5122 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5123 SourceLocation(),
5124 &Idents.get("Protocol"),
5125 /*PrevDecl=*/0,
5126 SourceLocation(), true);
5127 }
5128
5129 return ObjCProtocolClassDecl;
5130}
5131
Meador Ingec5613b22012-06-16 03:34:49 +00005132//===----------------------------------------------------------------------===//
5133// __builtin_va_list Construction Functions
5134//===----------------------------------------------------------------------===//
5135
5136static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5137 // typedef char* __builtin_va_list;
5138 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5139 TypeSourceInfo *TInfo
5140 = Context->getTrivialTypeSourceInfo(CharPtrType);
5141
5142 TypedefDecl *VaListTypeDecl
5143 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5144 Context->getTranslationUnitDecl(),
5145 SourceLocation(), SourceLocation(),
5146 &Context->Idents.get("__builtin_va_list"),
5147 TInfo);
5148 return VaListTypeDecl;
5149}
5150
5151static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5152 // typedef void* __builtin_va_list;
5153 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5154 TypeSourceInfo *TInfo
5155 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5156
5157 TypedefDecl *VaListTypeDecl
5158 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5159 Context->getTranslationUnitDecl(),
5160 SourceLocation(), SourceLocation(),
5161 &Context->Idents.get("__builtin_va_list"),
5162 TInfo);
5163 return VaListTypeDecl;
5164}
5165
5166static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5167 // typedef struct __va_list_tag {
5168 RecordDecl *VaListTagDecl;
5169
5170 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5171 Context->getTranslationUnitDecl(),
5172 &Context->Idents.get("__va_list_tag"));
5173 VaListTagDecl->startDefinition();
5174
5175 const size_t NumFields = 5;
5176 QualType FieldTypes[NumFields];
5177 const char *FieldNames[NumFields];
5178
5179 // unsigned char gpr;
5180 FieldTypes[0] = Context->UnsignedCharTy;
5181 FieldNames[0] = "gpr";
5182
5183 // unsigned char fpr;
5184 FieldTypes[1] = Context->UnsignedCharTy;
5185 FieldNames[1] = "fpr";
5186
5187 // unsigned short reserved;
5188 FieldTypes[2] = Context->UnsignedShortTy;
5189 FieldNames[2] = "reserved";
5190
5191 // void* overflow_arg_area;
5192 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5193 FieldNames[3] = "overflow_arg_area";
5194
5195 // void* reg_save_area;
5196 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5197 FieldNames[4] = "reg_save_area";
5198
5199 // Create fields
5200 for (unsigned i = 0; i < NumFields; ++i) {
5201 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5202 SourceLocation(),
5203 SourceLocation(),
5204 &Context->Idents.get(FieldNames[i]),
5205 FieldTypes[i], /*TInfo=*/0,
5206 /*BitWidth=*/0,
5207 /*Mutable=*/false,
5208 ICIS_NoInit);
5209 Field->setAccess(AS_public);
5210 VaListTagDecl->addDecl(Field);
5211 }
5212 VaListTagDecl->completeDefinition();
5213 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005214 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005215
5216 // } __va_list_tag;
5217 TypedefDecl *VaListTagTypedefDecl
5218 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5219 Context->getTranslationUnitDecl(),
5220 SourceLocation(), SourceLocation(),
5221 &Context->Idents.get("__va_list_tag"),
5222 Context->getTrivialTypeSourceInfo(VaListTagType));
5223 QualType VaListTagTypedefType =
5224 Context->getTypedefType(VaListTagTypedefDecl);
5225
5226 // typedef __va_list_tag __builtin_va_list[1];
5227 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5228 QualType VaListTagArrayType
5229 = Context->getConstantArrayType(VaListTagTypedefType,
5230 Size, ArrayType::Normal, 0);
5231 TypeSourceInfo *TInfo
5232 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5233 TypedefDecl *VaListTypedefDecl
5234 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5235 Context->getTranslationUnitDecl(),
5236 SourceLocation(), SourceLocation(),
5237 &Context->Idents.get("__builtin_va_list"),
5238 TInfo);
5239
5240 return VaListTypedefDecl;
5241}
5242
5243static TypedefDecl *
5244CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5245 // typedef struct __va_list_tag {
5246 RecordDecl *VaListTagDecl;
5247 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5248 Context->getTranslationUnitDecl(),
5249 &Context->Idents.get("__va_list_tag"));
5250 VaListTagDecl->startDefinition();
5251
5252 const size_t NumFields = 4;
5253 QualType FieldTypes[NumFields];
5254 const char *FieldNames[NumFields];
5255
5256 // unsigned gp_offset;
5257 FieldTypes[0] = Context->UnsignedIntTy;
5258 FieldNames[0] = "gp_offset";
5259
5260 // unsigned fp_offset;
5261 FieldTypes[1] = Context->UnsignedIntTy;
5262 FieldNames[1] = "fp_offset";
5263
5264 // void* overflow_arg_area;
5265 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5266 FieldNames[2] = "overflow_arg_area";
5267
5268 // void* reg_save_area;
5269 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5270 FieldNames[3] = "reg_save_area";
5271
5272 // Create fields
5273 for (unsigned i = 0; i < NumFields; ++i) {
5274 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5275 VaListTagDecl,
5276 SourceLocation(),
5277 SourceLocation(),
5278 &Context->Idents.get(FieldNames[i]),
5279 FieldTypes[i], /*TInfo=*/0,
5280 /*BitWidth=*/0,
5281 /*Mutable=*/false,
5282 ICIS_NoInit);
5283 Field->setAccess(AS_public);
5284 VaListTagDecl->addDecl(Field);
5285 }
5286 VaListTagDecl->completeDefinition();
5287 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005288 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005289
5290 // } __va_list_tag;
5291 TypedefDecl *VaListTagTypedefDecl
5292 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5293 Context->getTranslationUnitDecl(),
5294 SourceLocation(), SourceLocation(),
5295 &Context->Idents.get("__va_list_tag"),
5296 Context->getTrivialTypeSourceInfo(VaListTagType));
5297 QualType VaListTagTypedefType =
5298 Context->getTypedefType(VaListTagTypedefDecl);
5299
5300 // typedef __va_list_tag __builtin_va_list[1];
5301 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5302 QualType VaListTagArrayType
5303 = Context->getConstantArrayType(VaListTagTypedefType,
5304 Size, ArrayType::Normal,0);
5305 TypeSourceInfo *TInfo
5306 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5307 TypedefDecl *VaListTypedefDecl
5308 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5309 Context->getTranslationUnitDecl(),
5310 SourceLocation(), SourceLocation(),
5311 &Context->Idents.get("__builtin_va_list"),
5312 TInfo);
5313
5314 return VaListTypedefDecl;
5315}
5316
5317static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5318 // typedef int __builtin_va_list[4];
5319 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5320 QualType IntArrayType
5321 = Context->getConstantArrayType(Context->IntTy,
5322 Size, ArrayType::Normal, 0);
5323 TypedefDecl *VaListTypedefDecl
5324 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5325 Context->getTranslationUnitDecl(),
5326 SourceLocation(), SourceLocation(),
5327 &Context->Idents.get("__builtin_va_list"),
5328 Context->getTrivialTypeSourceInfo(IntArrayType));
5329
5330 return VaListTypedefDecl;
5331}
5332
5333static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5334 TargetInfo::BuiltinVaListKind Kind) {
5335 switch (Kind) {
5336 case TargetInfo::CharPtrBuiltinVaList:
5337 return CreateCharPtrBuiltinVaListDecl(Context);
5338 case TargetInfo::VoidPtrBuiltinVaList:
5339 return CreateVoidPtrBuiltinVaListDecl(Context);
5340 case TargetInfo::PowerABIBuiltinVaList:
5341 return CreatePowerABIBuiltinVaListDecl(Context);
5342 case TargetInfo::X86_64ABIBuiltinVaList:
5343 return CreateX86_64ABIBuiltinVaListDecl(Context);
5344 case TargetInfo::PNaClABIBuiltinVaList:
5345 return CreatePNaClABIBuiltinVaListDecl(Context);
5346 }
5347
5348 llvm_unreachable("Unhandled __builtin_va_list type kind");
5349}
5350
5351TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5352 if (!BuiltinVaListDecl)
5353 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5354
5355 return BuiltinVaListDecl;
5356}
5357
Meador Ingefb40e3f2012-07-01 15:57:25 +00005358QualType ASTContext::getVaListTagType() const {
5359 // Force the creation of VaListTagTy by building the __builtin_va_list
5360 // declaration.
5361 if (VaListTagTy.isNull())
5362 (void) getBuiltinVaListDecl();
5363
5364 return VaListTagTy;
5365}
5366
Ted Kremeneka526c5c2008-01-07 19:49:32 +00005367void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00005368 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00005369 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00005370
Ted Kremeneka526c5c2008-01-07 19:49:32 +00005371 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00005372}
5373
John McCall0bd6feb2009-12-02 08:04:21 +00005374/// \brief Retrieve the template name that corresponds to a non-empty
5375/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00005376TemplateName
5377ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5378 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00005379 unsigned size = End - Begin;
5380 assert(size > 1 && "set is not overloaded!");
5381
5382 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5383 size * sizeof(FunctionTemplateDecl*));
5384 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5385
5386 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00005387 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00005388 NamedDecl *D = *I;
5389 assert(isa<FunctionTemplateDecl>(D) ||
5390 (isa<UsingShadowDecl>(D) &&
5391 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5392 *Storage++ = D;
5393 }
5394
5395 return TemplateName(OT);
5396}
5397
Douglas Gregor7532dc62009-03-30 22:58:21 +00005398/// \brief Retrieve the template name that represents a qualified
5399/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00005400TemplateName
5401ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5402 bool TemplateKeyword,
5403 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00005404 assert(NNS && "Missing nested-name-specifier in qualified template name");
5405
Douglas Gregor789b1f62010-02-04 18:10:26 +00005406 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00005407 llvm::FoldingSetNodeID ID;
5408 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5409
5410 void *InsertPos = 0;
5411 QualifiedTemplateName *QTN =
5412 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5413 if (!QTN) {
5414 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
5415 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5416 }
5417
5418 return TemplateName(QTN);
5419}
5420
5421/// \brief Retrieve the template name that represents a dependent
5422/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00005423TemplateName
5424ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5425 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00005426 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00005427 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00005428
5429 llvm::FoldingSetNodeID ID;
5430 DependentTemplateName::Profile(ID, NNS, Name);
5431
5432 void *InsertPos = 0;
5433 DependentTemplateName *QTN =
5434 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5435
5436 if (QTN)
5437 return TemplateName(QTN);
5438
5439 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5440 if (CanonNNS == NNS) {
5441 QTN = new (*this,4) DependentTemplateName(NNS, Name);
5442 } else {
5443 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
5444 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00005445 DependentTemplateName *CheckQTN =
5446 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5447 assert(!CheckQTN && "Dependent type name canonicalization broken");
5448 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00005449 }
5450
5451 DependentTemplateNames.InsertNode(QTN, InsertPos);
5452 return TemplateName(QTN);
5453}
5454
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005455/// \brief Retrieve the template name that represents a dependent
5456/// template name such as \c MetaFun::template operator+.
5457TemplateName
5458ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00005459 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005460 assert((!NNS || NNS->isDependent()) &&
5461 "Nested name specifier must be dependent");
5462
5463 llvm::FoldingSetNodeID ID;
5464 DependentTemplateName::Profile(ID, NNS, Operator);
5465
5466 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00005467 DependentTemplateName *QTN
5468 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005469
5470 if (QTN)
5471 return TemplateName(QTN);
5472
5473 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5474 if (CanonNNS == NNS) {
5475 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
5476 } else {
5477 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
5478 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00005479
5480 DependentTemplateName *CheckQTN
5481 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5482 assert(!CheckQTN && "Dependent template name canonicalization broken");
5483 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005484 }
5485
5486 DependentTemplateNames.InsertNode(QTN, InsertPos);
5487 return TemplateName(QTN);
5488}
5489
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005490TemplateName
John McCall14606042011-06-30 08:33:18 +00005491ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5492 TemplateName replacement) const {
5493 llvm::FoldingSetNodeID ID;
5494 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5495
5496 void *insertPos = 0;
5497 SubstTemplateTemplateParmStorage *subst
5498 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5499
5500 if (!subst) {
5501 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5502 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5503 }
5504
5505 return TemplateName(subst);
5506}
5507
5508TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005509ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5510 const TemplateArgument &ArgPack) const {
5511 ASTContext &Self = const_cast<ASTContext &>(*this);
5512 llvm::FoldingSetNodeID ID;
5513 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5514
5515 void *InsertPos = 0;
5516 SubstTemplateTemplateParmPackStorage *Subst
5517 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5518
5519 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00005520 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005521 ArgPack.pack_size(),
5522 ArgPack.pack_begin());
5523 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5524 }
5525
5526 return TemplateName(Subst);
5527}
5528
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005529/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00005530/// TargetInfo, produce the corresponding type. The unsigned @p Type
5531/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00005532CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005533 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00005534 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005535 case TargetInfo::SignedShort: return ShortTy;
5536 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5537 case TargetInfo::SignedInt: return IntTy;
5538 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5539 case TargetInfo::SignedLong: return LongTy;
5540 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5541 case TargetInfo::SignedLongLong: return LongLongTy;
5542 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5543 }
5544
David Blaikieb219cfc2011-09-23 05:06:16 +00005545 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005546}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00005547
5548//===----------------------------------------------------------------------===//
5549// Type Predicates.
5550//===----------------------------------------------------------------------===//
5551
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005552/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5553/// garbage collection attribute.
5554///
John McCallae278a32011-01-12 00:34:59 +00005555Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00005556 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCallae278a32011-01-12 00:34:59 +00005557 return Qualifiers::GCNone;
5558
David Blaikie4e4d0842012-03-11 07:00:24 +00005559 assert(getLangOpts().ObjC1);
John McCallae278a32011-01-12 00:34:59 +00005560 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5561
5562 // Default behaviour under objective-C's gc is for ObjC pointers
5563 // (or pointers to them) be treated as though they were declared
5564 // as __strong.
5565 if (GCAttrs == Qualifiers::GCNone) {
5566 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5567 return Qualifiers::Strong;
5568 else if (Ty->isPointerType())
5569 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5570 } else {
5571 // It's not valid to set GC attributes on anything that isn't a
5572 // pointer.
5573#ifndef NDEBUG
5574 QualType CT = Ty->getCanonicalTypeInternal();
5575 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5576 CT = AT->getElementType();
5577 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5578#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005579 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00005580 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005581}
5582
Chris Lattner6ac46a42008-04-07 06:51:04 +00005583//===----------------------------------------------------------------------===//
5584// Type Compatibility Testing
5585//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00005586
Mike Stump1eb44332009-09-09 15:08:12 +00005587/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005588/// compatible.
5589static bool areCompatVectorTypes(const VectorType *LHS,
5590 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00005591 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00005592 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00005593 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00005594}
5595
Douglas Gregor255210e2010-08-06 10:14:59 +00005596bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5597 QualType SecondVec) {
5598 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5599 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5600
5601 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5602 return true;
5603
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005604 // Treat Neon vector types and most AltiVec vector types as if they are the
5605 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00005606 const VectorType *First = FirstVec->getAs<VectorType>();
5607 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005608 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00005609 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005610 First->getVectorKind() != VectorType::AltiVecPixel &&
5611 First->getVectorKind() != VectorType::AltiVecBool &&
5612 Second->getVectorKind() != VectorType::AltiVecPixel &&
5613 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00005614 return true;
5615
5616 return false;
5617}
5618
Steve Naroff4084c302009-07-23 01:01:38 +00005619//===----------------------------------------------------------------------===//
5620// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5621//===----------------------------------------------------------------------===//
5622
5623/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5624/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00005625bool
5626ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5627 ObjCProtocolDecl *rProto) const {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00005628 if (declaresSameEntity(lProto, rProto))
Steve Naroff4084c302009-07-23 01:01:38 +00005629 return true;
5630 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5631 E = rProto->protocol_end(); PI != E; ++PI)
5632 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5633 return true;
5634 return false;
5635}
5636
Steve Naroff4084c302009-07-23 01:01:38 +00005637/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5638/// return true if lhs's protocols conform to rhs's protocol; false
5639/// otherwise.
5640bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5641 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5642 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5643 return false;
5644}
5645
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005646/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5647/// Class<p1, ...>.
5648bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5649 QualType rhs) {
5650 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5651 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5652 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5653
5654 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5655 E = lhsQID->qual_end(); I != E; ++I) {
5656 bool match = false;
5657 ObjCProtocolDecl *lhsProto = *I;
5658 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5659 E = rhsOPT->qual_end(); J != E; ++J) {
5660 ObjCProtocolDecl *rhsProto = *J;
5661 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5662 match = true;
5663 break;
5664 }
5665 }
5666 if (!match)
5667 return false;
5668 }
5669 return true;
5670}
5671
Steve Naroff4084c302009-07-23 01:01:38 +00005672/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5673/// ObjCQualifiedIDType.
5674bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5675 bool compare) {
5676 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00005677 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005678 lhs->isObjCIdType() || lhs->isObjCClassType())
5679 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005680 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005681 rhs->isObjCIdType() || rhs->isObjCClassType())
5682 return true;
5683
5684 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00005685 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005686
Steve Naroff4084c302009-07-23 01:01:38 +00005687 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005688
Steve Naroff4084c302009-07-23 01:01:38 +00005689 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005690 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00005691 // make sure we check the class hierarchy.
5692 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5693 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5694 E = lhsQID->qual_end(); I != E; ++I) {
5695 // when comparing an id<P> on lhs with a static type on rhs,
5696 // see if static class implements all of id's protocols, directly or
5697 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005698 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00005699 return false;
5700 }
5701 }
5702 // If there are no qualifiers and no interface, we have an 'id'.
5703 return true;
5704 }
Mike Stump1eb44332009-09-09 15:08:12 +00005705 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005706 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5707 E = lhsQID->qual_end(); I != E; ++I) {
5708 ObjCProtocolDecl *lhsProto = *I;
5709 bool match = false;
5710
5711 // when comparing an id<P> on lhs with a static type on rhs,
5712 // see if static class implements all of id's protocols, directly or
5713 // through its super class and categories.
5714 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5715 E = rhsOPT->qual_end(); J != E; ++J) {
5716 ObjCProtocolDecl *rhsProto = *J;
5717 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5718 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5719 match = true;
5720 break;
5721 }
5722 }
Mike Stump1eb44332009-09-09 15:08:12 +00005723 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00005724 // make sure we check the class hierarchy.
5725 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5726 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5727 E = lhsQID->qual_end(); I != E; ++I) {
5728 // when comparing an id<P> on lhs with a static type on rhs,
5729 // see if static class implements all of id's protocols, directly or
5730 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005731 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00005732 match = true;
5733 break;
5734 }
5735 }
5736 }
5737 if (!match)
5738 return false;
5739 }
Mike Stump1eb44332009-09-09 15:08:12 +00005740
Steve Naroff4084c302009-07-23 01:01:38 +00005741 return true;
5742 }
Mike Stump1eb44332009-09-09 15:08:12 +00005743
Steve Naroff4084c302009-07-23 01:01:38 +00005744 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5745 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5746
Mike Stump1eb44332009-09-09 15:08:12 +00005747 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00005748 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005749 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005750 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5751 E = lhsOPT->qual_end(); I != E; ++I) {
5752 ObjCProtocolDecl *lhsProto = *I;
5753 bool match = false;
5754
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005755 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00005756 // see if static class implements all of id's protocols, directly or
5757 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005758 // First, lhs protocols in the qualifier list must be found, direct
5759 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00005760 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5761 E = rhsQID->qual_end(); J != E; ++J) {
5762 ObjCProtocolDecl *rhsProto = *J;
5763 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5764 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5765 match = true;
5766 break;
5767 }
5768 }
5769 if (!match)
5770 return false;
5771 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005772
5773 // Static class's protocols, or its super class or category protocols
5774 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5775 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5776 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5777 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5778 // This is rather dubious but matches gcc's behavior. If lhs has
5779 // no type qualifier and its class has no static protocol(s)
5780 // assume that it is mismatch.
5781 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5782 return false;
5783 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5784 LHSInheritedProtocols.begin(),
5785 E = LHSInheritedProtocols.end(); I != E; ++I) {
5786 bool match = false;
5787 ObjCProtocolDecl *lhsProto = (*I);
5788 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5789 E = rhsQID->qual_end(); J != E; ++J) {
5790 ObjCProtocolDecl *rhsProto = *J;
5791 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5792 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5793 match = true;
5794 break;
5795 }
5796 }
5797 if (!match)
5798 return false;
5799 }
5800 }
Steve Naroff4084c302009-07-23 01:01:38 +00005801 return true;
5802 }
5803 return false;
5804}
5805
Eli Friedman3d815e72008-08-22 00:56:42 +00005806/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005807/// compatible for assignment from RHS to LHS. This handles validation of any
5808/// protocol qualifiers on the LHS or RHS.
5809///
Steve Naroff14108da2009-07-10 23:34:53 +00005810bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5811 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00005812 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5813 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5814
Steve Naroffde2e22d2009-07-15 18:40:39 +00005815 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00005816 if (LHS->isObjCUnqualifiedIdOrClass() ||
5817 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00005818 return true;
5819
John McCallc12c5bb2010-05-15 11:32:37 +00005820 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00005821 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5822 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00005823 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005824
5825 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5826 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5827 QualType(RHSOPT,0));
5828
John McCallc12c5bb2010-05-15 11:32:37 +00005829 // If we have 2 user-defined types, fall into that path.
5830 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00005831 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00005832
Steve Naroff4084c302009-07-23 01:01:38 +00005833 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005834}
5835
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005836/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00005837/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005838/// arguments in block literals. When passed as arguments, passing 'A*' where
5839/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5840/// not OK. For the return type, the opposite is not OK.
5841bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5842 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005843 const ObjCObjectPointerType *RHSOPT,
5844 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005845 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005846 return true;
5847
5848 if (LHSOPT->isObjCBuiltinType()) {
5849 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5850 }
5851
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005852 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005853 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5854 QualType(RHSOPT,0),
5855 false);
5856
5857 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5858 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5859 if (LHS && RHS) { // We have 2 user-defined types.
5860 if (LHS != RHS) {
5861 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005862 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005863 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005864 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005865 }
5866 else
5867 return true;
5868 }
5869 return false;
5870}
5871
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005872/// getIntersectionOfProtocols - This routine finds the intersection of set
5873/// of protocols inherited from two distinct objective-c pointer objects.
5874/// It is used to build composite qualifier list of the composite type of
5875/// the conditional expression involving two objective-c pointer objects.
5876static
5877void getIntersectionOfProtocols(ASTContext &Context,
5878 const ObjCObjectPointerType *LHSOPT,
5879 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005880 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005881
John McCallc12c5bb2010-05-15 11:32:37 +00005882 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5883 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5884 assert(LHS->getInterface() && "LHS must have an interface base");
5885 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005886
5887 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5888 unsigned LHSNumProtocols = LHS->getNumProtocols();
5889 if (LHSNumProtocols > 0)
5890 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5891 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005892 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005893 Context.CollectInheritedProtocols(LHS->getInterface(),
5894 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005895 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5896 LHSInheritedProtocols.end());
5897 }
5898
5899 unsigned RHSNumProtocols = RHS->getNumProtocols();
5900 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00005901 ObjCProtocolDecl **RHSProtocols =
5902 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005903 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5904 if (InheritedProtocolSet.count(RHSProtocols[i]))
5905 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier30601782011-08-17 23:08:45 +00005906 } else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005907 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005908 Context.CollectInheritedProtocols(RHS->getInterface(),
5909 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005910 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5911 RHSInheritedProtocols.begin(),
5912 E = RHSInheritedProtocols.end(); I != E; ++I)
5913 if (InheritedProtocolSet.count((*I)))
5914 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005915 }
5916}
5917
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005918/// areCommonBaseCompatible - Returns common base class of the two classes if
5919/// one found. Note that this is O'2 algorithm. But it will be called as the
5920/// last type comparison in a ?-exp of ObjC pointer types before a
5921/// warning is issued. So, its invokation is extremely rare.
5922QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00005923 const ObjCObjectPointerType *Lptr,
5924 const ObjCObjectPointerType *Rptr) {
5925 const ObjCObjectType *LHS = Lptr->getObjectType();
5926 const ObjCObjectType *RHS = Rptr->getObjectType();
5927 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5928 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor60ef3082011-12-15 00:29:59 +00005929 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005930 return QualType();
5931
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005932 do {
John McCallc12c5bb2010-05-15 11:32:37 +00005933 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005934 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005935 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005936 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5937
5938 QualType Result = QualType(LHS, 0);
5939 if (!Protocols.empty())
5940 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5941 Result = getObjCObjectPointerType(Result);
5942 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005943 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005944 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005945
5946 return QualType();
5947}
5948
John McCallc12c5bb2010-05-15 11:32:37 +00005949bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5950 const ObjCObjectType *RHS) {
5951 assert(LHS->getInterface() && "LHS is not an interface type");
5952 assert(RHS->getInterface() && "RHS is not an interface type");
5953
Chris Lattner6ac46a42008-04-07 06:51:04 +00005954 // Verify that the base decls are compatible: the RHS must be a subclass of
5955 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00005956 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00005957 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005958
Chris Lattner6ac46a42008-04-07 06:51:04 +00005959 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5960 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00005961 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00005962 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005963
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005964 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5965 // more detailed analysis is required.
5966 if (RHS->getNumProtocols() == 0) {
5967 // OK, if LHS is a superclass of RHS *and*
5968 // this superclass is assignment compatible with LHS.
5969 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005970 bool IsSuperClass =
5971 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5972 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005973 // OK if conversion of LHS to SuperClass results in narrowing of types
5974 // ; i.e., SuperClass may implement at least one of the protocols
5975 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5976 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5977 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005978 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005979 // If super class has no protocols, it is not a match.
5980 if (SuperClassInheritedProtocols.empty())
5981 return false;
5982
5983 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5984 LHSPE = LHS->qual_end();
5985 LHSPI != LHSPE; LHSPI++) {
5986 bool SuperImplementsProtocol = false;
5987 ObjCProtocolDecl *LHSProto = (*LHSPI);
5988
5989 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5990 SuperClassInheritedProtocols.begin(),
5991 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5992 ObjCProtocolDecl *SuperClassProto = (*I);
5993 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5994 SuperImplementsProtocol = true;
5995 break;
5996 }
5997 }
5998 if (!SuperImplementsProtocol)
5999 return false;
6000 }
6001 return true;
6002 }
6003 return false;
6004 }
Mike Stump1eb44332009-09-09 15:08:12 +00006005
John McCallc12c5bb2010-05-15 11:32:37 +00006006 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6007 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006008 LHSPI != LHSPE; LHSPI++) {
6009 bool RHSImplementsProtocol = false;
6010
6011 // If the RHS doesn't implement the protocol on the left, the types
6012 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00006013 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6014 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00006015 RHSPI != RHSPE; RHSPI++) {
6016 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006017 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00006018 break;
6019 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006020 }
6021 // FIXME: For better diagnostics, consider passing back the protocol name.
6022 if (!RHSImplementsProtocol)
6023 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006024 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006025 // The RHS implements all protocols listed on the LHS.
6026 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006027}
6028
Steve Naroff389bf462009-02-12 17:52:19 +00006029bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6030 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00006031 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6032 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006033
Steve Naroff14108da2009-07-10 23:34:53 +00006034 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00006035 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006036
6037 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6038 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00006039}
6040
Douglas Gregor569c3162010-08-07 11:51:51 +00006041bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6042 return canAssignObjCInterfaces(
6043 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6044 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6045}
6046
Mike Stump1eb44332009-09-09 15:08:12 +00006047/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00006048/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00006049/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00006050/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00006051bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6052 bool CompareUnqualified) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006053 if (getLangOpts().CPlusPlus)
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006054 return hasSameType(LHS, RHS);
6055
Douglas Gregor447234d2010-07-29 15:18:02 +00006056 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00006057}
6058
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006059bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00006060 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006061}
6062
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006063bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6064 return !mergeTypes(LHS, RHS, true).isNull();
6065}
6066
Peter Collingbourne48466752010-10-24 18:30:18 +00006067/// mergeTransparentUnionType - if T is a transparent union type and a member
6068/// of T is compatible with SubType, return the merged type, else return
6069/// QualType()
6070QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6071 bool OfBlockPointer,
6072 bool Unqualified) {
6073 if (const RecordType *UT = T->getAsUnionType()) {
6074 RecordDecl *UD = UT->getDecl();
6075 if (UD->hasAttr<TransparentUnionAttr>()) {
6076 for (RecordDecl::field_iterator it = UD->field_begin(),
6077 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00006078 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006079 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6080 if (!MT.isNull())
6081 return MT;
6082 }
6083 }
6084 }
6085
6086 return QualType();
6087}
6088
6089/// mergeFunctionArgumentTypes - merge two types which appear as function
6090/// argument types
6091QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6092 bool OfBlockPointer,
6093 bool Unqualified) {
6094 // GNU extension: two types are compatible if they appear as a function
6095 // argument, one of the types is a transparent union type and the other
6096 // type is compatible with a union member
6097 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6098 Unqualified);
6099 if (!lmerge.isNull())
6100 return lmerge;
6101
6102 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6103 Unqualified);
6104 if (!rmerge.isNull())
6105 return rmerge;
6106
6107 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6108}
6109
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006110QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00006111 bool OfBlockPointer,
6112 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00006113 const FunctionType *lbase = lhs->getAs<FunctionType>();
6114 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00006115 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6116 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00006117 bool allLTypes = true;
6118 bool allRTypes = true;
6119
6120 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006121 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006122 if (OfBlockPointer) {
6123 QualType RHS = rbase->getResultType();
6124 QualType LHS = lbase->getResultType();
6125 bool UnqualifiedResult = Unqualified;
6126 if (!UnqualifiedResult)
6127 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006128 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006129 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006130 else
John McCall8cc246c2010-12-15 01:06:38 +00006131 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6132 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006133 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006134
6135 if (Unqualified)
6136 retType = retType.getUnqualifiedType();
6137
6138 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6139 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6140 if (Unqualified) {
6141 LRetType = LRetType.getUnqualifiedType();
6142 RRetType = RRetType.getUnqualifiedType();
6143 }
6144
6145 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006146 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00006147 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006148 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00006149
Daniel Dunbar6a15c852010-04-28 16:20:58 +00006150 // FIXME: double check this
6151 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6152 // rbase->getRegParmAttr() != 0 &&
6153 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00006154 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6155 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00006156
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006157 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00006158 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006159 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006160
John McCall8cc246c2010-12-15 01:06:38 +00006161 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00006162 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6163 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00006164 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6165 return QualType();
6166
John McCallf85e1932011-06-15 23:02:42 +00006167 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6168 return QualType();
6169
Fariborz Jahanian53c81672011-10-05 00:05:34 +00006170 // functypes which return are preferred over those that do not.
6171 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
6172 allLTypes = false;
6173 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
6174 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00006175 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6176 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8cc246c2010-12-15 01:06:38 +00006177
John McCallf85e1932011-06-15 23:02:42 +00006178 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00006179
Eli Friedman3d815e72008-08-22 00:56:42 +00006180 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00006181 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6182 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00006183 unsigned lproto_nargs = lproto->getNumArgs();
6184 unsigned rproto_nargs = rproto->getNumArgs();
6185
6186 // Compatible functions must have the same number of arguments
6187 if (lproto_nargs != rproto_nargs)
6188 return QualType();
6189
6190 // Variadic and non-variadic functions aren't compatible
6191 if (lproto->isVariadic() != rproto->isVariadic())
6192 return QualType();
6193
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00006194 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6195 return QualType();
6196
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006197 if (LangOpts.ObjCAutoRefCount &&
6198 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6199 return QualType();
6200
Eli Friedman3d815e72008-08-22 00:56:42 +00006201 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00006202 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00006203 for (unsigned i = 0; i < lproto_nargs; i++) {
6204 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6205 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006206 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6207 OfBlockPointer,
6208 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006209 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006210
6211 if (Unqualified)
6212 argtype = argtype.getUnqualifiedType();
6213
Eli Friedman3d815e72008-08-22 00:56:42 +00006214 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00006215 if (Unqualified) {
6216 largtype = largtype.getUnqualifiedType();
6217 rargtype = rargtype.getUnqualifiedType();
6218 }
6219
Chris Lattner61710852008-10-05 17:34:18 +00006220 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6221 allLTypes = false;
6222 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6223 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00006224 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006225
Eli Friedman3d815e72008-08-22 00:56:42 +00006226 if (allLTypes) return lhs;
6227 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00006228
6229 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6230 EPI.ExtInfo = einfo;
6231 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00006232 }
6233
6234 if (lproto) allRTypes = false;
6235 if (rproto) allLTypes = false;
6236
Douglas Gregor72564e72009-02-26 23:50:07 +00006237 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00006238 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00006239 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00006240 if (proto->isVariadic()) return QualType();
6241 // Check that the types are compatible with the types that
6242 // would result from default argument promotions (C99 6.7.5.3p15).
6243 // The only types actually affected are promotable integer
6244 // types and floats, which would be passed as a different
6245 // type depending on whether the prototype is visible.
6246 unsigned proto_nargs = proto->getNumArgs();
6247 for (unsigned i = 0; i < proto_nargs; ++i) {
6248 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00006249
6250 // Look at the promotion type of enum types, since that is the type used
6251 // to pass enum values.
6252 if (const EnumType *Enum = argTy->getAs<EnumType>())
6253 argTy = Enum->getDecl()->getPromotionType();
6254
Eli Friedman3d815e72008-08-22 00:56:42 +00006255 if (argTy->isPromotableIntegerType() ||
6256 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6257 return QualType();
6258 }
6259
6260 if (allLTypes) return lhs;
6261 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00006262
6263 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6264 EPI.ExtInfo = einfo;
Eli Friedman3d815e72008-08-22 00:56:42 +00006265 return getFunctionType(retType, proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00006266 proto->getNumArgs(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00006267 }
6268
6269 if (allLTypes) return lhs;
6270 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00006271 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00006272}
6273
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006274QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00006275 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006276 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00006277 // C++ [expr]: If an expression initially has the type "reference to T", the
6278 // type is adjusted to "T" prior to any further analysis, the expression
6279 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00006280 // expression is an lvalue unless the reference is an rvalue reference and
6281 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006282 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6283 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00006284
6285 if (Unqualified) {
6286 LHS = LHS.getUnqualifiedType();
6287 RHS = RHS.getUnqualifiedType();
6288 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006289
Eli Friedman3d815e72008-08-22 00:56:42 +00006290 QualType LHSCan = getCanonicalType(LHS),
6291 RHSCan = getCanonicalType(RHS);
6292
6293 // If two types are identical, they are compatible.
6294 if (LHSCan == RHSCan)
6295 return LHS;
6296
John McCall0953e762009-09-24 19:53:00 +00006297 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006298 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6299 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00006300 if (LQuals != RQuals) {
6301 // If any of these qualifiers are different, we have a type
6302 // mismatch.
6303 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00006304 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6305 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00006306 return QualType();
6307
6308 // Exactly one GC qualifier difference is allowed: __strong is
6309 // okay if the other type has no GC qualifier but is an Objective
6310 // C object pointer (i.e. implicitly strong by default). We fix
6311 // this by pretending that the unqualified type was actually
6312 // qualified __strong.
6313 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6314 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6315 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6316
6317 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6318 return QualType();
6319
6320 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6321 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6322 }
6323 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6324 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6325 }
Eli Friedman3d815e72008-08-22 00:56:42 +00006326 return QualType();
John McCall0953e762009-09-24 19:53:00 +00006327 }
6328
6329 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00006330
Eli Friedman852d63b2009-06-01 01:22:52 +00006331 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6332 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00006333
Chris Lattner1adb8832008-01-14 05:45:46 +00006334 // We want to consider the two function types to be the same for these
6335 // comparisons, just force one to the other.
6336 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6337 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00006338
6339 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00006340 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6341 LHSClass = Type::ConstantArray;
6342 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6343 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00006344
John McCallc12c5bb2010-05-15 11:32:37 +00006345 // ObjCInterfaces are just specialized ObjCObjects.
6346 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6347 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6348
Nate Begeman213541a2008-04-18 23:10:10 +00006349 // Canonicalize ExtVector -> Vector.
6350 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6351 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00006352
Chris Lattnera36a61f2008-04-07 05:43:21 +00006353 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00006354 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00006355 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00006356 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00006357 // Compatibility is based on the underlying type, not the promotion
6358 // type.
John McCall183700f2009-09-21 23:43:11 +00006359 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianb918d6b2012-02-06 19:06:20 +00006360 QualType TINT = ETy->getDecl()->getIntegerType();
6361 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006362 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00006363 }
John McCall183700f2009-09-21 23:43:11 +00006364 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianb918d6b2012-02-06 19:06:20 +00006365 QualType TINT = ETy->getDecl()->getIntegerType();
6366 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006367 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00006368 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00006369 // allow block pointer type to match an 'id' type.
Fariborz Jahanian41963632012-01-26 17:08:50 +00006370 if (OfBlockPointer && !BlockReturnType) {
6371 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6372 return LHS;
6373 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6374 return RHS;
6375 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00006376
Eli Friedman3d815e72008-08-22 00:56:42 +00006377 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00006378 }
Eli Friedman3d815e72008-08-22 00:56:42 +00006379
Steve Naroff4a746782008-01-09 22:43:08 +00006380 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00006381 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00006382#define TYPE(Class, Base)
6383#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00006384#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00006385#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6386#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6387#include "clang/AST/TypeNodes.def"
David Blaikieb219cfc2011-09-23 05:06:16 +00006388 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregor72564e72009-02-26 23:50:07 +00006389
Sebastian Redl7c80bd62009-03-16 23:22:08 +00006390 case Type::LValueReference:
6391 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00006392 case Type::MemberPointer:
David Blaikieb219cfc2011-09-23 05:06:16 +00006393 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregor72564e72009-02-26 23:50:07 +00006394
John McCallc12c5bb2010-05-15 11:32:37 +00006395 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00006396 case Type::IncompleteArray:
6397 case Type::VariableArray:
6398 case Type::FunctionProto:
6399 case Type::ExtVector:
David Blaikieb219cfc2011-09-23 05:06:16 +00006400 llvm_unreachable("Types are eliminated above");
Douglas Gregor72564e72009-02-26 23:50:07 +00006401
Chris Lattner1adb8832008-01-14 05:45:46 +00006402 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00006403 {
6404 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00006405 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6406 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006407 if (Unqualified) {
6408 LHSPointee = LHSPointee.getUnqualifiedType();
6409 RHSPointee = RHSPointee.getUnqualifiedType();
6410 }
6411 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6412 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006413 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00006414 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00006415 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00006416 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00006417 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00006418 return getPointerType(ResultType);
6419 }
Steve Naroffc0febd52008-12-10 17:49:55 +00006420 case Type::BlockPointer:
6421 {
6422 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00006423 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6424 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006425 if (Unqualified) {
6426 LHSPointee = LHSPointee.getUnqualifiedType();
6427 RHSPointee = RHSPointee.getUnqualifiedType();
6428 }
6429 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6430 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00006431 if (ResultType.isNull()) return QualType();
6432 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6433 return LHS;
6434 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6435 return RHS;
6436 return getBlockPointerType(ResultType);
6437 }
Eli Friedmanb001de72011-10-06 23:00:33 +00006438 case Type::Atomic:
6439 {
6440 // Merge two pointer types, while trying to preserve typedef info
6441 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6442 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6443 if (Unqualified) {
6444 LHSValue = LHSValue.getUnqualifiedType();
6445 RHSValue = RHSValue.getUnqualifiedType();
6446 }
6447 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6448 Unqualified);
6449 if (ResultType.isNull()) return QualType();
6450 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6451 return LHS;
6452 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6453 return RHS;
6454 return getAtomicType(ResultType);
6455 }
Chris Lattner1adb8832008-01-14 05:45:46 +00006456 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00006457 {
6458 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6459 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6460 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6461 return QualType();
6462
6463 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6464 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006465 if (Unqualified) {
6466 LHSElem = LHSElem.getUnqualifiedType();
6467 RHSElem = RHSElem.getUnqualifiedType();
6468 }
6469
6470 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006471 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00006472 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6473 return LHS;
6474 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6475 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00006476 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6477 ArrayType::ArraySizeModifier(), 0);
6478 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6479 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00006480 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6481 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00006482 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6483 return LHS;
6484 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6485 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00006486 if (LVAT) {
6487 // FIXME: This isn't correct! But tricky to implement because
6488 // the array's size has to be the size of LHS, but the type
6489 // has to be different.
6490 return LHS;
6491 }
6492 if (RVAT) {
6493 // FIXME: This isn't correct! But tricky to implement because
6494 // the array's size has to be the size of RHS, but the type
6495 // has to be different.
6496 return RHS;
6497 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00006498 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6499 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00006500 return getIncompleteArrayType(ResultType,
6501 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00006502 }
Chris Lattner1adb8832008-01-14 05:45:46 +00006503 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00006504 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00006505 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00006506 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00006507 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00006508 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00006509 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00006510 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00006511 case Type::Complex:
6512 // Distinct complex types are incompatible.
6513 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00006514 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00006515 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00006516 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6517 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006518 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00006519 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00006520 case Type::ObjCObject: {
6521 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00006522 // FIXME: This should be type compatibility, e.g. whether
6523 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00006524 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6525 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6526 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00006527 return LHS;
6528
Eli Friedman3d815e72008-08-22 00:56:42 +00006529 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00006530 }
Steve Naroff14108da2009-07-10 23:34:53 +00006531 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006532 if (OfBlockPointer) {
6533 if (canAssignObjCInterfacesInBlockPointer(
6534 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006535 RHS->getAs<ObjCObjectPointerType>(),
6536 BlockReturnType))
David Blaikie7530c032012-01-17 06:56:22 +00006537 return LHS;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006538 return QualType();
6539 }
John McCall183700f2009-09-21 23:43:11 +00006540 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6541 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00006542 return LHS;
6543
Steve Naroffbc76dd02008-12-10 22:14:21 +00006544 return QualType();
David Blaikie7530c032012-01-17 06:56:22 +00006545 }
Steve Naroffec0550f2007-10-15 20:41:53 +00006546 }
Douglas Gregor72564e72009-02-26 23:50:07 +00006547
David Blaikie7530c032012-01-17 06:56:22 +00006548 llvm_unreachable("Invalid Type::Class!");
Steve Naroffec0550f2007-10-15 20:41:53 +00006549}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00006550
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006551bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6552 const FunctionProtoType *FromFunctionType,
6553 const FunctionProtoType *ToFunctionType) {
6554 if (FromFunctionType->hasAnyConsumedArgs() !=
6555 ToFunctionType->hasAnyConsumedArgs())
6556 return false;
6557 FunctionProtoType::ExtProtoInfo FromEPI =
6558 FromFunctionType->getExtProtoInfo();
6559 FunctionProtoType::ExtProtoInfo ToEPI =
6560 ToFunctionType->getExtProtoInfo();
6561 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6562 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6563 ArgIdx != NumArgs; ++ArgIdx) {
6564 if (FromEPI.ConsumedArguments[ArgIdx] !=
6565 ToEPI.ConsumedArguments[ArgIdx])
6566 return false;
6567 }
6568 return true;
6569}
6570
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006571/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6572/// 'RHS' attributes and returns the merged version; including for function
6573/// return types.
6574QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6575 QualType LHSCan = getCanonicalType(LHS),
6576 RHSCan = getCanonicalType(RHS);
6577 // If two types are identical, they are compatible.
6578 if (LHSCan == RHSCan)
6579 return LHS;
6580 if (RHSCan->isFunctionType()) {
6581 if (!LHSCan->isFunctionType())
6582 return QualType();
6583 QualType OldReturnType =
6584 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6585 QualType NewReturnType =
6586 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6587 QualType ResReturnType =
6588 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6589 if (ResReturnType.isNull())
6590 return QualType();
6591 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6592 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6593 // In either case, use OldReturnType to build the new function type.
6594 const FunctionType *F = LHS->getAs<FunctionType>();
6595 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00006596 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6597 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006598 QualType ResultType
6599 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00006600 FPT->getNumArgs(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006601 return ResultType;
6602 }
6603 }
6604 return QualType();
6605 }
6606
6607 // If the qualifiers are different, the types can still be merged.
6608 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6609 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6610 if (LQuals != RQuals) {
6611 // If any of these qualifiers are different, we have a type mismatch.
6612 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6613 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6614 return QualType();
6615
6616 // Exactly one GC qualifier difference is allowed: __strong is
6617 // okay if the other type has no GC qualifier but is an Objective
6618 // C object pointer (i.e. implicitly strong by default). We fix
6619 // this by pretending that the unqualified type was actually
6620 // qualified __strong.
6621 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6622 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6623 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6624
6625 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6626 return QualType();
6627
6628 if (GC_L == Qualifiers::Strong)
6629 return LHS;
6630 if (GC_R == Qualifiers::Strong)
6631 return RHS;
6632 return QualType();
6633 }
6634
6635 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6636 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6637 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6638 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6639 if (ResQT == LHSBaseQT)
6640 return LHS;
6641 if (ResQT == RHSBaseQT)
6642 return RHS;
6643 }
6644 return QualType();
6645}
6646
Chris Lattner5426bf62008-04-07 07:01:58 +00006647//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00006648// Integer Predicates
6649//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00006650
Jay Foad4ba2a172011-01-12 09:06:06 +00006651unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00006652 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00006653 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006654 if (T->isBooleanType())
6655 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00006656 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00006657 return (unsigned)getTypeSize(T);
6658}
6659
6660QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregorf6094622010-07-23 15:58:24 +00006661 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00006662
6663 // Turn <4 x signed int> -> <4 x unsigned int>
6664 if (const VectorType *VTy = T->getAs<VectorType>())
6665 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00006666 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00006667
6668 // For enums, we return the unsigned version of the base type.
6669 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00006670 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00006671
6672 const BuiltinType *BTy = T->getAs<BuiltinType>();
6673 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00006674 switch (BTy->getKind()) {
6675 case BuiltinType::Char_S:
6676 case BuiltinType::SChar:
6677 return UnsignedCharTy;
6678 case BuiltinType::Short:
6679 return UnsignedShortTy;
6680 case BuiltinType::Int:
6681 return UnsignedIntTy;
6682 case BuiltinType::Long:
6683 return UnsignedLongTy;
6684 case BuiltinType::LongLong:
6685 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00006686 case BuiltinType::Int128:
6687 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00006688 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00006689 llvm_unreachable("Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00006690 }
6691}
6692
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00006693ASTMutationListener::~ASTMutationListener() { }
6694
Chris Lattner86df27b2009-06-14 00:45:47 +00006695
6696//===----------------------------------------------------------------------===//
6697// Builtin Type Computation
6698//===----------------------------------------------------------------------===//
6699
6700/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00006701/// pointer over the consumed characters. This returns the resultant type. If
6702/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6703/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6704/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00006705///
6706/// RequiresICE is filled in on return to indicate whether the value is required
6707/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00006708static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00006709 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00006710 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00006711 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00006712 // Modifiers.
6713 int HowLong = 0;
6714 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00006715 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006716
Chris Lattner33daae62010-10-01 22:42:38 +00006717 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00006718 bool Done = false;
6719 while (!Done) {
6720 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00006721 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006722 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00006723 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006724 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006725 case 'S':
6726 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6727 assert(!Signed && "Can't use 'S' modifier multiple times!");
6728 Signed = true;
6729 break;
6730 case 'U':
6731 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6732 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6733 Unsigned = true;
6734 break;
6735 case 'L':
6736 assert(HowLong <= 2 && "Can't have LLLL modifier");
6737 ++HowLong;
6738 break;
6739 }
6740 }
6741
6742 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00006743
Chris Lattner86df27b2009-06-14 00:45:47 +00006744 // Read the base type.
6745 switch (*Str++) {
David Blaikieb219cfc2011-09-23 05:06:16 +00006746 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattner86df27b2009-06-14 00:45:47 +00006747 case 'v':
6748 assert(HowLong == 0 && !Signed && !Unsigned &&
6749 "Bad modifiers used with 'v'!");
6750 Type = Context.VoidTy;
6751 break;
6752 case 'f':
6753 assert(HowLong == 0 && !Signed && !Unsigned &&
6754 "Bad modifiers used with 'f'!");
6755 Type = Context.FloatTy;
6756 break;
6757 case 'd':
6758 assert(HowLong < 2 && !Signed && !Unsigned &&
6759 "Bad modifiers used with 'd'!");
6760 if (HowLong)
6761 Type = Context.LongDoubleTy;
6762 else
6763 Type = Context.DoubleTy;
6764 break;
6765 case 's':
6766 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6767 if (Unsigned)
6768 Type = Context.UnsignedShortTy;
6769 else
6770 Type = Context.ShortTy;
6771 break;
6772 case 'i':
6773 if (HowLong == 3)
6774 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6775 else if (HowLong == 2)
6776 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6777 else if (HowLong == 1)
6778 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6779 else
6780 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6781 break;
6782 case 'c':
6783 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6784 if (Signed)
6785 Type = Context.SignedCharTy;
6786 else if (Unsigned)
6787 Type = Context.UnsignedCharTy;
6788 else
6789 Type = Context.CharTy;
6790 break;
6791 case 'b': // boolean
6792 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6793 Type = Context.BoolTy;
6794 break;
6795 case 'z': // size_t.
6796 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6797 Type = Context.getSizeType();
6798 break;
6799 case 'F':
6800 Type = Context.getCFConstantStringType();
6801 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00006802 case 'G':
6803 Type = Context.getObjCIdType();
6804 break;
6805 case 'H':
6806 Type = Context.getObjCSelType();
6807 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006808 case 'a':
6809 Type = Context.getBuiltinVaListType();
6810 assert(!Type.isNull() && "builtin va list type not initialized!");
6811 break;
6812 case 'A':
6813 // This is a "reference" to a va_list; however, what exactly
6814 // this means depends on how va_list is defined. There are two
6815 // different kinds of va_list: ones passed by value, and ones
6816 // passed by reference. An example of a by-value va_list is
6817 // x86, where va_list is a char*. An example of by-ref va_list
6818 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6819 // we want this argument to be a char*&; for x86-64, we want
6820 // it to be a __va_list_tag*.
6821 Type = Context.getBuiltinVaListType();
6822 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00006823 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00006824 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00006825 else
Chris Lattner86df27b2009-06-14 00:45:47 +00006826 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00006827 break;
6828 case 'V': {
6829 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00006830 unsigned NumElements = strtoul(Str, &End, 10);
6831 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00006832 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00006833
Chris Lattner14e0e742010-10-01 22:53:11 +00006834 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6835 RequiresICE, false);
6836 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00006837
6838 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00006839 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00006840 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00006841 break;
6842 }
Douglas Gregorb4bc99b2012-06-07 18:08:25 +00006843 case 'E': {
6844 char *End;
6845
6846 unsigned NumElements = strtoul(Str, &End, 10);
6847 assert(End != Str && "Missing vector size");
6848
6849 Str = End;
6850
6851 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6852 false);
6853 Type = Context.getExtVectorType(ElementType, NumElements);
6854 break;
6855 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00006856 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00006857 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6858 false);
6859 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00006860 Type = Context.getComplexType(ElementType);
6861 break;
Fariborz Jahaniancc075e42011-08-23 23:33:09 +00006862 }
6863 case 'Y' : {
6864 Type = Context.getPointerDiffType();
6865 break;
6866 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006867 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00006868 Type = Context.getFILEType();
6869 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006870 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00006871 return QualType();
6872 }
Mike Stumpfd612db2009-07-28 23:47:15 +00006873 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006874 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00006875 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00006876 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00006877 else
6878 Type = Context.getjmp_bufType();
6879
Mike Stumpfd612db2009-07-28 23:47:15 +00006880 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006881 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00006882 return QualType();
6883 }
6884 break;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00006885 case 'K':
6886 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
6887 Type = Context.getucontext_tType();
6888
6889 if (Type.isNull()) {
6890 Error = ASTContext::GE_Missing_ucontext;
6891 return QualType();
6892 }
6893 break;
Mike Stump782fa302009-07-28 02:25:19 +00006894 }
Mike Stump1eb44332009-09-09 15:08:12 +00006895
Chris Lattner33daae62010-10-01 22:42:38 +00006896 // If there are modifiers and if we're allowed to parse them, go for it.
6897 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00006898 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00006899 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00006900 default: Done = true; --Str; break;
6901 case '*':
6902 case '&': {
6903 // Both pointers and references can have their pointee types
6904 // qualified with an address space.
6905 char *End;
6906 unsigned AddrSpace = strtoul(Str, &End, 10);
6907 if (End != Str && AddrSpace != 0) {
6908 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6909 Str = End;
6910 }
6911 if (c == '*')
6912 Type = Context.getPointerType(Type);
6913 else
6914 Type = Context.getLValueReferenceType(Type);
6915 break;
6916 }
6917 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6918 case 'C':
6919 Type = Type.withConst();
6920 break;
6921 case 'D':
6922 Type = Context.getVolatileType(Type);
6923 break;
Ted Kremenek18932a02012-01-20 21:40:12 +00006924 case 'R':
6925 Type = Type.withRestrict();
6926 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006927 }
6928 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00006929
Chris Lattner14e0e742010-10-01 22:53:11 +00006930 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00006931 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00006932
Chris Lattner86df27b2009-06-14 00:45:47 +00006933 return Type;
6934}
6935
6936/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00006937QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00006938 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00006939 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00006940 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00006941
Chris Lattner5f9e2722011-07-23 10:55:15 +00006942 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00006943
Chris Lattner14e0e742010-10-01 22:53:11 +00006944 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00006945 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00006946 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6947 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006948 if (Error != GE_None)
6949 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00006950
6951 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6952
Chris Lattner86df27b2009-06-14 00:45:47 +00006953 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00006954 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006955 if (Error != GE_None)
6956 return QualType();
6957
Chris Lattner14e0e742010-10-01 22:53:11 +00006958 // If this argument is required to be an IntegerConstantExpression and the
6959 // caller cares, fill in the bitmask we return.
6960 if (RequiresICE && IntegerConstantArgs)
6961 *IntegerConstantArgs |= 1 << ArgTypes.size();
6962
Chris Lattner86df27b2009-06-14 00:45:47 +00006963 // Do array -> pointer decay. The builtin should use the decayed type.
6964 if (Ty->isArrayType())
6965 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00006966
Chris Lattner86df27b2009-06-14 00:45:47 +00006967 ArgTypes.push_back(Ty);
6968 }
6969
6970 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6971 "'.' should only occur at end of builtin type list!");
6972
John McCall00ccbef2010-12-21 00:44:39 +00006973 FunctionType::ExtInfo EI;
6974 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6975
6976 bool Variadic = (TypeStr[0] == '.');
6977
6978 // We really shouldn't be making a no-proto type here, especially in C++.
6979 if (ArgTypes.empty() && Variadic)
6980 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00006981
John McCalle23cf432010-12-14 08:05:40 +00006982 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00006983 EPI.ExtInfo = EI;
6984 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00006985
6986 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00006987}
Eli Friedmana95d7572009-08-19 07:44:53 +00006988
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006989GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6990 GVALinkage External = GVA_StrongExternal;
6991
6992 Linkage L = FD->getLinkage();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006993 switch (L) {
6994 case NoLinkage:
6995 case InternalLinkage:
6996 case UniqueExternalLinkage:
6997 return GVA_Internal;
6998
6999 case ExternalLinkage:
7000 switch (FD->getTemplateSpecializationKind()) {
7001 case TSK_Undeclared:
7002 case TSK_ExplicitSpecialization:
7003 External = GVA_StrongExternal;
7004 break;
7005
7006 case TSK_ExplicitInstantiationDefinition:
7007 return GVA_ExplicitTemplateInstantiation;
7008
7009 case TSK_ExplicitInstantiationDeclaration:
7010 case TSK_ImplicitInstantiation:
7011 External = GVA_TemplateInstantiation;
7012 break;
7013 }
7014 }
7015
7016 if (!FD->isInlined())
7017 return External;
7018
David Blaikie4e4d0842012-03-11 07:00:24 +00007019 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007020 // GNU or C99 inline semantics. Determine whether this symbol should be
7021 // externally visible.
7022 if (FD->isInlineDefinitionExternallyVisible())
7023 return External;
7024
7025 // C99 inline semantics, where the symbol is not externally visible.
7026 return GVA_C99Inline;
7027 }
7028
7029 // C++0x [temp.explicit]p9:
7030 // [ Note: The intent is that an inline function that is the subject of
7031 // an explicit instantiation declaration will still be implicitly
7032 // instantiated when used so that the body can be considered for
7033 // inlining, but that no out-of-line copy of the inline function would be
7034 // generated in the translation unit. -- end note ]
7035 if (FD->getTemplateSpecializationKind()
7036 == TSK_ExplicitInstantiationDeclaration)
7037 return GVA_C99Inline;
7038
7039 return GVA_CXXInline;
7040}
7041
7042GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7043 // If this is a static data member, compute the kind of template
7044 // specialization. Otherwise, this variable is not part of a
7045 // template.
7046 TemplateSpecializationKind TSK = TSK_Undeclared;
7047 if (VD->isStaticDataMember())
7048 TSK = VD->getTemplateSpecializationKind();
7049
7050 Linkage L = VD->getLinkage();
David Blaikie4e4d0842012-03-11 07:00:24 +00007051 if (L == ExternalLinkage && getLangOpts().CPlusPlus &&
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007052 VD->getType()->getLinkage() == UniqueExternalLinkage)
7053 L = UniqueExternalLinkage;
7054
7055 switch (L) {
7056 case NoLinkage:
7057 case InternalLinkage:
7058 case UniqueExternalLinkage:
7059 return GVA_Internal;
7060
7061 case ExternalLinkage:
7062 switch (TSK) {
7063 case TSK_Undeclared:
7064 case TSK_ExplicitSpecialization:
7065 return GVA_StrongExternal;
7066
7067 case TSK_ExplicitInstantiationDeclaration:
7068 llvm_unreachable("Variable should not be instantiated");
7069 // Fall through to treat this like any other instantiation.
7070
7071 case TSK_ExplicitInstantiationDefinition:
7072 return GVA_ExplicitTemplateInstantiation;
7073
7074 case TSK_ImplicitInstantiation:
7075 return GVA_TemplateInstantiation;
7076 }
7077 }
7078
David Blaikie7530c032012-01-17 06:56:22 +00007079 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007080}
7081
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00007082bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007083 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7084 if (!VD->isFileVarDecl())
7085 return false;
Argyrios Kyrtzidis144b38a2011-09-13 21:35:00 +00007086 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007087 return false;
7088
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007089 // Weak references don't produce any output by themselves.
7090 if (D->hasAttr<WeakRefAttr>())
7091 return false;
7092
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007093 // Aliases and used decls are required.
7094 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7095 return true;
7096
7097 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7098 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00007099 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00007100 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007101
7102 // Constructors and destructors are required.
7103 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7104 return true;
7105
7106 // The key function for a class is required.
7107 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7108 const CXXRecordDecl *RD = MD->getParent();
7109 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7110 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
7111 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7112 return true;
7113 }
7114 }
7115
7116 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7117
7118 // static, static inline, always_inline, and extern inline functions can
7119 // always be deferred. Normal inline functions can be deferred in C99/C++.
7120 // Implicit template instantiations can also be deferred in C++.
7121 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev3a5aca82012-02-02 06:06:34 +00007122 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007123 return false;
7124 return true;
7125 }
Douglas Gregor94da1582011-09-10 00:22:34 +00007126
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007127 const VarDecl *VD = cast<VarDecl>(D);
7128 assert(VD->isFileVarDecl() && "Expected file scoped var");
7129
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007130 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7131 return false;
7132
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007133 // Structs that have non-trivial constructors or destructors are required.
7134
7135 // FIXME: Handle references.
Sean Hunt023df372011-05-09 18:22:59 +00007136 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007137 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
7138 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Sean Hunt023df372011-05-09 18:22:59 +00007139 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
7140 RD->hasTrivialCopyConstructor() &&
7141 RD->hasTrivialMoveConstructor() &&
7142 RD->hasTrivialDestructor()))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007143 return true;
7144 }
7145 }
7146
7147 GVALinkage L = GetGVALinkageForVariable(VD);
7148 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
7149 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
7150 return false;
7151 }
7152
7153 return true;
7154}
Charles Davis071cc7d2010-08-16 03:33:14 +00007155
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007156CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davisee743f92010-11-09 18:04:24 +00007157 // Pass through to the C++ ABI object
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007158 return ABI->getDefaultMethodCallConv(isVariadic);
7159}
7160
7161CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
7162 if (CC == CC_C && !LangOpts.MRTD && getTargetInfo().getCXXABI() != CXXABI_Microsoft)
7163 return CC_Default;
7164 return CC;
Charles Davisee743f92010-11-09 18:04:24 +00007165}
7166
Jay Foad4ba2a172011-01-12 09:06:06 +00007167bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00007168 // Pass through to the C++ ABI object
7169 return ABI->isNearlyEmpty(RD);
7170}
7171
Peter Collingbourne14110472011-01-13 18:57:25 +00007172MangleContext *ASTContext::createMangleContext() {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00007173 switch (Target->getCXXABI()) {
Peter Collingbourne14110472011-01-13 18:57:25 +00007174 case CXXABI_ARM:
7175 case CXXABI_Itanium:
7176 return createItaniumMangleContext(*this, getDiagnostics());
7177 case CXXABI_Microsoft:
7178 return createMicrosoftMangleContext(*this, getDiagnostics());
7179 }
David Blaikieb219cfc2011-09-23 05:06:16 +00007180 llvm_unreachable("Unsupported ABI");
Peter Collingbourne14110472011-01-13 18:57:25 +00007181}
7182
Charles Davis071cc7d2010-08-16 03:33:14 +00007183CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00007184
7185size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +00007186 return ASTRecordLayouts.getMemorySize()
7187 + llvm::capacity_in_bytes(ObjCLayouts)
7188 + llvm::capacity_in_bytes(KeyFunctions)
7189 + llvm::capacity_in_bytes(ObjCImpls)
7190 + llvm::capacity_in_bytes(BlockVarCopyInits)
7191 + llvm::capacity_in_bytes(DeclAttrs)
7192 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7193 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7194 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7195 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7196 + llvm::capacity_in_bytes(OverriddenMethods)
7197 + llvm::capacity_in_bytes(Types)
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007198 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet0d95f0d2011-08-14 14:28:49 +00007199 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekba29bd22011-04-28 04:53:38 +00007200}
Ted Kremenekd211cb72011-10-06 05:00:56 +00007201
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00007202unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7203 CXXRecordDecl *Lambda = CallOperator->getParent();
7204 return LambdaMangleContexts[Lambda->getDeclContext()]
7205 .getManglingNumber(CallOperator);
7206}
7207
7208
Ted Kremenekd211cb72011-10-06 05:00:56 +00007209void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7210 ParamIndices[D] = index;
7211}
7212
7213unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7214 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7215 assert(I != ParamIndices.end() &&
7216 "ParmIndices lacks entry set by ParmVarDecl");
7217 return I->second;
7218}