blob: ad48dffb4d4f93b123efc8b9bf6755c4754e6be9 [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Dmitri Gribenkoca7f80a2012-08-09 00:03:17 +000016#include "clang/AST/CommentCommandTraits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000017#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000018#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +000020#include "clang/AST/TypeLoc.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000021#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000023#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +000024#include "clang/AST/ASTMutationListener.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000025#include "clang/AST/RecordLayout.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000026#include "clang/AST/Mangle.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000027#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000028#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000029#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000030#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000031#include "llvm/ADT/StringExtras.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000032#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000033#include "llvm/Support/raw_ostream.h"
Ted Kremenek7d39c9a2011-07-27 18:41:12 +000034#include "llvm/Support/Capacity.h"
Charles Davis53c59df2010-08-16 03:33:14 +000035#include "CXXABI.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000036#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000037
Chris Lattnerddc135e2006-11-10 06:34:16 +000038using namespace clang;
39
Douglas Gregor9672f922010-07-03 00:47:00 +000040unsigned ASTContext::NumImplicitDefaultConstructors;
41unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000042unsigned ASTContext::NumImplicitCopyConstructors;
43unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000044unsigned ASTContext::NumImplicitMoveConstructors;
45unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000046unsigned ASTContext::NumImplicitCopyAssignmentOperators;
47unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000048unsigned ASTContext::NumImplicitMoveAssignmentOperators;
49unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000050unsigned ASTContext::NumImplicitDestructors;
51unsigned ASTContext::NumImplicitDestructorsDeclared;
52
Steve Naroff0af91202007-04-27 21:51:21 +000053enum FloatingRank {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000054 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Steve Naroff0af91202007-04-27 21:51:21 +000055};
56
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000057RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000058 if (!CommentsLoaded && ExternalSource) {
59 ExternalSource->ReadComments();
60 CommentsLoaded = true;
61 }
62
63 assert(D);
64
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000065 // User can not attach documentation to implicit declarations.
66 if (D->isImplicit())
67 return NULL;
68
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000069 // TODO: handle comments for function parameters properly.
70 if (isa<ParmVarDecl>(D))
71 return NULL;
72
Dmitri Gribenko34df2202012-07-31 22:37:06 +000073 // TODO: we could look up template parameter documentation in the template
74 // documentation.
75 if (isa<TemplateTypeParmDecl>(D) ||
76 isa<NonTypeTemplateParmDecl>(D) ||
77 isa<TemplateTemplateParmDecl>(D))
78 return NULL;
79
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +000080 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000081
82 // If there are no comments anywhere, we won't find anything.
83 if (RawComments.empty())
84 return NULL;
85
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +000086 // Find declaration location.
87 // For Objective-C declarations we generally don't expect to have multiple
88 // declarators, thus use declaration starting location as the "declaration
89 // location".
90 // For all other declarations multiple declarators are used quite frequently,
91 // so we use the location of the identifier as the "declaration location".
92 SourceLocation DeclLoc;
93 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +000094 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +000095 isa<RedeclarableTemplateDecl>(D) ||
96 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +000097 DeclLoc = D->getLocStart();
98 else
99 DeclLoc = D->getLocation();
100
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000101 // If the declaration doesn't map directly to a location in a file, we
102 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000103 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
104 return NULL;
105
106 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000107 ArrayRef<RawComment *>::iterator Comment;
108 {
109 // When searching for comments during parsing, the comment we are looking
110 // for is usually among the last two comments we parsed -- check them
111 // first.
112 RawComment CommentAtDeclLoc(SourceMgr, SourceRange(DeclLoc));
113 BeforeThanCompare<RawComment> Compare(SourceMgr);
114 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
115 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
116 if (!Found && RawComments.size() >= 2) {
117 MaybeBeforeDecl--;
118 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
119 }
120
121 if (Found) {
122 Comment = MaybeBeforeDecl + 1;
123 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
124 &CommentAtDeclLoc, Compare));
125 } else {
126 // Slow path.
127 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
128 &CommentAtDeclLoc, Compare);
129 }
130 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000131
132 // Decompose the location for the declaration and find the beginning of the
133 // file buffer.
134 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
135
136 // First check whether we have a trailing comment.
137 if (Comment != RawComments.end() &&
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000138 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Dmitri Gribenko44cd7e62012-07-06 23:27:33 +0000139 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000140 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000141 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000142 // Check that Doxygen trailing comment comes after the declaration, starts
143 // on the same line and in the same file as the declaration.
144 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
145 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
146 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
147 CommentBeginDecomp.second)) {
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000148 (*Comment)->setDecl(D);
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000149 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000150 }
151 }
152
153 // The comment just after the declaration was not a trailing comment.
154 // Let's look at the previous comment.
155 if (Comment == RawComments.begin())
156 return NULL;
157 --Comment;
158
159 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000160 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000161 return NULL;
162
163 // Decompose the end of the comment.
164 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000165 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000166
167 // If the comment and the declaration aren't in the same file, then they
168 // aren't related.
169 if (DeclLocDecomp.first != CommentEndDecomp.first)
170 return NULL;
171
172 // Get the corresponding buffer.
173 bool Invalid = false;
174 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
175 &Invalid).data();
176 if (Invalid)
177 return NULL;
178
179 // Extract text between the comment and declaration.
180 StringRef Text(Buffer + CommentEndDecomp.second,
181 DeclLocDecomp.second - CommentEndDecomp.second);
182
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000183 // There should be no other declarations or preprocessor directives between
184 // comment and declaration.
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000185 if (Text.find_first_of(",;{}#@") != StringRef::npos)
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000186 return NULL;
187
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000188 (*Comment)->setDecl(D);
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000189 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000190}
191
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000192const RawComment *ASTContext::getRawCommentForAnyRedecl(const Decl *D) const {
Douglas Gregor35ceb272012-08-13 16:37:30 +0000193 // If we have a 'templated' declaration for a template, adjust 'D' to
194 // refer to the actual template.
195 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
196 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
197 D = FTD;
198 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
199 if (const ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
200 D = CTD;
201 }
202 // FIXME: Alias templates?
203
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000204 // Check whether we have cached a comment for this declaration already.
205 {
206 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
207 RedeclComments.find(D);
208 if (Pos != RedeclComments.end()) {
209 const RawCommentAndCacheFlags &Raw = Pos->second;
210 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl)
211 return Raw.getRaw();
212 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000213 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000214
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000215 // Search for comments attached to declarations in the redeclaration chain.
216 const RawComment *RC = NULL;
217 for (Decl::redecl_iterator I = D->redecls_begin(),
218 E = D->redecls_end();
219 I != E; ++I) {
220 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
221 RedeclComments.find(*I);
222 if (Pos != RedeclComments.end()) {
223 const RawCommentAndCacheFlags &Raw = Pos->second;
224 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
225 RC = Raw.getRaw();
226 break;
227 }
228 } else {
229 RC = getRawCommentForDeclNoCache(*I);
230 RawCommentAndCacheFlags Raw;
231 if (RC) {
232 Raw.setRaw(RC);
233 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
234 } else
235 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
236 RedeclComments[*I] = Raw;
237 if (RC)
238 break;
239 }
240 }
241
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000242 // If we found a comment, it should be a documentation comment.
243 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000244
245 // Update cache for every declaration in the redeclaration chain.
246 RawCommentAndCacheFlags Raw;
247 Raw.setRaw(RC);
248 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
249
250 for (Decl::redecl_iterator I = D->redecls_begin(),
251 E = D->redecls_end();
252 I != E; ++I) {
253 RawCommentAndCacheFlags &R = RedeclComments[*I];
254 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
255 R = Raw;
256 }
257
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000258 return RC;
259}
260
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000261comments::FullComment *ASTContext::getCommentForDecl(const Decl *D) const {
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000262 const RawComment *RC = getRawCommentForAnyRedecl(D);
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000263 if (!RC)
264 return NULL;
265
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000266 return RC->getParsed(*this);
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000267}
268
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000269void
270ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
271 TemplateTemplateParmDecl *Parm) {
272 ID.AddInteger(Parm->getDepth());
273 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000274 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000275
276 TemplateParameterList *Params = Parm->getTemplateParameters();
277 ID.AddInteger(Params->size());
278 for (TemplateParameterList::const_iterator P = Params->begin(),
279 PEnd = Params->end();
280 P != PEnd; ++P) {
281 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
282 ID.AddInteger(0);
283 ID.AddBoolean(TTP->isParameterPack());
284 continue;
285 }
286
287 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
288 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000289 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000290 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000291 if (NTTP->isExpandedParameterPack()) {
292 ID.AddBoolean(true);
293 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000294 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
295 QualType T = NTTP->getExpansionType(I);
296 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
297 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000298 } else
299 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000300 continue;
301 }
302
303 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
304 ID.AddInteger(2);
305 Profile(ID, TTP);
306 }
307}
308
309TemplateTemplateParmDecl *
310ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000311 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000312 // Check if we already have a canonical template template parameter.
313 llvm::FoldingSetNodeID ID;
314 CanonicalTemplateTemplateParm::Profile(ID, TTP);
315 void *InsertPos = 0;
316 CanonicalTemplateTemplateParm *Canonical
317 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
318 if (Canonical)
319 return Canonical->getParam();
320
321 // Build a canonical template parameter list.
322 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000323 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000324 CanonParams.reserve(Params->size());
325 for (TemplateParameterList::const_iterator P = Params->begin(),
326 PEnd = Params->end();
327 P != PEnd; ++P) {
328 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
329 CanonParams.push_back(
330 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000331 SourceLocation(),
332 SourceLocation(),
333 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000334 TTP->getIndex(), 0, false,
335 TTP->isParameterPack()));
336 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000337 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
338 QualType T = getCanonicalType(NTTP->getType());
339 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
340 NonTypeTemplateParmDecl *Param;
341 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000342 SmallVector<QualType, 2> ExpandedTypes;
343 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000344 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
345 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
346 ExpandedTInfos.push_back(
347 getTrivialTypeSourceInfo(ExpandedTypes.back()));
348 }
349
350 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000351 SourceLocation(),
352 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000353 NTTP->getDepth(),
354 NTTP->getPosition(), 0,
355 T,
356 TInfo,
357 ExpandedTypes.data(),
358 ExpandedTypes.size(),
359 ExpandedTInfos.data());
360 } else {
361 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000362 SourceLocation(),
363 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000364 NTTP->getDepth(),
365 NTTP->getPosition(), 0,
366 T,
367 NTTP->isParameterPack(),
368 TInfo);
369 }
370 CanonParams.push_back(Param);
371
372 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000373 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
374 cast<TemplateTemplateParmDecl>(*P)));
375 }
376
377 TemplateTemplateParmDecl *CanonTTP
378 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
379 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000380 TTP->getPosition(),
381 TTP->isParameterPack(),
382 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000383 TemplateParameterList::Create(*this, SourceLocation(),
384 SourceLocation(),
385 CanonParams.data(),
386 CanonParams.size(),
387 SourceLocation()));
388
389 // Get the new insert position for the node we care about.
390 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
391 assert(Canonical == 0 && "Shouldn't be in the map!");
392 (void)Canonical;
393
394 // Create the canonical template template parameter entry.
395 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
396 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
397 return CanonTTP;
398}
399
Charles Davis53c59df2010-08-16 03:33:14 +0000400CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000401 if (!LangOpts.CPlusPlus) return 0;
402
Charles Davis6bcb07a2010-08-19 02:18:14 +0000403 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000404 case CXXABI_ARM:
405 return CreateARMCXXABI(*this);
406 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000407 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000408 case CXXABI_Microsoft:
409 return CreateMicrosoftCXXABI(*this);
410 }
David Blaikie8a40f702012-01-17 06:56:22 +0000411 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000412}
413
Douglas Gregore8bbc122011-09-02 00:18:52 +0000414static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000415 const LangOptions &LOpts) {
416 if (LOpts.FakeAddressSpaceMap) {
417 // The fake address space map must have a distinct entry for each
418 // language-specific address space.
419 static const unsigned FakeAddrSpaceMap[] = {
420 1, // opencl_global
421 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000422 3, // opencl_constant
423 4, // cuda_device
424 5, // cuda_constant
425 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000426 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000427 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000428 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000429 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000430 }
431}
432
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000433ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000434 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000435 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000436 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000437 unsigned size_reserve,
438 bool DelayInitialization)
439 : FunctionProtoTypes(this_()),
440 TemplateSpecializationTypes(this_()),
441 DependentTemplateSpecializationTypes(this_()),
442 SubstTemplateTemplateParmPacks(this_()),
443 GlobalNestedNameSpecifier(0),
444 Int128Decl(0), UInt128Decl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000445 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000446 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000447 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000448 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000449 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
450 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
451 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000452 NullTypeSourceInfo(QualType()),
453 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000454 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000455 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000456 Idents(idents), Selectors(sels),
457 BuiltinInfo(builtins),
458 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000459 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000460 Comments(SM), CommentsLoaded(false),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000461 LastSDM(0, 0),
462 UniqueBlockByRefTypeID(0)
463{
Mike Stump11289f42009-09-09 15:08:12 +0000464 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000465 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000466
467 if (!DelayInitialization) {
468 assert(t && "No target supplied for ASTContext initialization");
469 InitBuiltinTypes(*t);
470 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000471}
472
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000473ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000474 // Release the DenseMaps associated with DeclContext objects.
475 // FIXME: Is this the ideal solution?
476 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000477
Douglas Gregor5b11d492010-07-25 17:53:33 +0000478 // Call all of the deallocation functions.
479 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
480 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000481
Ted Kremenek076baeb2010-06-08 23:00:58 +0000482 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000483 // because they can contain DenseMaps.
484 for (llvm::DenseMap<const ObjCContainerDecl*,
485 const ASTRecordLayout*>::iterator
486 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
487 // Increment in loop to prevent using deallocated memory.
488 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
489 R->Destroy(*this);
490
Ted Kremenek076baeb2010-06-08 23:00:58 +0000491 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
492 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
493 // Increment in loop to prevent using deallocated memory.
494 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
495 R->Destroy(*this);
496 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000497
498 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
499 AEnd = DeclAttrs.end();
500 A != AEnd; ++A)
501 A->second->~AttrVec();
502}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000503
Douglas Gregor1a809332010-05-23 18:26:36 +0000504void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
505 Deallocations.push_back(std::make_pair(Callback, Data));
506}
507
Mike Stump11289f42009-09-09 15:08:12 +0000508void
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000509ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000510 ExternalSource.reset(Source.take());
511}
512
Chris Lattner4eb445d2007-01-26 01:27:23 +0000513void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000514 llvm::errs() << "\n*** AST Context Stats:\n";
515 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000516
Douglas Gregora30d0462009-05-26 14:40:08 +0000517 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000518#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000519#define ABSTRACT_TYPE(Name, Parent)
520#include "clang/AST/TypeNodes.def"
521 0 // Extra
522 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000523
Chris Lattner4eb445d2007-01-26 01:27:23 +0000524 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
525 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000526 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000527 }
528
Douglas Gregora30d0462009-05-26 14:40:08 +0000529 unsigned Idx = 0;
530 unsigned TotalBytes = 0;
531#define TYPE(Name, Parent) \
532 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000533 llvm::errs() << " " << counts[Idx] << " " << #Name \
534 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000535 TotalBytes += counts[Idx] * sizeof(Name##Type); \
536 ++Idx;
537#define ABSTRACT_TYPE(Name, Parent)
538#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000539
Chandler Carruth3c147a72011-07-04 05:32:14 +0000540 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
541
Douglas Gregor7454c562010-07-02 20:37:36 +0000542 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000543 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
544 << NumImplicitDefaultConstructors
545 << " implicit default constructors created\n";
546 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
547 << NumImplicitCopyConstructors
548 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000549 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000550 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
551 << NumImplicitMoveConstructors
552 << " implicit move constructors created\n";
553 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
554 << NumImplicitCopyAssignmentOperators
555 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000556 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000557 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
558 << NumImplicitMoveAssignmentOperators
559 << " implicit move assignment operators created\n";
560 llvm::errs() << NumImplicitDestructorsDeclared << "/"
561 << NumImplicitDestructors
562 << " implicit destructors created\n";
563
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000564 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000565 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000566 ExternalSource->PrintStats();
567 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000568
Douglas Gregor5b11d492010-07-25 17:53:33 +0000569 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000570}
571
Douglas Gregor801c99d2011-08-12 06:49:56 +0000572TypedefDecl *ASTContext::getInt128Decl() const {
573 if (!Int128Decl) {
574 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
575 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
576 getTranslationUnitDecl(),
577 SourceLocation(),
578 SourceLocation(),
579 &Idents.get("__int128_t"),
580 TInfo);
581 }
582
583 return Int128Decl;
584}
585
586TypedefDecl *ASTContext::getUInt128Decl() const {
587 if (!UInt128Decl) {
588 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
589 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
590 getTranslationUnitDecl(),
591 SourceLocation(),
592 SourceLocation(),
593 &Idents.get("__uint128_t"),
594 TInfo);
595 }
596
597 return UInt128Decl;
598}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000599
John McCall48f2d582009-10-23 23:03:21 +0000600void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000601 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000602 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000603 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000604}
605
Douglas Gregore8bbc122011-09-02 00:18:52 +0000606void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
607 assert((!this->Target || this->Target == &Target) &&
608 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000609 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000610
Douglas Gregore8bbc122011-09-02 00:18:52 +0000611 this->Target = &Target;
612
613 ABI.reset(createCXXABI(Target));
614 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
615
Chris Lattner970e54e2006-11-12 00:37:36 +0000616 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000617 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000618
Chris Lattner970e54e2006-11-12 00:37:36 +0000619 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000620 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000621 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000622 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000623 InitBuiltinType(CharTy, BuiltinType::Char_S);
624 else
625 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000626 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000627 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
628 InitBuiltinType(ShortTy, BuiltinType::Short);
629 InitBuiltinType(IntTy, BuiltinType::Int);
630 InitBuiltinType(LongTy, BuiltinType::Long);
631 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000632
Chris Lattner970e54e2006-11-12 00:37:36 +0000633 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000634 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
635 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
636 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
637 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
638 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000639
Chris Lattner970e54e2006-11-12 00:37:36 +0000640 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000641 InitBuiltinType(FloatTy, BuiltinType::Float);
642 InitBuiltinType(DoubleTy, BuiltinType::Double);
643 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000644
Chris Lattnerf122cef2009-04-30 02:43:43 +0000645 // GNU extension, 128-bit integers.
646 InitBuiltinType(Int128Ty, BuiltinType::Int128);
647 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
648
Chris Lattnerad3467e2010-12-25 23:25:43 +0000649 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedman786d0872011-04-30 19:24:24 +0000650 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000651 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
652 else // -fshort-wchar makes wchar_t be unsigned.
653 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
654 } else // C99
Chris Lattner007cb022009-02-26 23:43:47 +0000655 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000656
James Molloy36365542012-05-04 10:55:22 +0000657 WIntTy = getFromTargetType(Target.getWIntType());
658
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000659 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
660 InitBuiltinType(Char16Ty, BuiltinType::Char16);
661 else // C99
662 Char16Ty = getFromTargetType(Target.getChar16Type());
663
664 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
665 InitBuiltinType(Char32Ty, BuiltinType::Char32);
666 else // C99
667 Char32Ty = getFromTargetType(Target.getChar32Type());
668
Douglas Gregor4619e432008-12-05 23:32:09 +0000669 // Placeholder type for type-dependent expressions whose type is
670 // completely unknown. No code should ever check a type against
671 // DependentTy and users should never see it; however, it is here to
672 // help diagnose failures to properly check for type-dependent
673 // expressions.
674 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000675
John McCall36e7fe32010-10-12 00:20:44 +0000676 // Placeholder type for functions.
677 InitBuiltinType(OverloadTy, BuiltinType::Overload);
678
John McCall0009fcc2011-04-26 20:42:42 +0000679 // Placeholder type for bound members.
680 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
681
John McCall526ab472011-10-25 17:37:35 +0000682 // Placeholder type for pseudo-objects.
683 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
684
John McCall31996342011-04-07 08:22:57 +0000685 // "any" type; useful for debugger-like clients.
686 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
687
John McCall8a6b59a2011-10-17 18:09:15 +0000688 // Placeholder type for unbridged ARC casts.
689 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
690
Chris Lattner970e54e2006-11-12 00:37:36 +0000691 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000692 FloatComplexTy = getComplexType(FloatTy);
693 DoubleComplexTy = getComplexType(DoubleTy);
694 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000695
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000696 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000697 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
698 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000699 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000700
701 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +0000702 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
703 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000704
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000705 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000706
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000707 // void * type
708 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000709
710 // nullptr type (C++0x 2.14.7)
711 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000712
713 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
714 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +0000715
716 // Builtin type used to help define __builtin_va_list.
717 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +0000718}
719
David Blaikie9c902b52011-09-25 23:23:43 +0000720DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000721 return SourceMgr.getDiagnostics();
722}
723
Douglas Gregor561eceb2010-08-30 16:49:28 +0000724AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
725 AttrVec *&Result = DeclAttrs[D];
726 if (!Result) {
727 void *Mem = Allocate(sizeof(AttrVec));
728 Result = new (Mem) AttrVec;
729 }
730
731 return *Result;
732}
733
734/// \brief Erase the attributes corresponding to the given declaration.
735void ASTContext::eraseDeclAttrs(const Decl *D) {
736 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
737 if (Pos != DeclAttrs.end()) {
738 Pos->second->~AttrVec();
739 DeclAttrs.erase(Pos);
740 }
741}
742
Douglas Gregor86d142a2009-10-08 07:24:58 +0000743MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000744ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000745 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000746 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000747 = InstantiatedFromStaticDataMember.find(Var);
748 if (Pos == InstantiatedFromStaticDataMember.end())
749 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000750
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000751 return Pos->second;
752}
753
Mike Stump11289f42009-09-09 15:08:12 +0000754void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000755ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000756 TemplateSpecializationKind TSK,
757 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000758 assert(Inst->isStaticDataMember() && "Not a static data member");
759 assert(Tmpl->isStaticDataMember() && "Not a static data member");
760 assert(!InstantiatedFromStaticDataMember[Inst] &&
761 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000762 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000763 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000764}
765
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000766FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
767 const FunctionDecl *FD){
768 assert(FD && "Specialization is 0");
769 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +0000770 = ClassScopeSpecializationPattern.find(FD);
771 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000772 return 0;
773
774 return Pos->second;
775}
776
777void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
778 FunctionDecl *Pattern) {
779 assert(FD && "Specialization is 0");
780 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +0000781 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000782}
783
John McCalle61f2ba2009-11-18 02:36:19 +0000784NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000785ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000786 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000787 = InstantiatedFromUsingDecl.find(UUD);
788 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000789 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000790
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000791 return Pos->second;
792}
793
794void
John McCallb96ec562009-12-04 22:46:56 +0000795ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
796 assert((isa<UsingDecl>(Pattern) ||
797 isa<UnresolvedUsingValueDecl>(Pattern) ||
798 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
799 "pattern decl is not a using decl");
800 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
801 InstantiatedFromUsingDecl[Inst] = Pattern;
802}
803
804UsingShadowDecl *
805ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
806 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
807 = InstantiatedFromUsingShadowDecl.find(Inst);
808 if (Pos == InstantiatedFromUsingShadowDecl.end())
809 return 0;
810
811 return Pos->second;
812}
813
814void
815ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
816 UsingShadowDecl *Pattern) {
817 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
818 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000819}
820
Anders Carlsson5da84842009-09-01 04:26:58 +0000821FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
822 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
823 = InstantiatedFromUnnamedFieldDecl.find(Field);
824 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
825 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000826
Anders Carlsson5da84842009-09-01 04:26:58 +0000827 return Pos->second;
828}
829
830void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
831 FieldDecl *Tmpl) {
832 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
833 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
834 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
835 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000836
Anders Carlsson5da84842009-09-01 04:26:58 +0000837 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
838}
839
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000840bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
841 const FieldDecl *LastFD) const {
842 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000843 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000844}
845
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000846bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
847 const FieldDecl *LastFD) const {
848 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000849 FD->getBitWidthValue(*this) == 0 &&
850 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000851}
852
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000853bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
854 const FieldDecl *LastFD) const {
855 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000856 FD->getBitWidthValue(*this) &&
857 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000858}
859
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000860bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000861 const FieldDecl *LastFD) const {
862 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000863 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000864}
865
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000866bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000867 const FieldDecl *LastFD) const {
868 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000869 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000870}
871
Douglas Gregor832940b2010-03-02 23:58:15 +0000872ASTContext::overridden_cxx_method_iterator
873ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
874 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
875 = OverriddenMethods.find(Method);
876 if (Pos == OverriddenMethods.end())
877 return 0;
878
879 return Pos->second.begin();
880}
881
882ASTContext::overridden_cxx_method_iterator
883ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
884 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
885 = OverriddenMethods.find(Method);
886 if (Pos == OverriddenMethods.end())
887 return 0;
888
889 return Pos->second.end();
890}
891
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000892unsigned
893ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
894 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
895 = OverriddenMethods.find(Method);
896 if (Pos == OverriddenMethods.end())
897 return 0;
898
899 return Pos->second.size();
900}
901
Douglas Gregor832940b2010-03-02 23:58:15 +0000902void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
903 const CXXMethodDecl *Overridden) {
904 OverriddenMethods[Method].push_back(Overridden);
905}
906
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000907void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
908 assert(!Import->NextLocalImport && "Import declaration already in the chain");
909 assert(!Import->isFromASTFile() && "Non-local import declaration");
910 if (!FirstLocalImport) {
911 FirstLocalImport = Import;
912 LastLocalImport = Import;
913 return;
914 }
915
916 LastLocalImport->NextLocalImport = Import;
917 LastLocalImport = Import;
918}
919
Chris Lattner53cfe802007-07-18 17:52:12 +0000920//===----------------------------------------------------------------------===//
921// Type Sizing and Analysis
922//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000923
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000924/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
925/// scalar floating point type.
926const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000927 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000928 assert(BT && "Not a floating point type!");
929 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +0000930 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000931 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +0000932 case BuiltinType::Float: return Target->getFloatFormat();
933 case BuiltinType::Double: return Target->getDoubleFormat();
934 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000935 }
936}
937
Ken Dyck160146e2010-01-27 17:10:57 +0000938/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000939/// specified decl. Note that bitfields do not have a valid alignment, so
940/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000941/// If @p RefAsPointee, references are treated like their underlying type
942/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000943CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000944 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +0000945
John McCall94268702010-10-08 18:24:19 +0000946 bool UseAlignAttrOnly = false;
947 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
948 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000949
John McCall94268702010-10-08 18:24:19 +0000950 // __attribute__((aligned)) can increase or decrease alignment
951 // *except* on a struct or struct member, where it only increases
952 // alignment unless 'packed' is also specified.
953 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +0000954 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +0000955 // ignore that possibility; Sema should diagnose it.
956 if (isa<FieldDecl>(D)) {
957 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
958 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
959 } else {
960 UseAlignAttrOnly = true;
961 }
962 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +0000963 else if (isa<FieldDecl>(D))
964 UseAlignAttrOnly =
965 D->hasAttr<PackedAttr>() ||
966 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +0000967
John McCall4e819612011-01-20 07:57:12 +0000968 // If we're using the align attribute only, just ignore everything
969 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +0000970 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +0000971 // do nothing
972
John McCall94268702010-10-08 18:24:19 +0000973 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000974 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000975 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000976 if (RefAsPointee)
977 T = RT->getPointeeType();
978 else
979 T = getPointerType(RT->getPointeeType());
980 }
981 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +0000982 // Adjust alignments of declarations with array type by the
983 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +0000984 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +0000985 const ArrayType *arrayType;
986 if (MinWidth && (arrayType = getAsArrayType(T))) {
987 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000988 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +0000989 else if (isa<ConstantArrayType>(arrayType) &&
990 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000991 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +0000992
John McCall33ddac02011-01-19 10:06:00 +0000993 // Walk through any array types while we're at it.
994 T = getBaseElementType(arrayType);
995 }
Chad Rosier99ee7822011-07-26 07:03:04 +0000996 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +0000997 }
John McCall4e819612011-01-20 07:57:12 +0000998
999 // Fields can be subject to extra alignment constraints, like if
1000 // the field is packed, the struct is packed, or the struct has a
1001 // a max-field-alignment constraint (#pragma pack). So calculate
1002 // the actual alignment of the field within the struct, and then
1003 // (as we're expected to) constrain that by the alignment of the type.
1004 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
1005 // So calculate the alignment of the field.
1006 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
1007
1008 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +00001009 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001010
1011 // Use the GCD of that and the offset within the record.
1012 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
1013 if (offset > 0) {
1014 // Alignment is always a power of 2, so the GCD will be a power of 2,
1015 // which means we get to do this crazy thing instead of Euclid's.
1016 uint64_t lowBitOfOffset = offset & (~offset + 1);
1017 if (lowBitOfOffset < fieldAlign)
1018 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
1019 }
1020
1021 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +00001022 }
Chris Lattner68061312009-01-24 21:53:27 +00001023 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001024
Ken Dyckcc56c542011-01-15 18:38:59 +00001025 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001026}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001027
John McCall87fe5d52010-05-20 01:18:31 +00001028std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001029ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001030 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +00001031 return std::make_pair(toCharUnitsFromBits(Info.first),
1032 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +00001033}
1034
1035std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001036ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001037 return getTypeInfoInChars(T.getTypePtr());
1038}
1039
Daniel Dunbarc6475872012-03-09 04:12:54 +00001040std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1041 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1042 if (it != MemoizedTypeInfo.end())
1043 return it->second;
1044
1045 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1046 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1047 return Info;
1048}
1049
1050/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1051/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001052///
1053/// FIXME: Pointers into different addr spaces could have different sizes and
1054/// alignment requirements: getPointerInfo should take an AddrSpace, this
1055/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +00001056std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +00001057ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +00001058 uint64_t Width=0;
1059 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001060 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001061#define TYPE(Class, Base)
1062#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001063#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001064#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1065#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001066 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001067
Chris Lattner355332d2007-07-13 22:27:08 +00001068 case Type::FunctionNoProto:
1069 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001070 // GCC extension: alignof(function) = 32 bits
1071 Width = 0;
1072 Align = 32;
1073 break;
1074
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001075 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001076 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001077 Width = 0;
1078 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1079 break;
1080
Steve Naroff5c131802007-08-30 01:06:46 +00001081 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001082 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001083
Chris Lattner37e05872008-03-05 18:54:05 +00001084 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001085 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +00001086 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1087 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001088 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001089 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +00001090 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001091 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001092 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001093 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001094 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001095 const VectorType *VT = cast<VectorType>(T);
1096 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1097 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001098 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001099 // If the alignment is not a power of 2, round up to the next power of 2.
1100 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001101 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001102 Align = llvm::NextPowerOf2(Align);
1103 Width = llvm::RoundUpToAlignment(Width, Align);
1104 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001105 // Adjust the alignment based on the target max.
1106 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1107 if (TargetVectorAlign && TargetVectorAlign < Align)
1108 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001109 break;
1110 }
Chris Lattner647fb222007-07-18 18:26:58 +00001111
Chris Lattner7570e9c2008-03-08 08:52:55 +00001112 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001113 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001114 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001115 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001116 // GCC extension: alignof(void) = 8 bits.
1117 Width = 0;
1118 Align = 8;
1119 break;
1120
Chris Lattner6a4f7452007-12-19 19:23:28 +00001121 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001122 Width = Target->getBoolWidth();
1123 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001124 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001125 case BuiltinType::Char_S:
1126 case BuiltinType::Char_U:
1127 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001128 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001129 Width = Target->getCharWidth();
1130 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001131 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001132 case BuiltinType::WChar_S:
1133 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001134 Width = Target->getWCharWidth();
1135 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001136 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001137 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001138 Width = Target->getChar16Width();
1139 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001140 break;
1141 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001142 Width = Target->getChar32Width();
1143 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001144 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001145 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001146 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001147 Width = Target->getShortWidth();
1148 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001149 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001150 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001151 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001152 Width = Target->getIntWidth();
1153 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001154 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001155 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001156 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001157 Width = Target->getLongWidth();
1158 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001159 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001160 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001161 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001162 Width = Target->getLongLongWidth();
1163 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001164 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001165 case BuiltinType::Int128:
1166 case BuiltinType::UInt128:
1167 Width = 128;
1168 Align = 128; // int128_t is 128-bit aligned on all targets.
1169 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001170 case BuiltinType::Half:
1171 Width = Target->getHalfWidth();
1172 Align = Target->getHalfAlign();
1173 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001174 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001175 Width = Target->getFloatWidth();
1176 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001177 break;
1178 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001179 Width = Target->getDoubleWidth();
1180 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001181 break;
1182 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001183 Width = Target->getLongDoubleWidth();
1184 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001185 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001186 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001187 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1188 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001189 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001190 case BuiltinType::ObjCId:
1191 case BuiltinType::ObjCClass:
1192 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001193 Width = Target->getPointerWidth(0);
1194 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001195 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001196 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001197 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001198 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001199 Width = Target->getPointerWidth(0);
1200 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001201 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001202 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001203 unsigned AS = getTargetAddressSpace(
1204 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001205 Width = Target->getPointerWidth(AS);
1206 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001207 break;
1208 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001209 case Type::LValueReference:
1210 case Type::RValueReference: {
1211 // alignof and sizeof should never enter this code path here, so we go
1212 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001213 unsigned AS = getTargetAddressSpace(
1214 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001215 Width = Target->getPointerWidth(AS);
1216 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001217 break;
1218 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001219 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001220 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001221 Width = Target->getPointerWidth(AS);
1222 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001223 break;
1224 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001225 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001226 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001227 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +00001228 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +00001229 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001230 Align = PtrDiffInfo.second;
1231 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001232 }
Chris Lattner647fb222007-07-18 18:26:58 +00001233 case Type::Complex: {
1234 // Complex types have the same alignment as their elements, but twice the
1235 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001236 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001237 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001238 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001239 Align = EltInfo.second;
1240 break;
1241 }
John McCall8b07ec22010-05-15 11:32:37 +00001242 case Type::ObjCObject:
1243 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001244 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001245 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001246 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001247 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001248 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001249 break;
1250 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001251 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001252 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001253 const TagType *TT = cast<TagType>(T);
1254
1255 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001256 Width = 8;
1257 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001258 break;
1259 }
Mike Stump11289f42009-09-09 15:08:12 +00001260
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001261 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001262 return getTypeInfo(ET->getDecl()->getIntegerType());
1263
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001264 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001265 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001266 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001267 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001268 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001269 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001270
Chris Lattner63d2b362009-10-22 05:17:15 +00001271 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001272 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1273 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001274
Richard Smith30482bc2011-02-20 03:19:35 +00001275 case Type::Auto: {
1276 const AutoType *A = cast<AutoType>(T);
1277 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001278 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001279 }
1280
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001281 case Type::Paren:
1282 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1283
Douglas Gregoref462e62009-04-30 17:32:17 +00001284 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001285 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001286 std::pair<uint64_t, unsigned> Info
1287 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001288 // If the typedef has an aligned attribute on it, it overrides any computed
1289 // alignment we have. This violates the GCC documentation (which says that
1290 // attribute(aligned) can only round up) but matches its implementation.
1291 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1292 Align = AttrAlign;
1293 else
1294 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001295 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001296 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001297 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001298
1299 case Type::TypeOfExpr:
1300 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1301 .getTypePtr());
1302
1303 case Type::TypeOf:
1304 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1305
Anders Carlsson81df7b82009-06-24 19:06:50 +00001306 case Type::Decltype:
1307 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1308 .getTypePtr());
1309
Alexis Hunte852b102011-05-24 22:41:36 +00001310 case Type::UnaryTransform:
1311 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1312
Abramo Bagnara6150c882010-05-11 21:36:43 +00001313 case Type::Elaborated:
1314 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001315
John McCall81904512011-01-06 01:58:22 +00001316 case Type::Attributed:
1317 return getTypeInfo(
1318 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1319
Richard Smith3f1b5d02011-05-05 21:57:07 +00001320 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001321 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001322 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001323 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1324 // A type alias template specialization may refer to a typedef with the
1325 // aligned attribute on it.
1326 if (TST->isTypeAlias())
1327 return getTypeInfo(TST->getAliasedType().getTypePtr());
1328 else
1329 return getTypeInfo(getCanonicalType(T));
1330 }
1331
Eli Friedman0dfb8892011-10-06 23:00:33 +00001332 case Type::Atomic: {
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001333 std::pair<uint64_t, unsigned> Info
1334 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1335 Width = Info.first;
1336 Align = Info.second;
1337 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1338 llvm::isPowerOf2_64(Width)) {
1339 // We can potentially perform lock-free atomic operations for this
1340 // type; promote the alignment appropriately.
1341 // FIXME: We could potentially promote the width here as well...
1342 // is that worthwhile? (Non-struct atomic types generally have
1343 // power-of-two size anyway, but structs might not. Requires a bit
1344 // of implementation work to make sure we zero out the extra bits.)
1345 Align = static_cast<unsigned>(Width);
1346 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001347 }
1348
Douglas Gregoref462e62009-04-30 17:32:17 +00001349 }
Mike Stump11289f42009-09-09 15:08:12 +00001350
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001351 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001352 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001353}
1354
Ken Dyckcc56c542011-01-15 18:38:59 +00001355/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1356CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1357 return CharUnits::fromQuantity(BitSize / getCharWidth());
1358}
1359
Ken Dyckb0fcc592011-02-11 01:54:29 +00001360/// toBits - Convert a size in characters to a size in characters.
1361int64_t ASTContext::toBits(CharUnits CharSize) const {
1362 return CharSize.getQuantity() * getCharWidth();
1363}
1364
Ken Dyck8c89d592009-12-22 14:23:30 +00001365/// getTypeSizeInChars - Return the size of the specified type, in characters.
1366/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001367CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001368 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001369}
Jay Foad39c79802011-01-12 09:06:06 +00001370CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001371 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001372}
1373
Ken Dycka6046ab2010-01-26 17:25:18 +00001374/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001375/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001376CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001377 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001378}
Jay Foad39c79802011-01-12 09:06:06 +00001379CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001380 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001381}
1382
Chris Lattnera3402cd2009-01-27 18:08:34 +00001383/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1384/// type for the current target in bits. This can be different than the ABI
1385/// alignment in cases where it is beneficial for performance to overalign
1386/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001387unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001388 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001389
1390 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001391 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001392 T = CT->getElementType().getTypePtr();
1393 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001394 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1395 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001396 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1397
Chris Lattnera3402cd2009-01-27 18:08:34 +00001398 return ABIAlign;
1399}
1400
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001401/// DeepCollectObjCIvars -
1402/// This routine first collects all declared, but not synthesized, ivars in
1403/// super class and then collects all ivars, including those synthesized for
1404/// current class. This routine is used for implementation of current class
1405/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001406///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001407void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1408 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001409 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001410 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1411 DeepCollectObjCIvars(SuperClass, false, Ivars);
1412 if (!leafClass) {
1413 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1414 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001415 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001416 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001417 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001418 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001419 Iv= Iv->getNextIvar())
1420 Ivars.push_back(Iv);
1421 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001422}
1423
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001424/// CollectInheritedProtocols - Collect all protocols in current class and
1425/// those inherited by it.
1426void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001427 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001428 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001429 // We can use protocol_iterator here instead of
1430 // all_referenced_protocol_iterator since we are walking all categories.
1431 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1432 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001433 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001434 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001435 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001436 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001437 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001438 CollectInheritedProtocols(*P, Protocols);
1439 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001440 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001441
1442 // Categories of this Interface.
1443 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1444 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1445 CollectInheritedProtocols(CDeclChain, Protocols);
1446 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1447 while (SD) {
1448 CollectInheritedProtocols(SD, Protocols);
1449 SD = SD->getSuperClass();
1450 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001451 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001452 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001453 PE = OC->protocol_end(); P != PE; ++P) {
1454 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001455 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001456 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1457 PE = Proto->protocol_end(); P != PE; ++P)
1458 CollectInheritedProtocols(*P, Protocols);
1459 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001460 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001461 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1462 PE = OP->protocol_end(); P != PE; ++P) {
1463 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001464 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001465 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1466 PE = Proto->protocol_end(); P != PE; ++P)
1467 CollectInheritedProtocols(*P, Protocols);
1468 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001469 }
1470}
1471
Jay Foad39c79802011-01-12 09:06:06 +00001472unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001473 unsigned count = 0;
1474 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001475 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1476 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001477 count += CDecl->ivar_size();
1478
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001479 // Count ivar defined in this class's implementation. This
1480 // includes synthesized ivars.
1481 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001482 count += ImplDecl->ivar_size();
1483
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001484 return count;
1485}
1486
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001487bool ASTContext::isSentinelNullExpr(const Expr *E) {
1488 if (!E)
1489 return false;
1490
1491 // nullptr_t is always treated as null.
1492 if (E->getType()->isNullPtrType()) return true;
1493
1494 if (E->getType()->isAnyPointerType() &&
1495 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1496 Expr::NPC_ValueDependentIsNull))
1497 return true;
1498
1499 // Unfortunately, __null has type 'int'.
1500 if (isa<GNUNullExpr>(E)) return true;
1501
1502 return false;
1503}
1504
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001505/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1506ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1507 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1508 I = ObjCImpls.find(D);
1509 if (I != ObjCImpls.end())
1510 return cast<ObjCImplementationDecl>(I->second);
1511 return 0;
1512}
1513/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1514ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1515 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1516 I = ObjCImpls.find(D);
1517 if (I != ObjCImpls.end())
1518 return cast<ObjCCategoryImplDecl>(I->second);
1519 return 0;
1520}
1521
1522/// \brief Set the implementation of ObjCInterfaceDecl.
1523void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1524 ObjCImplementationDecl *ImplD) {
1525 assert(IFaceD && ImplD && "Passed null params");
1526 ObjCImpls[IFaceD] = ImplD;
1527}
1528/// \brief Set the implementation of ObjCCategoryDecl.
1529void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1530 ObjCCategoryImplDecl *ImplD) {
1531 assert(CatD && ImplD && "Passed null params");
1532 ObjCImpls[CatD] = ImplD;
1533}
1534
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001535ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1536 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1537 return ID;
1538 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1539 return CD->getClassInterface();
1540 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1541 return IMD->getClassInterface();
1542
1543 return 0;
1544}
1545
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001546/// \brief Get the copy initialization expression of VarDecl,or NULL if
1547/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001548Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001549 assert(VD && "Passed null params");
1550 assert(VD->hasAttr<BlocksAttr>() &&
1551 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001552 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001553 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001554 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1555}
1556
1557/// \brief Set the copy inialization expression of a block var decl.
1558void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1559 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001560 assert(VD->hasAttr<BlocksAttr>() &&
1561 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001562 BlockVarCopyInits[VD] = Init;
1563}
1564
John McCallbcd03502009-12-07 02:54:59 +00001565TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001566 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001567 if (!DataSize)
1568 DataSize = TypeLoc::getFullDataSizeForType(T);
1569 else
1570 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001571 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001572
John McCallbcd03502009-12-07 02:54:59 +00001573 TypeSourceInfo *TInfo =
1574 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1575 new (TInfo) TypeSourceInfo(T);
1576 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001577}
1578
John McCallbcd03502009-12-07 02:54:59 +00001579TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001580 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001581 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001582 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001583 return DI;
1584}
1585
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001586const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001587ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001588 return getObjCLayout(D, 0);
1589}
1590
1591const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001592ASTContext::getASTObjCImplementationLayout(
1593 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001594 return getObjCLayout(D->getClassInterface(), D);
1595}
1596
Chris Lattner983a8bb2007-07-13 22:13:22 +00001597//===----------------------------------------------------------------------===//
1598// Type creation/memoization methods
1599//===----------------------------------------------------------------------===//
1600
Jay Foad39c79802011-01-12 09:06:06 +00001601QualType
John McCall33ddac02011-01-19 10:06:00 +00001602ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1603 unsigned fastQuals = quals.getFastQualifiers();
1604 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001605
1606 // Check if we've already instantiated this type.
1607 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001608 ExtQuals::Profile(ID, baseType, quals);
1609 void *insertPos = 0;
1610 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1611 assert(eq->getQualifiers() == quals);
1612 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001613 }
1614
John McCall33ddac02011-01-19 10:06:00 +00001615 // If the base type is not canonical, make the appropriate canonical type.
1616 QualType canon;
1617 if (!baseType->isCanonicalUnqualified()) {
1618 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00001619 canonSplit.Quals.addConsistentQualifiers(quals);
1620 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001621
1622 // Re-find the insert position.
1623 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1624 }
1625
1626 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1627 ExtQualNodes.InsertNode(eq, insertPos);
1628 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001629}
1630
Jay Foad39c79802011-01-12 09:06:06 +00001631QualType
1632ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001633 QualType CanT = getCanonicalType(T);
1634 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001635 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001636
John McCall8ccfcb52009-09-24 19:53:00 +00001637 // If we are composing extended qualifiers together, merge together
1638 // into one ExtQuals node.
1639 QualifierCollector Quals;
1640 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001641
John McCall8ccfcb52009-09-24 19:53:00 +00001642 // If this type already has an address space specified, it cannot get
1643 // another one.
1644 assert(!Quals.hasAddressSpace() &&
1645 "Type cannot be in multiple addr spaces!");
1646 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001647
John McCall8ccfcb52009-09-24 19:53:00 +00001648 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001649}
1650
Chris Lattnerd60183d2009-02-18 22:53:11 +00001651QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001652 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001653 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001654 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001655 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001656
John McCall53fa7142010-12-24 02:08:15 +00001657 if (const PointerType *ptr = T->getAs<PointerType>()) {
1658 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001659 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001660 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1661 return getPointerType(ResultType);
1662 }
1663 }
Mike Stump11289f42009-09-09 15:08:12 +00001664
John McCall8ccfcb52009-09-24 19:53:00 +00001665 // If we are composing extended qualifiers together, merge together
1666 // into one ExtQuals node.
1667 QualifierCollector Quals;
1668 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001669
John McCall8ccfcb52009-09-24 19:53:00 +00001670 // If this type already has an ObjCGC specified, it cannot get
1671 // another one.
1672 assert(!Quals.hasObjCGCAttr() &&
1673 "Type cannot have multiple ObjCGCs!");
1674 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001675
John McCall8ccfcb52009-09-24 19:53:00 +00001676 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001677}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001678
John McCall4f5019e2010-12-19 02:44:49 +00001679const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1680 FunctionType::ExtInfo Info) {
1681 if (T->getExtInfo() == Info)
1682 return T;
1683
1684 QualType Result;
1685 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1686 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1687 } else {
1688 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1689 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1690 EPI.ExtInfo = Info;
1691 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1692 FPT->getNumArgs(), EPI);
1693 }
1694
1695 return cast<FunctionType>(Result.getTypePtr());
1696}
1697
Chris Lattnerc6395932007-06-22 20:56:16 +00001698/// getComplexType - Return the uniqued reference to the type for a complex
1699/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001700QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001701 // Unique pointers, to guarantee there is only one pointer of a particular
1702 // structure.
1703 llvm::FoldingSetNodeID ID;
1704 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001705
Chris Lattnerc6395932007-06-22 20:56:16 +00001706 void *InsertPos = 0;
1707 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1708 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001709
Chris Lattnerc6395932007-06-22 20:56:16 +00001710 // If the pointee type isn't canonical, this won't be a canonical type either,
1711 // so fill in the canonical type field.
1712 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001713 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001714 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001715
Chris Lattnerc6395932007-06-22 20:56:16 +00001716 // Get the new insert position for the node we care about.
1717 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001718 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001719 }
John McCall90d1c2d2009-09-24 23:30:46 +00001720 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001721 Types.push_back(New);
1722 ComplexTypes.InsertNode(New, InsertPos);
1723 return QualType(New, 0);
1724}
1725
Chris Lattner970e54e2006-11-12 00:37:36 +00001726/// getPointerType - Return the uniqued reference to the type for a pointer to
1727/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001728QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001729 // Unique pointers, to guarantee there is only one pointer of a particular
1730 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001731 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001732 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001733
Chris Lattner67521df2007-01-27 01:29:36 +00001734 void *InsertPos = 0;
1735 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001736 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001737
Chris Lattner7ccecb92006-11-12 08:50:50 +00001738 // If the pointee type isn't canonical, this won't be a canonical type either,
1739 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001740 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001741 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001742 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001743
Chris Lattner67521df2007-01-27 01:29:36 +00001744 // Get the new insert position for the node we care about.
1745 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001746 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001747 }
John McCall90d1c2d2009-09-24 23:30:46 +00001748 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001749 Types.push_back(New);
1750 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001751 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001752}
1753
Mike Stump11289f42009-09-09 15:08:12 +00001754/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001755/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001756QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001757 assert(T->isFunctionType() && "block of function types only");
1758 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001759 // structure.
1760 llvm::FoldingSetNodeID ID;
1761 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001762
Steve Naroffec33ed92008-08-27 16:04:49 +00001763 void *InsertPos = 0;
1764 if (BlockPointerType *PT =
1765 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1766 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001767
1768 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001769 // type either so fill in the canonical type field.
1770 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001771 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001772 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001773
Steve Naroffec33ed92008-08-27 16:04:49 +00001774 // Get the new insert position for the node we care about.
1775 BlockPointerType *NewIP =
1776 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001777 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001778 }
John McCall90d1c2d2009-09-24 23:30:46 +00001779 BlockPointerType *New
1780 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001781 Types.push_back(New);
1782 BlockPointerTypes.InsertNode(New, InsertPos);
1783 return QualType(New, 0);
1784}
1785
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001786/// getLValueReferenceType - Return the uniqued reference to the type for an
1787/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001788QualType
1789ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00001790 assert(getCanonicalType(T) != OverloadTy &&
1791 "Unresolved overloaded function type");
1792
Bill Wendling3708c182007-05-27 10:15:43 +00001793 // Unique pointers, to guarantee there is only one pointer of a particular
1794 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001795 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001796 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001797
1798 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001799 if (LValueReferenceType *RT =
1800 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001801 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001802
John McCallfc93cf92009-10-22 22:37:11 +00001803 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1804
Bill Wendling3708c182007-05-27 10:15:43 +00001805 // If the referencee type isn't canonical, this won't be a canonical type
1806 // either, so fill in the canonical type field.
1807 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001808 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1809 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1810 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001811
Bill Wendling3708c182007-05-27 10:15:43 +00001812 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001813 LValueReferenceType *NewIP =
1814 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001815 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001816 }
1817
John McCall90d1c2d2009-09-24 23:30:46 +00001818 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001819 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1820 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001821 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001822 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001823
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001824 return QualType(New, 0);
1825}
1826
1827/// getRValueReferenceType - Return the uniqued reference to the type for an
1828/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001829QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001830 // Unique pointers, to guarantee there is only one pointer of a particular
1831 // structure.
1832 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001833 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001834
1835 void *InsertPos = 0;
1836 if (RValueReferenceType *RT =
1837 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1838 return QualType(RT, 0);
1839
John McCallfc93cf92009-10-22 22:37:11 +00001840 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1841
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001842 // If the referencee type isn't canonical, this won't be a canonical type
1843 // either, so fill in the canonical type field.
1844 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001845 if (InnerRef || !T.isCanonical()) {
1846 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1847 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001848
1849 // Get the new insert position for the node we care about.
1850 RValueReferenceType *NewIP =
1851 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001852 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001853 }
1854
John McCall90d1c2d2009-09-24 23:30:46 +00001855 RValueReferenceType *New
1856 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001857 Types.push_back(New);
1858 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001859 return QualType(New, 0);
1860}
1861
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001862/// getMemberPointerType - Return the uniqued reference to the type for a
1863/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001864QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001865 // Unique pointers, to guarantee there is only one pointer of a particular
1866 // structure.
1867 llvm::FoldingSetNodeID ID;
1868 MemberPointerType::Profile(ID, T, Cls);
1869
1870 void *InsertPos = 0;
1871 if (MemberPointerType *PT =
1872 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1873 return QualType(PT, 0);
1874
1875 // If the pointee or class type isn't canonical, this won't be a canonical
1876 // type either, so fill in the canonical type field.
1877 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001878 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001879 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1880
1881 // Get the new insert position for the node we care about.
1882 MemberPointerType *NewIP =
1883 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001884 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001885 }
John McCall90d1c2d2009-09-24 23:30:46 +00001886 MemberPointerType *New
1887 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001888 Types.push_back(New);
1889 MemberPointerTypes.InsertNode(New, InsertPos);
1890 return QualType(New, 0);
1891}
1892
Mike Stump11289f42009-09-09 15:08:12 +00001893/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001894/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001895QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001896 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001897 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001898 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001899 assert((EltTy->isDependentType() ||
1900 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001901 "Constant array of VLAs is illegal!");
1902
Chris Lattnere2df3f92009-05-13 04:12:56 +00001903 // Convert the array size into a canonical width matching the pointer size for
1904 // the target.
1905 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001906 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001907 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00001908
Chris Lattner23b7eb62007-06-15 23:05:46 +00001909 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001910 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001911
Chris Lattner36f8e652007-01-27 08:31:04 +00001912 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001913 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001914 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001915 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001916
John McCall33ddac02011-01-19 10:06:00 +00001917 // If the element type isn't canonical or has qualifiers, this won't
1918 // be a canonical type either, so fill in the canonical type field.
1919 QualType Canon;
1920 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1921 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00001922 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001923 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00001924 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001925
Chris Lattner36f8e652007-01-27 08:31:04 +00001926 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001927 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001928 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001929 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001930 }
Mike Stump11289f42009-09-09 15:08:12 +00001931
John McCall90d1c2d2009-09-24 23:30:46 +00001932 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001933 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001934 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001935 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001936 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001937}
1938
John McCall06549462011-01-18 08:40:38 +00001939/// getVariableArrayDecayedType - Turns the given type, which may be
1940/// variably-modified, into the corresponding type with all the known
1941/// sizes replaced with [*].
1942QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1943 // Vastly most common case.
1944 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001945
John McCall06549462011-01-18 08:40:38 +00001946 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001947
John McCall06549462011-01-18 08:40:38 +00001948 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00001949 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00001950 switch (ty->getTypeClass()) {
1951#define TYPE(Class, Base)
1952#define ABSTRACT_TYPE(Class, Base)
1953#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1954#include "clang/AST/TypeNodes.def"
1955 llvm_unreachable("didn't desugar past all non-canonical types?");
1956
1957 // These types should never be variably-modified.
1958 case Type::Builtin:
1959 case Type::Complex:
1960 case Type::Vector:
1961 case Type::ExtVector:
1962 case Type::DependentSizedExtVector:
1963 case Type::ObjCObject:
1964 case Type::ObjCInterface:
1965 case Type::ObjCObjectPointer:
1966 case Type::Record:
1967 case Type::Enum:
1968 case Type::UnresolvedUsing:
1969 case Type::TypeOfExpr:
1970 case Type::TypeOf:
1971 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00001972 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00001973 case Type::DependentName:
1974 case Type::InjectedClassName:
1975 case Type::TemplateSpecialization:
1976 case Type::DependentTemplateSpecialization:
1977 case Type::TemplateTypeParm:
1978 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00001979 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00001980 case Type::PackExpansion:
1981 llvm_unreachable("type should never be variably-modified");
1982
1983 // These types can be variably-modified but should never need to
1984 // further decay.
1985 case Type::FunctionNoProto:
1986 case Type::FunctionProto:
1987 case Type::BlockPointer:
1988 case Type::MemberPointer:
1989 return type;
1990
1991 // These types can be variably-modified. All these modifications
1992 // preserve structure except as noted by comments.
1993 // TODO: if we ever care about optimizing VLAs, there are no-op
1994 // optimizations available here.
1995 case Type::Pointer:
1996 result = getPointerType(getVariableArrayDecayedType(
1997 cast<PointerType>(ty)->getPointeeType()));
1998 break;
1999
2000 case Type::LValueReference: {
2001 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2002 result = getLValueReferenceType(
2003 getVariableArrayDecayedType(lv->getPointeeType()),
2004 lv->isSpelledAsLValue());
2005 break;
2006 }
2007
2008 case Type::RValueReference: {
2009 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2010 result = getRValueReferenceType(
2011 getVariableArrayDecayedType(lv->getPointeeType()));
2012 break;
2013 }
2014
Eli Friedman0dfb8892011-10-06 23:00:33 +00002015 case Type::Atomic: {
2016 const AtomicType *at = cast<AtomicType>(ty);
2017 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2018 break;
2019 }
2020
John McCall06549462011-01-18 08:40:38 +00002021 case Type::ConstantArray: {
2022 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2023 result = getConstantArrayType(
2024 getVariableArrayDecayedType(cat->getElementType()),
2025 cat->getSize(),
2026 cat->getSizeModifier(),
2027 cat->getIndexTypeCVRQualifiers());
2028 break;
2029 }
2030
2031 case Type::DependentSizedArray: {
2032 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2033 result = getDependentSizedArrayType(
2034 getVariableArrayDecayedType(dat->getElementType()),
2035 dat->getSizeExpr(),
2036 dat->getSizeModifier(),
2037 dat->getIndexTypeCVRQualifiers(),
2038 dat->getBracketsRange());
2039 break;
2040 }
2041
2042 // Turn incomplete types into [*] types.
2043 case Type::IncompleteArray: {
2044 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2045 result = getVariableArrayType(
2046 getVariableArrayDecayedType(iat->getElementType()),
2047 /*size*/ 0,
2048 ArrayType::Normal,
2049 iat->getIndexTypeCVRQualifiers(),
2050 SourceRange());
2051 break;
2052 }
2053
2054 // Turn VLA types into [*] types.
2055 case Type::VariableArray: {
2056 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2057 result = getVariableArrayType(
2058 getVariableArrayDecayedType(vat->getElementType()),
2059 /*size*/ 0,
2060 ArrayType::Star,
2061 vat->getIndexTypeCVRQualifiers(),
2062 vat->getBracketsRange());
2063 break;
2064 }
2065 }
2066
2067 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002068 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002069}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002070
Steve Naroffcadebd02007-08-30 18:14:25 +00002071/// getVariableArrayType - Returns a non-unique reference to the type for a
2072/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002073QualType ASTContext::getVariableArrayType(QualType EltTy,
2074 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002075 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002076 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002077 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002078 // Since we don't unique expressions, it isn't possible to unique VLA's
2079 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002080 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002081
John McCall33ddac02011-01-19 10:06:00 +00002082 // Be sure to pull qualifiers off the element type.
2083 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2084 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002085 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002086 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002087 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002088 }
2089
John McCall90d1c2d2009-09-24 23:30:46 +00002090 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002091 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002092
2093 VariableArrayTypes.push_back(New);
2094 Types.push_back(New);
2095 return QualType(New, 0);
2096}
2097
Douglas Gregor4619e432008-12-05 23:32:09 +00002098/// getDependentSizedArrayType - Returns a non-unique reference to
2099/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002100/// type.
John McCall33ddac02011-01-19 10:06:00 +00002101QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2102 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002103 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002104 unsigned elementTypeQuals,
2105 SourceRange brackets) const {
2106 assert((!numElements || numElements->isTypeDependent() ||
2107 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002108 "Size must be type- or value-dependent!");
2109
John McCall33ddac02011-01-19 10:06:00 +00002110 // Dependently-sized array types that do not have a specified number
2111 // of elements will have their sizes deduced from a dependent
2112 // initializer. We do no canonicalization here at all, which is okay
2113 // because they can't be used in most locations.
2114 if (!numElements) {
2115 DependentSizedArrayType *newType
2116 = new (*this, TypeAlignment)
2117 DependentSizedArrayType(*this, elementType, QualType(),
2118 numElements, ASM, elementTypeQuals,
2119 brackets);
2120 Types.push_back(newType);
2121 return QualType(newType, 0);
2122 }
2123
2124 // Otherwise, we actually build a new type every time, but we
2125 // also build a canonical type.
2126
2127 SplitQualType canonElementType = getCanonicalType(elementType).split();
2128
2129 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002130 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002131 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002132 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002133 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002134
John McCall33ddac02011-01-19 10:06:00 +00002135 // Look for an existing type with these properties.
2136 DependentSizedArrayType *canonTy =
2137 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002138
John McCall33ddac02011-01-19 10:06:00 +00002139 // If we don't have one, build one.
2140 if (!canonTy) {
2141 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002142 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002143 QualType(), numElements, ASM, elementTypeQuals,
2144 brackets);
2145 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2146 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002147 }
2148
John McCall33ddac02011-01-19 10:06:00 +00002149 // Apply qualifiers from the element type to the array.
2150 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002151 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002152
John McCall33ddac02011-01-19 10:06:00 +00002153 // If we didn't need extra canonicalization for the element type,
2154 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002155 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002156 return canon;
2157
2158 // Otherwise, we need to build a type which follows the spelling
2159 // of the element type.
2160 DependentSizedArrayType *sugaredType
2161 = new (*this, TypeAlignment)
2162 DependentSizedArrayType(*this, elementType, canon, numElements,
2163 ASM, elementTypeQuals, brackets);
2164 Types.push_back(sugaredType);
2165 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002166}
2167
John McCall33ddac02011-01-19 10:06:00 +00002168QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002169 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002170 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002171 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002172 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002173
John McCall33ddac02011-01-19 10:06:00 +00002174 void *insertPos = 0;
2175 if (IncompleteArrayType *iat =
2176 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2177 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002178
2179 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002180 // either, so fill in the canonical type field. We also have to pull
2181 // qualifiers off the element type.
2182 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002183
John McCall33ddac02011-01-19 10:06:00 +00002184 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2185 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002186 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002187 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002188 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002189
2190 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002191 IncompleteArrayType *existing =
2192 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2193 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002194 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002195
John McCall33ddac02011-01-19 10:06:00 +00002196 IncompleteArrayType *newType = new (*this, TypeAlignment)
2197 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002198
John McCall33ddac02011-01-19 10:06:00 +00002199 IncompleteArrayTypes.InsertNode(newType, insertPos);
2200 Types.push_back(newType);
2201 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002202}
2203
Steve Naroff91fcddb2007-07-18 18:00:27 +00002204/// getVectorType - Return the unique reference to a vector type of
2205/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002206QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002207 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002208 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002209
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002210 // Check if we've already instantiated a vector of this type.
2211 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002212 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002213
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002214 void *InsertPos = 0;
2215 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2216 return QualType(VTP, 0);
2217
2218 // If the element type isn't canonical, this won't be a canonical type either,
2219 // so fill in the canonical type field.
2220 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002221 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002222 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002223
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002224 // Get the new insert position for the node we care about.
2225 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002226 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002227 }
John McCall90d1c2d2009-09-24 23:30:46 +00002228 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002229 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002230 VectorTypes.InsertNode(New, InsertPos);
2231 Types.push_back(New);
2232 return QualType(New, 0);
2233}
2234
Nate Begemance4d7fc2008-04-18 23:10:10 +00002235/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002236/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002237QualType
2238ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002239 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002240
Steve Naroff91fcddb2007-07-18 18:00:27 +00002241 // Check if we've already instantiated a vector of this type.
2242 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002243 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002244 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002245 void *InsertPos = 0;
2246 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2247 return QualType(VTP, 0);
2248
2249 // If the element type isn't canonical, this won't be a canonical type either,
2250 // so fill in the canonical type field.
2251 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002252 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002253 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002254
Steve Naroff91fcddb2007-07-18 18:00:27 +00002255 // Get the new insert position for the node we care about.
2256 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002257 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002258 }
John McCall90d1c2d2009-09-24 23:30:46 +00002259 ExtVectorType *New = new (*this, TypeAlignment)
2260 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002261 VectorTypes.InsertNode(New, InsertPos);
2262 Types.push_back(New);
2263 return QualType(New, 0);
2264}
2265
Jay Foad39c79802011-01-12 09:06:06 +00002266QualType
2267ASTContext::getDependentSizedExtVectorType(QualType vecType,
2268 Expr *SizeExpr,
2269 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002270 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002271 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002272 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002273
Douglas Gregor352169a2009-07-31 03:54:25 +00002274 void *InsertPos = 0;
2275 DependentSizedExtVectorType *Canon
2276 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2277 DependentSizedExtVectorType *New;
2278 if (Canon) {
2279 // We already have a canonical version of this array type; use it as
2280 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002281 New = new (*this, TypeAlignment)
2282 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2283 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002284 } else {
2285 QualType CanonVecTy = getCanonicalType(vecType);
2286 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002287 New = new (*this, TypeAlignment)
2288 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2289 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002290
2291 DependentSizedExtVectorType *CanonCheck
2292 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2293 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2294 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002295 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2296 } else {
2297 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2298 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002299 New = new (*this, TypeAlignment)
2300 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002301 }
2302 }
Mike Stump11289f42009-09-09 15:08:12 +00002303
Douglas Gregor758a8692009-06-17 21:51:59 +00002304 Types.push_back(New);
2305 return QualType(New, 0);
2306}
2307
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002308/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002309///
Jay Foad39c79802011-01-12 09:06:06 +00002310QualType
2311ASTContext::getFunctionNoProtoType(QualType ResultTy,
2312 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002313 const CallingConv DefaultCC = Info.getCC();
2314 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2315 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002316 // Unique functions, to guarantee there is only one function of a particular
2317 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002318 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002319 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002320
Chris Lattner47955de2007-01-27 08:37:20 +00002321 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002322 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002323 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002324 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002325
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002326 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002327 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002328 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002329 Canonical =
2330 getFunctionNoProtoType(getCanonicalType(ResultTy),
2331 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002332
Chris Lattner47955de2007-01-27 08:37:20 +00002333 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002334 FunctionNoProtoType *NewIP =
2335 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002336 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002337 }
Mike Stump11289f42009-09-09 15:08:12 +00002338
Roman Divacky65b88cd2011-03-01 17:40:53 +00002339 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002340 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002341 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002342 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002343 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002344 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002345}
2346
2347/// getFunctionType - Return a normal function type with a typed argument
2348/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002349QualType
2350ASTContext::getFunctionType(QualType ResultTy,
2351 const QualType *ArgArray, unsigned NumArgs,
2352 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002353 // Unique functions, to guarantee there is only one function of a particular
2354 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002355 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002356 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002357
2358 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002359 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002360 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002361 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002362
2363 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002364 bool isCanonical =
2365 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2366 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002367 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002368 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002369 isCanonical = false;
2370
Roman Divacky65b88cd2011-03-01 17:40:53 +00002371 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2372 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2373 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002374
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002375 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002376 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002377 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002378 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002379 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002380 CanonicalArgs.reserve(NumArgs);
2381 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002382 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002383
John McCalldb40c7f2010-12-14 08:05:40 +00002384 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002385 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002386 CanonicalEPI.ExceptionSpecType = EST_None;
2387 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002388 CanonicalEPI.ExtInfo
2389 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2390
Chris Lattner76a00cf2008-04-06 22:59:24 +00002391 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002392 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002393 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002394
Chris Lattnerfd4de792007-01-27 01:15:32 +00002395 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002396 FunctionProtoType *NewIP =
2397 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002398 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002399 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002400
John McCall31168b02011-06-15 23:02:42 +00002401 // FunctionProtoType objects are allocated with extra bytes after
2402 // them for three variable size arrays at the end:
2403 // - parameter types
2404 // - exception types
2405 // - consumed-arguments flags
2406 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002407 // expression, or information used to resolve the exception
2408 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002409 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002410 NumArgs * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002411 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002412 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002413 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002414 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002415 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002416 Size += 2 * sizeof(FunctionDecl*);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002417 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2418 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002419 }
John McCall31168b02011-06-15 23:02:42 +00002420 if (EPI.ConsumedArguments)
2421 Size += NumArgs * sizeof(bool);
2422
John McCalldb40c7f2010-12-14 08:05:40 +00002423 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002424 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2425 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002426 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002427 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002428 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002429 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002430}
Chris Lattneref51c202006-11-10 07:17:23 +00002431
John McCalle78aac42010-03-10 03:28:59 +00002432#ifndef NDEBUG
2433static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2434 if (!isa<CXXRecordDecl>(D)) return false;
2435 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2436 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2437 return true;
2438 if (RD->getDescribedClassTemplate() &&
2439 !isa<ClassTemplateSpecializationDecl>(RD))
2440 return true;
2441 return false;
2442}
2443#endif
2444
2445/// getInjectedClassNameType - Return the unique reference to the
2446/// injected class name type for the specified templated declaration.
2447QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002448 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002449 assert(NeedsInjectedClassNameType(Decl));
2450 if (Decl->TypeForDecl) {
2451 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002452 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002453 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2454 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2455 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2456 } else {
John McCall424cec92011-01-19 06:33:43 +00002457 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002458 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002459 Decl->TypeForDecl = newType;
2460 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002461 }
2462 return QualType(Decl->TypeForDecl, 0);
2463}
2464
Douglas Gregor83a586e2008-04-13 21:07:44 +00002465/// getTypeDeclType - Return the unique reference to the type for the
2466/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002467QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002468 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002469 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002470
Richard Smithdda56e42011-04-15 14:24:37 +00002471 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002472 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002473
John McCall96f0b5f2010-03-10 06:48:02 +00002474 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2475 "Template type parameter types are always available.");
2476
John McCall81e38502010-02-16 03:57:14 +00002477 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002478 assert(!Record->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002479 "struct/union has previous declaration");
2480 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002481 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002482 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002483 assert(!Enum->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002484 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002485 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002486 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002487 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002488 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2489 Decl->TypeForDecl = newType;
2490 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002491 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002492 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002493
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002494 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002495}
2496
Chris Lattner32d920b2007-01-26 02:01:53 +00002497/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002498/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002499QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002500ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2501 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002502 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002503
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002504 if (Canonical.isNull())
2505 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002506 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002507 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002508 Decl->TypeForDecl = newType;
2509 Types.push_back(newType);
2510 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002511}
2512
Jay Foad39c79802011-01-12 09:06:06 +00002513QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002514 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2515
Douglas Gregorec9fd132012-01-14 16:38:05 +00002516 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002517 if (PrevDecl->TypeForDecl)
2518 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2519
John McCall424cec92011-01-19 06:33:43 +00002520 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2521 Decl->TypeForDecl = newType;
2522 Types.push_back(newType);
2523 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002524}
2525
Jay Foad39c79802011-01-12 09:06:06 +00002526QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002527 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2528
Douglas Gregorec9fd132012-01-14 16:38:05 +00002529 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002530 if (PrevDecl->TypeForDecl)
2531 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2532
John McCall424cec92011-01-19 06:33:43 +00002533 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2534 Decl->TypeForDecl = newType;
2535 Types.push_back(newType);
2536 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002537}
2538
John McCall81904512011-01-06 01:58:22 +00002539QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2540 QualType modifiedType,
2541 QualType equivalentType) {
2542 llvm::FoldingSetNodeID id;
2543 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2544
2545 void *insertPos = 0;
2546 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2547 if (type) return QualType(type, 0);
2548
2549 QualType canon = getCanonicalType(equivalentType);
2550 type = new (*this, TypeAlignment)
2551 AttributedType(canon, attrKind, modifiedType, equivalentType);
2552
2553 Types.push_back(type);
2554 AttributedTypes.InsertNode(type, insertPos);
2555
2556 return QualType(type, 0);
2557}
2558
2559
John McCallcebee162009-10-18 09:09:24 +00002560/// \brief Retrieve a substitution-result type.
2561QualType
2562ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002563 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002564 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002565 && "replacement types must always be canonical");
2566
2567 llvm::FoldingSetNodeID ID;
2568 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2569 void *InsertPos = 0;
2570 SubstTemplateTypeParmType *SubstParm
2571 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2572
2573 if (!SubstParm) {
2574 SubstParm = new (*this, TypeAlignment)
2575 SubstTemplateTypeParmType(Parm, Replacement);
2576 Types.push_back(SubstParm);
2577 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2578 }
2579
2580 return QualType(SubstParm, 0);
2581}
2582
Douglas Gregorada4b792011-01-14 02:55:32 +00002583/// \brief Retrieve a
2584QualType ASTContext::getSubstTemplateTypeParmPackType(
2585 const TemplateTypeParmType *Parm,
2586 const TemplateArgument &ArgPack) {
2587#ifndef NDEBUG
2588 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2589 PEnd = ArgPack.pack_end();
2590 P != PEnd; ++P) {
2591 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2592 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2593 }
2594#endif
2595
2596 llvm::FoldingSetNodeID ID;
2597 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2598 void *InsertPos = 0;
2599 if (SubstTemplateTypeParmPackType *SubstParm
2600 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2601 return QualType(SubstParm, 0);
2602
2603 QualType Canon;
2604 if (!Parm->isCanonicalUnqualified()) {
2605 Canon = getCanonicalType(QualType(Parm, 0));
2606 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2607 ArgPack);
2608 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2609 }
2610
2611 SubstTemplateTypeParmPackType *SubstParm
2612 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2613 ArgPack);
2614 Types.push_back(SubstParm);
2615 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2616 return QualType(SubstParm, 0);
2617}
2618
Douglas Gregoreff93e02009-02-05 23:33:38 +00002619/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002620/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002621/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002622QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002623 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002624 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002625 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002626 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002627 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002628 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002629 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2630
2631 if (TypeParm)
2632 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002633
Chandler Carruth08836322011-05-01 00:51:33 +00002634 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002635 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002636 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002637
2638 TemplateTypeParmType *TypeCheck
2639 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2640 assert(!TypeCheck && "Template type parameter canonical type broken");
2641 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002642 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002643 TypeParm = new (*this, TypeAlignment)
2644 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002645
2646 Types.push_back(TypeParm);
2647 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2648
2649 return QualType(TypeParm, 0);
2650}
2651
John McCalle78aac42010-03-10 03:28:59 +00002652TypeSourceInfo *
2653ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2654 SourceLocation NameLoc,
2655 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002656 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002657 assert(!Name.getAsDependentTemplateName() &&
2658 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002659 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002660
2661 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2662 TemplateSpecializationTypeLoc TL
2663 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002664 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00002665 TL.setTemplateNameLoc(NameLoc);
2666 TL.setLAngleLoc(Args.getLAngleLoc());
2667 TL.setRAngleLoc(Args.getRAngleLoc());
2668 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2669 TL.setArgLocInfo(i, Args[i].getLocInfo());
2670 return DI;
2671}
2672
Mike Stump11289f42009-09-09 15:08:12 +00002673QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002674ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002675 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002676 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002677 assert(!Template.getAsDependentTemplateName() &&
2678 "No dependent template names here!");
2679
John McCall6b51f282009-11-23 01:53:49 +00002680 unsigned NumArgs = Args.size();
2681
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002682 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002683 ArgVec.reserve(NumArgs);
2684 for (unsigned i = 0; i != NumArgs; ++i)
2685 ArgVec.push_back(Args[i].getArgument());
2686
John McCall2408e322010-04-27 00:57:59 +00002687 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002688 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002689}
2690
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002691#ifndef NDEBUG
2692static bool hasAnyPackExpansions(const TemplateArgument *Args,
2693 unsigned NumArgs) {
2694 for (unsigned I = 0; I != NumArgs; ++I)
2695 if (Args[I].isPackExpansion())
2696 return true;
2697
2698 return true;
2699}
2700#endif
2701
John McCall0ad16662009-10-29 08:12:44 +00002702QualType
2703ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002704 const TemplateArgument *Args,
2705 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002706 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002707 assert(!Template.getAsDependentTemplateName() &&
2708 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002709 // Look through qualified template names.
2710 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2711 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002712
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002713 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00002714 Template.getAsTemplateDecl() &&
2715 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00002716 QualType CanonType;
2717 if (!Underlying.isNull())
2718 CanonType = getCanonicalType(Underlying);
2719 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002720 // We can get here with an alias template when the specialization contains
2721 // a pack expansion that does not match up with a parameter pack.
2722 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2723 "Caller must compute aliased type");
2724 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00002725 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2726 NumArgs);
2727 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002728
Douglas Gregora8e02e72009-07-28 23:00:59 +00002729 // Allocate the (non-canonical) template specialization type, but don't
2730 // try to unique it: these types typically have location information that
2731 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002732 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2733 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002734 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002735 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002736 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002737 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2738 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002739
Douglas Gregor8bf42052009-02-09 18:46:07 +00002740 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002741 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002742}
2743
Mike Stump11289f42009-09-09 15:08:12 +00002744QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002745ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2746 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002747 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002748 assert(!Template.getAsDependentTemplateName() &&
2749 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002750
Douglas Gregore29139c2011-03-03 17:04:51 +00002751 // Look through qualified template names.
2752 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2753 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002754
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002755 // Build the canonical template specialization type.
2756 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002757 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002758 CanonArgs.reserve(NumArgs);
2759 for (unsigned I = 0; I != NumArgs; ++I)
2760 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2761
2762 // Determine whether this canonical template specialization type already
2763 // exists.
2764 llvm::FoldingSetNodeID ID;
2765 TemplateSpecializationType::Profile(ID, CanonTemplate,
2766 CanonArgs.data(), NumArgs, *this);
2767
2768 void *InsertPos = 0;
2769 TemplateSpecializationType *Spec
2770 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2771
2772 if (!Spec) {
2773 // Allocate a new canonical template specialization type.
2774 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2775 sizeof(TemplateArgument) * NumArgs),
2776 TypeAlignment);
2777 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2778 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002779 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002780 Types.push_back(Spec);
2781 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2782 }
2783
2784 assert(Spec->isDependentType() &&
2785 "Non-dependent template-id type must have a canonical type");
2786 return QualType(Spec, 0);
2787}
2788
2789QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002790ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2791 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002792 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002793 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002794 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002795
2796 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002797 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002798 if (T)
2799 return QualType(T, 0);
2800
Douglas Gregorc42075a2010-02-04 18:10:26 +00002801 QualType Canon = NamedType;
2802 if (!Canon.isCanonical()) {
2803 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002804 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2805 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002806 (void)CheckT;
2807 }
2808
Abramo Bagnara6150c882010-05-11 21:36:43 +00002809 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002810 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002811 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002812 return QualType(T, 0);
2813}
2814
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002815QualType
Jay Foad39c79802011-01-12 09:06:06 +00002816ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002817 llvm::FoldingSetNodeID ID;
2818 ParenType::Profile(ID, InnerType);
2819
2820 void *InsertPos = 0;
2821 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2822 if (T)
2823 return QualType(T, 0);
2824
2825 QualType Canon = InnerType;
2826 if (!Canon.isCanonical()) {
2827 Canon = getCanonicalType(InnerType);
2828 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2829 assert(!CheckT && "Paren canonical type broken");
2830 (void)CheckT;
2831 }
2832
2833 T = new (*this) ParenType(InnerType, Canon);
2834 Types.push_back(T);
2835 ParenTypes.InsertNode(T, InsertPos);
2836 return QualType(T, 0);
2837}
2838
Douglas Gregor02085352010-03-31 20:19:30 +00002839QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2840 NestedNameSpecifier *NNS,
2841 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002842 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002843 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2844
2845 if (Canon.isNull()) {
2846 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002847 ElaboratedTypeKeyword CanonKeyword = Keyword;
2848 if (Keyword == ETK_None)
2849 CanonKeyword = ETK_Typename;
2850
2851 if (CanonNNS != NNS || CanonKeyword != Keyword)
2852 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002853 }
2854
2855 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002856 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002857
2858 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002859 DependentNameType *T
2860 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002861 if (T)
2862 return QualType(T, 0);
2863
Douglas Gregor02085352010-03-31 20:19:30 +00002864 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002865 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002866 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002867 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002868}
2869
Mike Stump11289f42009-09-09 15:08:12 +00002870QualType
John McCallc392f372010-06-11 00:33:02 +00002871ASTContext::getDependentTemplateSpecializationType(
2872 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002873 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002874 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002875 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002876 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002877 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00002878 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2879 ArgCopy.push_back(Args[I].getArgument());
2880 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2881 ArgCopy.size(),
2882 ArgCopy.data());
2883}
2884
2885QualType
2886ASTContext::getDependentTemplateSpecializationType(
2887 ElaboratedTypeKeyword Keyword,
2888 NestedNameSpecifier *NNS,
2889 const IdentifierInfo *Name,
2890 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002891 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00002892 assert((!NNS || NNS->isDependent()) &&
2893 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00002894
Douglas Gregorc42075a2010-02-04 18:10:26 +00002895 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002896 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2897 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002898
2899 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002900 DependentTemplateSpecializationType *T
2901 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002902 if (T)
2903 return QualType(T, 0);
2904
John McCallc392f372010-06-11 00:33:02 +00002905 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002906
John McCallc392f372010-06-11 00:33:02 +00002907 ElaboratedTypeKeyword CanonKeyword = Keyword;
2908 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2909
2910 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002911 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00002912 for (unsigned I = 0; I != NumArgs; ++I) {
2913 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2914 if (!CanonArgs[I].structurallyEquals(Args[I]))
2915 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002916 }
2917
John McCallc392f372010-06-11 00:33:02 +00002918 QualType Canon;
2919 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2920 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2921 Name, NumArgs,
2922 CanonArgs.data());
2923
2924 // Find the insert position again.
2925 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2926 }
2927
2928 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2929 sizeof(TemplateArgument) * NumArgs),
2930 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002931 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002932 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002933 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002934 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002935 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002936}
2937
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002938QualType ASTContext::getPackExpansionType(QualType Pattern,
2939 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002940 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002941 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002942
2943 assert(Pattern->containsUnexpandedParameterPack() &&
2944 "Pack expansions must expand one or more parameter packs");
2945 void *InsertPos = 0;
2946 PackExpansionType *T
2947 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2948 if (T)
2949 return QualType(T, 0);
2950
2951 QualType Canon;
2952 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00002953 Canon = getCanonicalType(Pattern);
2954 // The canonical type might not contain an unexpanded parameter pack, if it
2955 // contains an alias template specialization which ignores one of its
2956 // parameters.
2957 if (Canon->containsUnexpandedParameterPack()) {
2958 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002959
Richard Smith68eea502012-07-16 00:20:35 +00002960 // Find the insert position again, in case we inserted an element into
2961 // PackExpansionTypes and invalidated our insert position.
2962 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2963 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00002964 }
2965
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002966 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002967 Types.push_back(T);
2968 PackExpansionTypes.InsertNode(T, InsertPos);
2969 return QualType(T, 0);
2970}
2971
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002972/// CmpProtocolNames - Comparison predicate for sorting protocols
2973/// alphabetically.
2974static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2975 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002976 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002977}
2978
John McCall8b07ec22010-05-15 11:32:37 +00002979static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002980 unsigned NumProtocols) {
2981 if (NumProtocols == 0) return true;
2982
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002983 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
2984 return false;
2985
John McCallfc93cf92009-10-22 22:37:11 +00002986 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002987 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
2988 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00002989 return false;
2990 return true;
2991}
2992
2993static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002994 unsigned &NumProtocols) {
2995 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002996
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002997 // Sort protocols, keyed by name.
2998 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2999
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003000 // Canonicalize.
3001 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3002 Protocols[I] = Protocols[I]->getCanonicalDecl();
3003
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003004 // Remove duplicates.
3005 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3006 NumProtocols = ProtocolsEnd-Protocols;
3007}
3008
John McCall8b07ec22010-05-15 11:32:37 +00003009QualType ASTContext::getObjCObjectType(QualType BaseType,
3010 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003011 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003012 // If the base type is an interface and there aren't any protocols
3013 // to add, then the interface type will do just fine.
3014 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3015 return BaseType;
3016
3017 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003018 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003019 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00003020 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00003021 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3022 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003023
John McCall8b07ec22010-05-15 11:32:37 +00003024 // Build the canonical type, which has the canonical base type and
3025 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003026 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003027 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3028 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3029 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003030 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003031 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003032 unsigned UniqueCount = NumProtocols;
3033
John McCallfc93cf92009-10-22 22:37:11 +00003034 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003035 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3036 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003037 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003038 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3039 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003040 }
3041
3042 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003043 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3044 }
3045
3046 unsigned Size = sizeof(ObjCObjectTypeImpl);
3047 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3048 void *Mem = Allocate(Size, TypeAlignment);
3049 ObjCObjectTypeImpl *T =
3050 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3051
3052 Types.push_back(T);
3053 ObjCObjectTypes.InsertNode(T, InsertPos);
3054 return QualType(T, 0);
3055}
3056
3057/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3058/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003059QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003060 llvm::FoldingSetNodeID ID;
3061 ObjCObjectPointerType::Profile(ID, ObjectT);
3062
3063 void *InsertPos = 0;
3064 if (ObjCObjectPointerType *QT =
3065 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3066 return QualType(QT, 0);
3067
3068 // Find the canonical object type.
3069 QualType Canonical;
3070 if (!ObjectT.isCanonical()) {
3071 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3072
3073 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003074 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3075 }
3076
Douglas Gregorf85bee62010-02-08 22:59:26 +00003077 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003078 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3079 ObjCObjectPointerType *QType =
3080 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003081
Steve Narofffb4330f2009-06-17 22:40:22 +00003082 Types.push_back(QType);
3083 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003084 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003085}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003086
Douglas Gregor1c283312010-08-11 12:19:30 +00003087/// getObjCInterfaceType - Return the unique reference to the type for the
3088/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003089QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3090 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003091 if (Decl->TypeForDecl)
3092 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003093
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003094 if (PrevDecl) {
3095 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3096 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3097 return QualType(PrevDecl->TypeForDecl, 0);
3098 }
3099
Douglas Gregor7671e532011-12-16 16:34:57 +00003100 // Prefer the definition, if there is one.
3101 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3102 Decl = Def;
3103
Douglas Gregor1c283312010-08-11 12:19:30 +00003104 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3105 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3106 Decl->TypeForDecl = T;
3107 Types.push_back(T);
3108 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003109}
3110
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003111/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3112/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003113/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003114/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003115/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003116QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003117 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003118 if (tofExpr->isTypeDependent()) {
3119 llvm::FoldingSetNodeID ID;
3120 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003121
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003122 void *InsertPos = 0;
3123 DependentTypeOfExprType *Canon
3124 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3125 if (Canon) {
3126 // We already have a "canonical" version of an identical, dependent
3127 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003128 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003129 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003130 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003131 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003132 Canon
3133 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003134 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3135 toe = Canon;
3136 }
3137 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003138 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003139 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003140 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003141 Types.push_back(toe);
3142 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003143}
3144
Steve Naroffa773cd52007-08-01 18:02:17 +00003145/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3146/// TypeOfType AST's. The only motivation to unique these nodes would be
3147/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003148/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003149/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003150QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003151 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003152 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003153 Types.push_back(tot);
3154 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003155}
3156
Anders Carlssonad6bd352009-06-24 21:24:56 +00003157
Anders Carlsson81df7b82009-06-24 19:06:50 +00003158/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3159/// DecltypeType AST's. The only motivation to unique these nodes would be
3160/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003161/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003162/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003163QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003164 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003165
3166 // C++0x [temp.type]p2:
3167 // If an expression e involves a template parameter, decltype(e) denotes a
3168 // unique dependent type. Two such decltype-specifiers refer to the same
3169 // type only if their expressions are equivalent (14.5.6.1).
3170 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003171 llvm::FoldingSetNodeID ID;
3172 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003173
Douglas Gregora21f6c32009-07-30 23:36:40 +00003174 void *InsertPos = 0;
3175 DependentDecltypeType *Canon
3176 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3177 if (Canon) {
3178 // We already have a "canonical" version of an equivalent, dependent
3179 // decltype type. Use that as our canonical type.
Richard Smithef8bf432012-08-13 20:08:14 +00003180 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003181 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003182 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003183 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003184 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003185 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3186 dt = Canon;
3187 }
3188 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003189 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3190 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003191 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003192 Types.push_back(dt);
3193 return QualType(dt, 0);
3194}
3195
Alexis Hunte852b102011-05-24 22:41:36 +00003196/// getUnaryTransformationType - We don't unique these, since the memory
3197/// savings are minimal and these are rare.
3198QualType ASTContext::getUnaryTransformType(QualType BaseType,
3199 QualType UnderlyingType,
3200 UnaryTransformType::UTTKind Kind)
3201 const {
3202 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003203 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3204 Kind,
3205 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003206 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003207 Types.push_back(Ty);
3208 return QualType(Ty, 0);
3209}
3210
Richard Smithb2bc2e62011-02-21 20:05:19 +00003211/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003212QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00003213 void *InsertPos = 0;
3214 if (!DeducedType.isNull()) {
3215 // Look in the folding set for an existing type.
3216 llvm::FoldingSetNodeID ID;
3217 AutoType::Profile(ID, DeducedType);
3218 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3219 return QualType(AT, 0);
3220 }
3221
3222 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3223 Types.push_back(AT);
3224 if (InsertPos)
3225 AutoTypes.InsertNode(AT, InsertPos);
3226 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003227}
3228
Eli Friedman0dfb8892011-10-06 23:00:33 +00003229/// getAtomicType - Return the uniqued reference to the atomic type for
3230/// the given value type.
3231QualType ASTContext::getAtomicType(QualType T) const {
3232 // Unique pointers, to guarantee there is only one pointer of a particular
3233 // structure.
3234 llvm::FoldingSetNodeID ID;
3235 AtomicType::Profile(ID, T);
3236
3237 void *InsertPos = 0;
3238 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3239 return QualType(AT, 0);
3240
3241 // If the atomic value type isn't canonical, this won't be a canonical type
3242 // either, so fill in the canonical type field.
3243 QualType Canonical;
3244 if (!T.isCanonical()) {
3245 Canonical = getAtomicType(getCanonicalType(T));
3246
3247 // Get the new insert position for the node we care about.
3248 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3249 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3250 }
3251 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3252 Types.push_back(New);
3253 AtomicTypes.InsertNode(New, InsertPos);
3254 return QualType(New, 0);
3255}
3256
Richard Smith02e85f32011-04-14 22:09:26 +00003257/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3258QualType ASTContext::getAutoDeductType() const {
3259 if (AutoDeductTy.isNull())
3260 AutoDeductTy = getAutoType(QualType());
3261 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3262 return AutoDeductTy;
3263}
3264
3265/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3266QualType ASTContext::getAutoRRefDeductType() const {
3267 if (AutoRRefDeductTy.isNull())
3268 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3269 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3270 return AutoRRefDeductTy;
3271}
3272
Chris Lattnerfb072462007-01-23 05:45:31 +00003273/// getTagDeclType - Return the unique reference to the type for the
3274/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003275QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003276 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003277 // FIXME: What is the design on getTagDeclType when it requires casting
3278 // away const? mutable?
3279 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003280}
3281
Mike Stump11289f42009-09-09 15:08:12 +00003282/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3283/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3284/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003285CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003286 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003287}
Chris Lattnerfb072462007-01-23 05:45:31 +00003288
Hans Wennborg27541db2011-10-27 08:29:09 +00003289/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3290CanQualType ASTContext::getIntMaxType() const {
3291 return getFromTargetType(Target->getIntMaxType());
3292}
3293
3294/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3295CanQualType ASTContext::getUIntMaxType() const {
3296 return getFromTargetType(Target->getUIntMaxType());
3297}
3298
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003299/// getSignedWCharType - Return the type of "signed wchar_t".
3300/// Used when in C++, as a GCC extension.
3301QualType ASTContext::getSignedWCharType() const {
3302 // FIXME: derive from "Target" ?
3303 return WCharTy;
3304}
3305
3306/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3307/// Used when in C++, as a GCC extension.
3308QualType ASTContext::getUnsignedWCharType() const {
3309 // FIXME: derive from "Target" ?
3310 return UnsignedIntTy;
3311}
3312
Hans Wennborg27541db2011-10-27 08:29:09 +00003313/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003314/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3315QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003316 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003317}
3318
Chris Lattnera21ad802008-04-02 05:18:44 +00003319//===----------------------------------------------------------------------===//
3320// Type Operators
3321//===----------------------------------------------------------------------===//
3322
Jay Foad39c79802011-01-12 09:06:06 +00003323CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003324 // Push qualifiers into arrays, and then discard any remaining
3325 // qualifiers.
3326 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003327 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003328 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003329 QualType Result;
3330 if (isa<ArrayType>(Ty)) {
3331 Result = getArrayDecayedType(QualType(Ty,0));
3332 } else if (isa<FunctionType>(Ty)) {
3333 Result = getPointerType(QualType(Ty, 0));
3334 } else {
3335 Result = QualType(Ty, 0);
3336 }
3337
3338 return CanQualType::CreateUnsafe(Result);
3339}
3340
John McCall6c9dd522011-01-18 07:41:22 +00003341QualType ASTContext::getUnqualifiedArrayType(QualType type,
3342 Qualifiers &quals) {
3343 SplitQualType splitType = type.getSplitUnqualifiedType();
3344
3345 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3346 // the unqualified desugared type and then drops it on the floor.
3347 // We then have to strip that sugar back off with
3348 // getUnqualifiedDesugaredType(), which is silly.
3349 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003350 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003351
3352 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003353 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003354 quals = splitType.Quals;
3355 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003356 }
3357
John McCall6c9dd522011-01-18 07:41:22 +00003358 // Otherwise, recurse on the array's element type.
3359 QualType elementType = AT->getElementType();
3360 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3361
3362 // If that didn't change the element type, AT has no qualifiers, so we
3363 // can just use the results in splitType.
3364 if (elementType == unqualElementType) {
3365 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003366 quals = splitType.Quals;
3367 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003368 }
3369
3370 // Otherwise, add in the qualifiers from the outermost type, then
3371 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003372 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003373
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003374 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003375 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003376 CAT->getSizeModifier(), 0);
3377 }
3378
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003379 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003380 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003381 }
3382
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003383 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003384 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003385 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003386 VAT->getSizeModifier(),
3387 VAT->getIndexTypeCVRQualifiers(),
3388 VAT->getBracketsRange());
3389 }
3390
3391 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003392 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003393 DSAT->getSizeModifier(), 0,
3394 SourceRange());
3395}
3396
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003397/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3398/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3399/// they point to and return true. If T1 and T2 aren't pointer types
3400/// or pointer-to-member types, or if they are not similar at this
3401/// level, returns false and leaves T1 and T2 unchanged. Top-level
3402/// qualifiers on T1 and T2 are ignored. This function will typically
3403/// be called in a loop that successively "unwraps" pointer and
3404/// pointer-to-member types to compare them at each level.
3405bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3406 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3407 *T2PtrType = T2->getAs<PointerType>();
3408 if (T1PtrType && T2PtrType) {
3409 T1 = T1PtrType->getPointeeType();
3410 T2 = T2PtrType->getPointeeType();
3411 return true;
3412 }
3413
3414 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3415 *T2MPType = T2->getAs<MemberPointerType>();
3416 if (T1MPType && T2MPType &&
3417 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3418 QualType(T2MPType->getClass(), 0))) {
3419 T1 = T1MPType->getPointeeType();
3420 T2 = T2MPType->getPointeeType();
3421 return true;
3422 }
3423
David Blaikiebbafb8a2012-03-11 07:00:24 +00003424 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003425 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3426 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3427 if (T1OPType && T2OPType) {
3428 T1 = T1OPType->getPointeeType();
3429 T2 = T2OPType->getPointeeType();
3430 return true;
3431 }
3432 }
3433
3434 // FIXME: Block pointers, too?
3435
3436 return false;
3437}
3438
Jay Foad39c79802011-01-12 09:06:06 +00003439DeclarationNameInfo
3440ASTContext::getNameForTemplate(TemplateName Name,
3441 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003442 switch (Name.getKind()) {
3443 case TemplateName::QualifiedTemplate:
3444 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003445 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003446 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3447 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003448
John McCalld9dfe3a2011-06-30 08:33:18 +00003449 case TemplateName::OverloadedTemplate: {
3450 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3451 // DNInfo work in progress: CHECKME: what about DNLoc?
3452 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3453 }
3454
3455 case TemplateName::DependentTemplate: {
3456 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003457 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003458 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003459 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3460 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003461 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003462 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3463 // DNInfo work in progress: FIXME: source locations?
3464 DeclarationNameLoc DNLoc;
3465 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3466 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3467 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003468 }
3469 }
3470
John McCalld9dfe3a2011-06-30 08:33:18 +00003471 case TemplateName::SubstTemplateTemplateParm: {
3472 SubstTemplateTemplateParmStorage *subst
3473 = Name.getAsSubstTemplateTemplateParm();
3474 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3475 NameLoc);
3476 }
3477
3478 case TemplateName::SubstTemplateTemplateParmPack: {
3479 SubstTemplateTemplateParmPackStorage *subst
3480 = Name.getAsSubstTemplateTemplateParmPack();
3481 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3482 NameLoc);
3483 }
3484 }
3485
3486 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003487}
3488
Jay Foad39c79802011-01-12 09:06:06 +00003489TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003490 switch (Name.getKind()) {
3491 case TemplateName::QualifiedTemplate:
3492 case TemplateName::Template: {
3493 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003494 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003495 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003496 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3497
3498 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003499 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003500 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003501
John McCalld9dfe3a2011-06-30 08:33:18 +00003502 case TemplateName::OverloadedTemplate:
3503 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003504
John McCalld9dfe3a2011-06-30 08:33:18 +00003505 case TemplateName::DependentTemplate: {
3506 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3507 assert(DTN && "Non-dependent template names must refer to template decls.");
3508 return DTN->CanonicalTemplateName;
3509 }
3510
3511 case TemplateName::SubstTemplateTemplateParm: {
3512 SubstTemplateTemplateParmStorage *subst
3513 = Name.getAsSubstTemplateTemplateParm();
3514 return getCanonicalTemplateName(subst->getReplacement());
3515 }
3516
3517 case TemplateName::SubstTemplateTemplateParmPack: {
3518 SubstTemplateTemplateParmPackStorage *subst
3519 = Name.getAsSubstTemplateTemplateParmPack();
3520 TemplateTemplateParmDecl *canonParameter
3521 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3522 TemplateArgument canonArgPack
3523 = getCanonicalTemplateArgument(subst->getArgumentPack());
3524 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3525 }
3526 }
3527
3528 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003529}
3530
Douglas Gregoradee3e32009-11-11 23:06:43 +00003531bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3532 X = getCanonicalTemplateName(X);
3533 Y = getCanonicalTemplateName(Y);
3534 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3535}
3536
Mike Stump11289f42009-09-09 15:08:12 +00003537TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003538ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003539 switch (Arg.getKind()) {
3540 case TemplateArgument::Null:
3541 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003542
Douglas Gregora8e02e72009-07-28 23:00:59 +00003543 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003544 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003545
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003546 case TemplateArgument::Declaration: {
3547 if (Decl *D = Arg.getAsDecl())
3548 return TemplateArgument(D->getCanonicalDecl());
3549 return TemplateArgument((Decl*)0);
3550 }
Mike Stump11289f42009-09-09 15:08:12 +00003551
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003552 case TemplateArgument::Template:
3553 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003554
3555 case TemplateArgument::TemplateExpansion:
3556 return TemplateArgument(getCanonicalTemplateName(
3557 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003558 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003559
Douglas Gregora8e02e72009-07-28 23:00:59 +00003560 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00003561 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003562
Douglas Gregora8e02e72009-07-28 23:00:59 +00003563 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003564 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003565
Douglas Gregora8e02e72009-07-28 23:00:59 +00003566 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003567 if (Arg.pack_size() == 0)
3568 return Arg;
3569
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003570 TemplateArgument *CanonArgs
3571 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003572 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003573 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003574 AEnd = Arg.pack_end();
3575 A != AEnd; (void)++A, ++Idx)
3576 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003577
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003578 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003579 }
3580 }
3581
3582 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003583 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003584}
3585
Douglas Gregor333489b2009-03-27 23:10:48 +00003586NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003587ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003588 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003589 return 0;
3590
3591 switch (NNS->getKind()) {
3592 case NestedNameSpecifier::Identifier:
3593 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003594 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003595 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3596 NNS->getAsIdentifier());
3597
3598 case NestedNameSpecifier::Namespace:
3599 // A namespace is canonical; build a nested-name-specifier with
3600 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003601 return NestedNameSpecifier::Create(*this, 0,
3602 NNS->getAsNamespace()->getOriginalNamespace());
3603
3604 case NestedNameSpecifier::NamespaceAlias:
3605 // A namespace is canonical; build a nested-name-specifier with
3606 // this namespace and no prefix.
3607 return NestedNameSpecifier::Create(*this, 0,
3608 NNS->getAsNamespaceAlias()->getNamespace()
3609 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003610
3611 case NestedNameSpecifier::TypeSpec:
3612 case NestedNameSpecifier::TypeSpecWithTemplate: {
3613 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003614
3615 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3616 // break it apart into its prefix and identifier, then reconsititute those
3617 // as the canonical nested-name-specifier. This is required to canonicalize
3618 // a dependent nested-name-specifier involving typedefs of dependent-name
3619 // types, e.g.,
3620 // typedef typename T::type T1;
3621 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00003622 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3623 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00003624 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003625
Eli Friedman5358a0a2012-03-03 04:09:56 +00003626 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3627 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3628 // first place?
John McCall33ddac02011-01-19 10:06:00 +00003629 return NestedNameSpecifier::Create(*this, 0, false,
3630 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003631 }
3632
3633 case NestedNameSpecifier::Global:
3634 // The global specifier is canonical and unique.
3635 return NNS;
3636 }
3637
David Blaikie8a40f702012-01-17 06:56:22 +00003638 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00003639}
3640
Chris Lattner7adf0762008-08-04 07:31:14 +00003641
Jay Foad39c79802011-01-12 09:06:06 +00003642const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003643 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003644 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003645 // Handle the common positive case fast.
3646 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3647 return AT;
3648 }
Mike Stump11289f42009-09-09 15:08:12 +00003649
John McCall8ccfcb52009-09-24 19:53:00 +00003650 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003651 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003652 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003653
John McCall8ccfcb52009-09-24 19:53:00 +00003654 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003655 // implements C99 6.7.3p8: "If the specification of an array type includes
3656 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003657
Chris Lattner7adf0762008-08-04 07:31:14 +00003658 // If we get here, we either have type qualifiers on the type, or we have
3659 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003660 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003661
John McCall33ddac02011-01-19 10:06:00 +00003662 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003663 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00003664
Chris Lattner7adf0762008-08-04 07:31:14 +00003665 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00003666 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00003667 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003668 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003669
Chris Lattner7adf0762008-08-04 07:31:14 +00003670 // Otherwise, we have an array and we have qualifiers on it. Push the
3671 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003672 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003673
Chris Lattner7adf0762008-08-04 07:31:14 +00003674 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3675 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3676 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003677 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003678 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3679 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3680 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003681 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003682
Mike Stump11289f42009-09-09 15:08:12 +00003683 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003684 = dyn_cast<DependentSizedArrayType>(ATy))
3685 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003686 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003687 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003688 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003689 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003690 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003691
Chris Lattner7adf0762008-08-04 07:31:14 +00003692 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003693 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003694 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003695 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003696 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003697 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003698}
3699
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003700QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003701 // C99 6.7.5.3p7:
3702 // A declaration of a parameter as "array of type" shall be
3703 // adjusted to "qualified pointer to type", where the type
3704 // qualifiers (if any) are those specified within the [ and ] of
3705 // the array type derivation.
3706 if (T->isArrayType())
3707 return getArrayDecayedType(T);
3708
3709 // C99 6.7.5.3p8:
3710 // A declaration of a parameter as "function returning type"
3711 // shall be adjusted to "pointer to function returning type", as
3712 // in 6.3.2.1.
3713 if (T->isFunctionType())
3714 return getPointerType(T);
3715
3716 return T;
3717}
3718
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003719QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003720 T = getVariableArrayDecayedType(T);
3721 T = getAdjustedParameterType(T);
3722 return T.getUnqualifiedType();
3723}
3724
Chris Lattnera21ad802008-04-02 05:18:44 +00003725/// getArrayDecayedType - Return the properly qualified result of decaying the
3726/// specified array type to a pointer. This operation is non-trivial when
3727/// handling typedefs etc. The canonical type of "T" must be an array type,
3728/// this returns a pointer to a properly qualified element of the array.
3729///
3730/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003731QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003732 // Get the element type with 'getAsArrayType' so that we don't lose any
3733 // typedefs in the element type of the array. This also handles propagation
3734 // of type qualifiers from the array type into the element type if present
3735 // (C99 6.7.3p8).
3736 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3737 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003738
Chris Lattner7adf0762008-08-04 07:31:14 +00003739 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003740
3741 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003742 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003743}
3744
John McCall33ddac02011-01-19 10:06:00 +00003745QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3746 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003747}
3748
John McCall33ddac02011-01-19 10:06:00 +00003749QualType ASTContext::getBaseElementType(QualType type) const {
3750 Qualifiers qs;
3751 while (true) {
3752 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003753 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00003754 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003755
John McCall33ddac02011-01-19 10:06:00 +00003756 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00003757 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003758 }
Mike Stump11289f42009-09-09 15:08:12 +00003759
John McCall33ddac02011-01-19 10:06:00 +00003760 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003761}
3762
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003763/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003764uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003765ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3766 uint64_t ElementCount = 1;
3767 do {
3768 ElementCount *= CA->getSize().getZExtValue();
3769 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3770 } while (CA);
3771 return ElementCount;
3772}
3773
Steve Naroff0af91202007-04-27 21:51:21 +00003774/// getFloatingRank - Return a relative rank for floating point types.
3775/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003776static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003777 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003778 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003779
John McCall9dd450b2009-09-21 23:43:11 +00003780 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3781 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003782 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003783 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00003784 case BuiltinType::Float: return FloatRank;
3785 case BuiltinType::Double: return DoubleRank;
3786 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003787 }
3788}
3789
Mike Stump11289f42009-09-09 15:08:12 +00003790/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3791/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003792/// 'typeDomain' is a real floating point or complex type.
3793/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003794QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3795 QualType Domain) const {
3796 FloatingRank EltRank = getFloatingRank(Size);
3797 if (Domain->isComplexType()) {
3798 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003799 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00003800 case FloatRank: return FloatComplexTy;
3801 case DoubleRank: return DoubleComplexTy;
3802 case LongDoubleRank: return LongDoubleComplexTy;
3803 }
Steve Naroff0af91202007-04-27 21:51:21 +00003804 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003805
3806 assert(Domain->isRealFloatingType() && "Unknown domain!");
3807 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003808 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003809 case FloatRank: return FloatTy;
3810 case DoubleRank: return DoubleTy;
3811 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003812 }
David Blaikief47fa302012-01-17 02:30:50 +00003813 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00003814}
3815
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003816/// getFloatingTypeOrder - Compare the rank of the two specified floating
3817/// point types, ignoring the domain of the type (i.e. 'double' ==
3818/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003819/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003820int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003821 FloatingRank LHSR = getFloatingRank(LHS);
3822 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003823
Chris Lattnerb90739d2008-04-06 23:38:49 +00003824 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003825 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003826 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003827 return 1;
3828 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003829}
3830
Chris Lattner76a00cf2008-04-06 22:59:24 +00003831/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3832/// routine will assert if passed a built-in type that isn't an integer or enum,
3833/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003834unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003835 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003836
Chris Lattner76a00cf2008-04-06 22:59:24 +00003837 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003838 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003839 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003840 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003841 case BuiltinType::Char_S:
3842 case BuiltinType::Char_U:
3843 case BuiltinType::SChar:
3844 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003845 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003846 case BuiltinType::Short:
3847 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003848 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003849 case BuiltinType::Int:
3850 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003851 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003852 case BuiltinType::Long:
3853 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003854 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003855 case BuiltinType::LongLong:
3856 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003857 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003858 case BuiltinType::Int128:
3859 case BuiltinType::UInt128:
3860 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003861 }
3862}
3863
Eli Friedman629ffb92009-08-20 04:21:42 +00003864/// \brief Whether this is a promotable bitfield reference according
3865/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3866///
3867/// \returns the type this bit-field will promote to, or NULL if no
3868/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003869QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003870 if (E->isTypeDependent() || E->isValueDependent())
3871 return QualType();
3872
Eli Friedman629ffb92009-08-20 04:21:42 +00003873 FieldDecl *Field = E->getBitField();
3874 if (!Field)
3875 return QualType();
3876
3877 QualType FT = Field->getType();
3878
Richard Smithcaf33902011-10-10 18:28:20 +00003879 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00003880 uint64_t IntSize = getTypeSize(IntTy);
3881 // GCC extension compatibility: if the bit-field size is less than or equal
3882 // to the size of int, it gets promoted no matter what its type is.
3883 // For instance, unsigned long bf : 4 gets promoted to signed int.
3884 if (BitWidth < IntSize)
3885 return IntTy;
3886
3887 if (BitWidth == IntSize)
3888 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3889
3890 // Types bigger than int are not subject to promotions, and therefore act
3891 // like the base type.
3892 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3893 // is ridiculous.
3894 return QualType();
3895}
3896
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003897/// getPromotedIntegerType - Returns the type that Promotable will
3898/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3899/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003900QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003901 assert(!Promotable.isNull());
3902 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003903 if (const EnumType *ET = Promotable->getAs<EnumType>())
3904 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00003905
3906 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3907 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3908 // (3.9.1) can be converted to a prvalue of the first of the following
3909 // types that can represent all the values of its underlying type:
3910 // int, unsigned int, long int, unsigned long int, long long int, or
3911 // unsigned long long int [...]
3912 // FIXME: Is there some better way to compute this?
3913 if (BT->getKind() == BuiltinType::WChar_S ||
3914 BT->getKind() == BuiltinType::WChar_U ||
3915 BT->getKind() == BuiltinType::Char16 ||
3916 BT->getKind() == BuiltinType::Char32) {
3917 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3918 uint64_t FromSize = getTypeSize(BT);
3919 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3920 LongLongTy, UnsignedLongLongTy };
3921 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3922 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3923 if (FromSize < ToSize ||
3924 (FromSize == ToSize &&
3925 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3926 return PromoteTypes[Idx];
3927 }
3928 llvm_unreachable("char type should fit into long long");
3929 }
3930 }
3931
3932 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003933 if (Promotable->isSignedIntegerType())
3934 return IntTy;
3935 uint64_t PromotableSize = getTypeSize(Promotable);
3936 uint64_t IntSize = getTypeSize(IntTy);
3937 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3938 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3939}
3940
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003941/// \brief Recurses in pointer/array types until it finds an objc retainable
3942/// type and returns its ownership.
3943Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3944 while (!T.isNull()) {
3945 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3946 return T.getObjCLifetime();
3947 if (T->isArrayType())
3948 T = getBaseElementType(T);
3949 else if (const PointerType *PT = T->getAs<PointerType>())
3950 T = PT->getPointeeType();
3951 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00003952 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003953 else
3954 break;
3955 }
3956
3957 return Qualifiers::OCL_None;
3958}
3959
Mike Stump11289f42009-09-09 15:08:12 +00003960/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003961/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003962/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003963int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00003964 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3965 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003966 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003967
Chris Lattner76a00cf2008-04-06 22:59:24 +00003968 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3969 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003970
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003971 unsigned LHSRank = getIntegerRank(LHSC);
3972 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003973
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003974 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3975 if (LHSRank == RHSRank) return 0;
3976 return LHSRank > RHSRank ? 1 : -1;
3977 }
Mike Stump11289f42009-09-09 15:08:12 +00003978
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003979 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3980 if (LHSUnsigned) {
3981 // If the unsigned [LHS] type is larger, return it.
3982 if (LHSRank >= RHSRank)
3983 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003984
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003985 // If the signed type can represent all values of the unsigned type, it
3986 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003987 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003988 return -1;
3989 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003990
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003991 // If the unsigned [RHS] type is larger, return it.
3992 if (RHSRank >= LHSRank)
3993 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003994
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003995 // If the signed type can represent all values of the unsigned type, it
3996 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003997 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003998 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003999}
Anders Carlsson98f07902007-08-17 05:31:46 +00004000
Anders Carlsson6d417272009-11-14 21:45:58 +00004001static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004002CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4003 DeclContext *DC, IdentifierInfo *Id) {
4004 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004005 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004006 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004007 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004008 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004009}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004010
Mike Stump11289f42009-09-09 15:08:12 +00004011// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004012QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004013 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00004014 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004015 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004016 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00004017 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004018
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004019 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004020
Anders Carlsson98f07902007-08-17 05:31:46 +00004021 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004022 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004023 // int flags;
4024 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004025 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004026 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004027 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004028 FieldTypes[3] = LongTy;
4029
Anders Carlsson98f07902007-08-17 05:31:46 +00004030 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004031 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004032 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004033 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004034 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00004035 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00004036 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004037 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004038 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004039 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004040 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004041 }
4042
Douglas Gregord5058122010-02-11 01:19:42 +00004043 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004044 }
Mike Stump11289f42009-09-09 15:08:12 +00004045
Anders Carlsson98f07902007-08-17 05:31:46 +00004046 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004047}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004048
Douglas Gregor512b0772009-04-23 22:29:11 +00004049void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004050 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004051 assert(Rec && "Invalid CFConstantStringType");
4052 CFConstantStringTypeDecl = Rec->getDecl();
4053}
4054
Jay Foad39c79802011-01-12 09:06:06 +00004055QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004056 if (BlockDescriptorType)
4057 return getTagDeclType(BlockDescriptorType);
4058
4059 RecordDecl *T;
4060 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004061 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004062 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00004063 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004064
4065 QualType FieldTypes[] = {
4066 UnsignedLongTy,
4067 UnsignedLongTy,
4068 };
4069
4070 const char *FieldNames[] = {
4071 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004072 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004073 };
4074
4075 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004076 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00004077 SourceLocation(),
4078 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004079 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00004080 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004081 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004082 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004083 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00004084 T->addDecl(Field);
4085 }
4086
Douglas Gregord5058122010-02-11 01:19:42 +00004087 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004088
4089 BlockDescriptorType = T;
4090
4091 return getTagDeclType(BlockDescriptorType);
4092}
4093
Jay Foad39c79802011-01-12 09:06:06 +00004094QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004095 if (BlockDescriptorExtendedType)
4096 return getTagDeclType(BlockDescriptorExtendedType);
4097
4098 RecordDecl *T;
4099 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004100 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004101 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00004102 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004103
4104 QualType FieldTypes[] = {
4105 UnsignedLongTy,
4106 UnsignedLongTy,
4107 getPointerType(VoidPtrTy),
4108 getPointerType(VoidPtrTy)
4109 };
4110
4111 const char *FieldNames[] = {
4112 "reserved",
4113 "Size",
4114 "CopyFuncPtr",
4115 "DestroyFuncPtr"
4116 };
4117
4118 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004119 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004120 SourceLocation(),
4121 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004122 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004123 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004124 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004125 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004126 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004127 T->addDecl(Field);
4128 }
4129
Douglas Gregord5058122010-02-11 01:19:42 +00004130 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004131
4132 BlockDescriptorExtendedType = T;
4133
4134 return getTagDeclType(BlockDescriptorExtendedType);
4135}
4136
Jay Foad39c79802011-01-12 09:06:06 +00004137bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCall31168b02011-06-15 23:02:42 +00004138 if (Ty->isObjCRetainableType())
Mike Stump94967902009-10-21 18:16:27 +00004139 return true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004140 if (getLangOpts().CPlusPlus) {
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004141 if (const RecordType *RT = Ty->getAs<RecordType>()) {
4142 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntfcaeae42011-05-25 20:50:04 +00004143 return RD->hasConstCopyConstructor();
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004144
4145 }
4146 }
Mike Stump94967902009-10-21 18:16:27 +00004147 return false;
4148}
4149
Jay Foad39c79802011-01-12 09:06:06 +00004150QualType
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004151ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00004152 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00004153 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00004154 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00004155 // unsigned int __flags;
4156 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00004157 // void *__copy_helper; // as needed
4158 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00004159 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00004160 // } *
4161
Mike Stump94967902009-10-21 18:16:27 +00004162 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
4163
4164 // FIXME: Move up
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004165 SmallString<36> Name;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00004166 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
4167 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00004168 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004169 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00004170 T->startDefinition();
4171 QualType Int32Ty = IntTy;
4172 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
4173 QualType FieldTypes[] = {
4174 getPointerType(VoidPtrTy),
4175 getPointerType(getTagDeclType(T)),
4176 Int32Ty,
4177 Int32Ty,
4178 getPointerType(VoidPtrTy),
4179 getPointerType(VoidPtrTy),
4180 Ty
4181 };
4182
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004183 StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00004184 "__isa",
4185 "__forwarding",
4186 "__flags",
4187 "__size",
4188 "__copy_helper",
4189 "__destroy_helper",
4190 DeclName,
4191 };
4192
4193 for (size_t i = 0; i < 7; ++i) {
4194 if (!HasCopyAndDispose && i >=4 && i <= 5)
4195 continue;
4196 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00004197 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00004198 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004199 FieldTypes[i], /*TInfo=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004200 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004201 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004202 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00004203 T->addDecl(Field);
4204 }
4205
Douglas Gregord5058122010-02-11 01:19:42 +00004206 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00004207
4208 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00004209}
4210
Douglas Gregorbab8a962011-09-08 01:46:34 +00004211TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4212 if (!ObjCInstanceTypeDecl)
4213 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4214 getTranslationUnitDecl(),
4215 SourceLocation(),
4216 SourceLocation(),
4217 &Idents.get("instancetype"),
4218 getTrivialTypeSourceInfo(getObjCIdType()));
4219 return ObjCInstanceTypeDecl;
4220}
4221
Anders Carlsson18acd442007-10-29 06:33:42 +00004222// This returns true if a type has been typedefed to BOOL:
4223// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004224static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004225 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004226 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4227 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004228
Anders Carlssond8499822007-10-29 05:01:08 +00004229 return false;
4230}
4231
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004232/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004233/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004234CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004235 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4236 return CharUnits::Zero();
4237
Ken Dyck40775002010-01-11 17:06:35 +00004238 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004239
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004240 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004241 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004242 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004243 // Treat arrays as pointers, since that's how they're passed in.
4244 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004245 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004246 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004247}
4248
4249static inline
4250std::string charUnitsToString(const CharUnits &CU) {
4251 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004252}
4253
John McCall351762c2011-02-07 10:33:21 +00004254/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004255/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004256std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4257 std::string S;
4258
David Chisnall950a9512009-11-17 19:33:30 +00004259 const BlockDecl *Decl = Expr->getBlockDecl();
4260 QualType BlockTy =
4261 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4262 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00004263 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004264 // Compute size of all parameters.
4265 // Start with computing size of a pointer in number of bytes.
4266 // FIXME: There might(should) be a better way of doing this computation!
4267 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004268 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4269 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004270 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004271 E = Decl->param_end(); PI != E; ++PI) {
4272 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004273 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004274 if (sz.isZero())
4275 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004276 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004277 ParmOffset += sz;
4278 }
4279 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004280 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004281 // Block pointer and offset.
4282 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004283
4284 // Argument types.
4285 ParmOffset = PtrSize;
4286 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4287 Decl->param_end(); PI != E; ++PI) {
4288 ParmVarDecl *PVDecl = *PI;
4289 QualType PType = PVDecl->getOriginalType();
4290 if (const ArrayType *AT =
4291 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4292 // Use array's original type only if it has known number of
4293 // elements.
4294 if (!isa<ConstantArrayType>(AT))
4295 PType = PVDecl->getType();
4296 } else if (PType->isFunctionType())
4297 PType = PVDecl->getType();
4298 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004299 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004300 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004301 }
John McCall351762c2011-02-07 10:33:21 +00004302
4303 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004304}
4305
Douglas Gregora9d84932011-05-27 01:19:52 +00004306bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004307 std::string& S) {
4308 // Encode result type.
4309 getObjCEncodingForType(Decl->getResultType(), S);
4310 CharUnits ParmOffset;
4311 // Compute size of all parameters.
4312 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4313 E = Decl->param_end(); PI != E; ++PI) {
4314 QualType PType = (*PI)->getType();
4315 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004316 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004317 continue;
4318
David Chisnall50e4eba2010-12-30 14:05:53 +00004319 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004320 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004321 ParmOffset += sz;
4322 }
4323 S += charUnitsToString(ParmOffset);
4324 ParmOffset = CharUnits::Zero();
4325
4326 // Argument types.
4327 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4328 E = Decl->param_end(); PI != E; ++PI) {
4329 ParmVarDecl *PVDecl = *PI;
4330 QualType PType = PVDecl->getOriginalType();
4331 if (const ArrayType *AT =
4332 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4333 // Use array's original type only if it has known number of
4334 // elements.
4335 if (!isa<ConstantArrayType>(AT))
4336 PType = PVDecl->getType();
4337 } else if (PType->isFunctionType())
4338 PType = PVDecl->getType();
4339 getObjCEncodingForType(PType, S);
4340 S += charUnitsToString(ParmOffset);
4341 ParmOffset += getObjCEncodingTypeSize(PType);
4342 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004343
4344 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004345}
4346
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004347/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4348/// method parameter or return type. If Extended, include class names and
4349/// block object types.
4350void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4351 QualType T, std::string& S,
4352 bool Extended) const {
4353 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4354 getObjCEncodingForTypeQualifier(QT, S);
4355 // Encode parameter type.
4356 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4357 true /*OutermostType*/,
4358 false /*EncodingProperty*/,
4359 false /*StructField*/,
4360 Extended /*EncodeBlockParameters*/,
4361 Extended /*EncodeClassNames*/);
4362}
4363
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004364/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004365/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004366bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004367 std::string& S,
4368 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004369 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004370 // Encode return type.
4371 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4372 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004373 // Compute size of all parameters.
4374 // Start with computing size of a pointer in number of bytes.
4375 // FIXME: There might(should) be a better way of doing this computation!
4376 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004377 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004378 // The first two arguments (self and _cmd) are pointers; account for
4379 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004380 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004381 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004382 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004383 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004384 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004385 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004386 continue;
4387
Ken Dyck40775002010-01-11 17:06:35 +00004388 assert (sz.isPositive() &&
4389 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004390 ParmOffset += sz;
4391 }
Ken Dyck40775002010-01-11 17:06:35 +00004392 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004393 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004394 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004395
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004396 // Argument types.
4397 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004398 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004399 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004400 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004401 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004402 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004403 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4404 // Use array's original type only if it has known number of
4405 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004406 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004407 PType = PVDecl->getType();
4408 } else if (PType->isFunctionType())
4409 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004410 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4411 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004412 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004413 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004414 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004415
4416 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004417}
4418
Daniel Dunbar4932b362008-08-28 04:38:10 +00004419/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004420/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004421/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4422/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004423/// Property attributes are stored as a comma-delimited C string. The simple
4424/// attributes readonly and bycopy are encoded as single characters. The
4425/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4426/// encoded as single characters, followed by an identifier. Property types
4427/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004428/// these attributes are defined by the following enumeration:
4429/// @code
4430/// enum PropertyAttributes {
4431/// kPropertyReadOnly = 'R', // property is read-only.
4432/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4433/// kPropertyByref = '&', // property is a reference to the value last assigned
4434/// kPropertyDynamic = 'D', // property is dynamic
4435/// kPropertyGetter = 'G', // followed by getter selector name
4436/// kPropertySetter = 'S', // followed by setter selector name
4437/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004438/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004439/// kPropertyWeak = 'W' // 'weak' property
4440/// kPropertyStrong = 'P' // property GC'able
4441/// kPropertyNonAtomic = 'N' // property non-atomic
4442/// };
4443/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004444void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004445 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004446 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004447 // Collect information from the property implementation decl(s).
4448 bool Dynamic = false;
4449 ObjCPropertyImplDecl *SynthesizePID = 0;
4450
4451 // FIXME: Duplicated code due to poor abstraction.
4452 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004453 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004454 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4455 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004456 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004457 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004458 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004459 if (PID->getPropertyDecl() == PD) {
4460 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4461 Dynamic = true;
4462 } else {
4463 SynthesizePID = PID;
4464 }
4465 }
4466 }
4467 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004468 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004469 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004470 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004471 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004472 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004473 if (PID->getPropertyDecl() == PD) {
4474 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4475 Dynamic = true;
4476 } else {
4477 SynthesizePID = PID;
4478 }
4479 }
Mike Stump11289f42009-09-09 15:08:12 +00004480 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004481 }
4482 }
4483
4484 // FIXME: This is not very efficient.
4485 S = "T";
4486
4487 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004488 // GCC has some special rules regarding encoding of properties which
4489 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004490 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004491 true /* outermost type */,
4492 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004493
4494 if (PD->isReadOnly()) {
4495 S += ",R";
4496 } else {
4497 switch (PD->getSetterKind()) {
4498 case ObjCPropertyDecl::Assign: break;
4499 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004500 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004501 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004502 }
4503 }
4504
4505 // It really isn't clear at all what this means, since properties
4506 // are "dynamic by default".
4507 if (Dynamic)
4508 S += ",D";
4509
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004510 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4511 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004512
Daniel Dunbar4932b362008-08-28 04:38:10 +00004513 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4514 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004515 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004516 }
4517
4518 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4519 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004520 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004521 }
4522
4523 if (SynthesizePID) {
4524 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4525 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004526 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004527 }
4528
4529 // FIXME: OBJCGC: weak & strong
4530}
4531
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004532/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004533/// Another legacy compatibility encoding: 32-bit longs are encoded as
4534/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004535/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4536///
4537void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004538 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004539 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004540 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004541 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004542 else
Jay Foad39c79802011-01-12 09:06:06 +00004543 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004544 PointeeTy = IntTy;
4545 }
4546 }
4547}
4548
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004549void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004550 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004551 // We follow the behavior of gcc, expanding structures which are
4552 // directly pointed to, and expanding embedded structures. Note that
4553 // these rules are sufficient to prevent recursive encoding of the
4554 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004555 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004556 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004557}
4558
David Chisnallb190a2c2010-06-04 01:10:52 +00004559static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4560 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004561 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnallb190a2c2010-06-04 01:10:52 +00004562 case BuiltinType::Void: return 'v';
4563 case BuiltinType::Bool: return 'B';
4564 case BuiltinType::Char_U:
4565 case BuiltinType::UChar: return 'C';
4566 case BuiltinType::UShort: return 'S';
4567 case BuiltinType::UInt: return 'I';
4568 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004569 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004570 case BuiltinType::UInt128: return 'T';
4571 case BuiltinType::ULongLong: return 'Q';
4572 case BuiltinType::Char_S:
4573 case BuiltinType::SChar: return 'c';
4574 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004575 case BuiltinType::WChar_S:
4576 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004577 case BuiltinType::Int: return 'i';
4578 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004579 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004580 case BuiltinType::LongLong: return 'q';
4581 case BuiltinType::Int128: return 't';
4582 case BuiltinType::Float: return 'f';
4583 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004584 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004585 }
4586}
4587
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004588static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4589 EnumDecl *Enum = ET->getDecl();
4590
4591 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4592 if (!Enum->isFixed())
4593 return 'i';
4594
4595 // The encoding of a fixed enum type matches its fixed underlying type.
4596 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4597}
4598
Jay Foad39c79802011-01-12 09:06:06 +00004599static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004600 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00004601 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004602 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004603 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4604 // The GNU runtime requires more information; bitfields are encoded as b,
4605 // then the offset (in bits) of the first element, then the type of the
4606 // bitfield, then the size in bits. For example, in this structure:
4607 //
4608 // struct
4609 // {
4610 // int integer;
4611 // int flags:2;
4612 // };
4613 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4614 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4615 // information is not especially sensible, but we're stuck with it for
4616 // compatibility with GCC, although providing it breaks anything that
4617 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00004618 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004619 const RecordDecl *RD = FD->getParent();
4620 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004621 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004622 if (const EnumType *ET = T->getAs<EnumType>())
4623 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnall6f0a7d22010-12-26 20:12:30 +00004624 else
Jay Foad39c79802011-01-12 09:06:06 +00004625 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004626 }
Richard Smithcaf33902011-10-10 18:28:20 +00004627 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004628}
4629
Daniel Dunbar07d07852009-10-18 21:17:35 +00004630// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004631void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4632 bool ExpandPointedToStructures,
4633 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004634 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004635 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004636 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004637 bool StructField,
4638 bool EncodeBlockParameters,
4639 bool EncodeClassNames) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004640 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004641 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004642 return EncodeBitField(this, S, T, FD);
4643 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004644 return;
4645 }
Mike Stump11289f42009-09-09 15:08:12 +00004646
John McCall9dd450b2009-09-21 23:43:11 +00004647 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004648 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004649 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004650 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004651 return;
4652 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004653
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004654 // encoding for pointer or r3eference types.
4655 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004656 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004657 if (PT->isObjCSelType()) {
4658 S += ':';
4659 return;
4660 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004661 PointeeTy = PT->getPointeeType();
4662 }
4663 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4664 PointeeTy = RT->getPointeeType();
4665 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004666 bool isReadOnly = false;
4667 // For historical/compatibility reasons, the read-only qualifier of the
4668 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4669 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004670 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004671 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004672 if (OutermostType && T.isConstQualified()) {
4673 isReadOnly = true;
4674 S += 'r';
4675 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004676 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004677 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004678 while (P->getAs<PointerType>())
4679 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004680 if (P.isConstQualified()) {
4681 isReadOnly = true;
4682 S += 'r';
4683 }
4684 }
4685 if (isReadOnly) {
4686 // Another legacy compatibility encoding. Some ObjC qualifier and type
4687 // combinations need to be rearranged.
4688 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004689 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004690 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004691 }
Mike Stump11289f42009-09-09 15:08:12 +00004692
Anders Carlssond8499822007-10-29 05:01:08 +00004693 if (PointeeTy->isCharType()) {
4694 // char pointer types should be encoded as '*' unless it is a
4695 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004696 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004697 S += '*';
4698 return;
4699 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004700 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004701 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4702 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4703 S += '#';
4704 return;
4705 }
4706 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4707 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4708 S += '@';
4709 return;
4710 }
4711 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004712 }
Anders Carlssond8499822007-10-29 05:01:08 +00004713 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004714 getLegacyIntegralTypeEncoding(PointeeTy);
4715
Mike Stump11289f42009-09-09 15:08:12 +00004716 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004717 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004718 return;
4719 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004720
Chris Lattnere7cabb92009-07-13 00:10:46 +00004721 if (const ArrayType *AT =
4722 // Ignore type qualifiers etc.
4723 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004724 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004725 // Incomplete arrays are encoded as a pointer to the array element.
4726 S += '^';
4727
Mike Stump11289f42009-09-09 15:08:12 +00004728 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004729 false, ExpandStructures, FD);
4730 } else {
4731 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004732
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004733 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4734 if (getTypeSize(CAT->getElementType()) == 0)
4735 S += '0';
4736 else
4737 S += llvm::utostr(CAT->getSize().getZExtValue());
4738 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004739 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004740 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4741 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00004742 S += '0';
4743 }
Mike Stump11289f42009-09-09 15:08:12 +00004744
4745 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004746 false, ExpandStructures, FD);
4747 S += ']';
4748 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004749 return;
4750 }
Mike Stump11289f42009-09-09 15:08:12 +00004751
John McCall9dd450b2009-09-21 23:43:11 +00004752 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004753 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004754 return;
4755 }
Mike Stump11289f42009-09-09 15:08:12 +00004756
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004757 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004758 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004759 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004760 // Anonymous structures print as '?'
4761 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4762 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004763 if (ClassTemplateSpecializationDecl *Spec
4764 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4765 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4766 std::string TemplateArgsStr
4767 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004768 TemplateArgs.data(),
4769 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00004770 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004771
4772 S += TemplateArgsStr;
4773 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004774 } else {
4775 S += '?';
4776 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004777 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004778 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004779 if (!RDecl->isUnion()) {
4780 getObjCEncodingForStructureImpl(RDecl, S, FD);
4781 } else {
4782 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4783 FieldEnd = RDecl->field_end();
4784 Field != FieldEnd; ++Field) {
4785 if (FD) {
4786 S += '"';
4787 S += Field->getNameAsString();
4788 S += '"';
4789 }
Mike Stump11289f42009-09-09 15:08:12 +00004790
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004791 // Special case bit-fields.
4792 if (Field->isBitField()) {
4793 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00004794 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004795 } else {
4796 QualType qt = Field->getType();
4797 getLegacyIntegralTypeEncoding(qt);
4798 getObjCEncodingForTypeImpl(qt, S, false, true,
4799 FD, /*OutermostType*/false,
4800 /*EncodingProperty*/false,
4801 /*StructField*/true);
4802 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004803 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004804 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004805 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004806 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004807 return;
4808 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004809
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004810 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004811 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004812 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004813 else
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004814 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004815 return;
4816 }
Mike Stump11289f42009-09-09 15:08:12 +00004817
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004818 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004819 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004820 if (EncodeBlockParameters) {
4821 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4822
4823 S += '<';
4824 // Block return type
4825 getObjCEncodingForTypeImpl(FT->getResultType(), S,
4826 ExpandPointedToStructures, ExpandStructures,
4827 FD,
4828 false /* OutermostType */,
4829 EncodingProperty,
4830 false /* StructField */,
4831 EncodeBlockParameters,
4832 EncodeClassNames);
4833 // Block self
4834 S += "@?";
4835 // Block parameters
4836 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4837 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4838 E = FPT->arg_type_end(); I && (I != E); ++I) {
4839 getObjCEncodingForTypeImpl(*I, S,
4840 ExpandPointedToStructures,
4841 ExpandStructures,
4842 FD,
4843 false /* OutermostType */,
4844 EncodingProperty,
4845 false /* StructField */,
4846 EncodeBlockParameters,
4847 EncodeClassNames);
4848 }
4849 }
4850 S += '>';
4851 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004852 return;
4853 }
Mike Stump11289f42009-09-09 15:08:12 +00004854
John McCall8b07ec22010-05-15 11:32:37 +00004855 // Ignore protocol qualifiers when mangling at this level.
4856 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4857 T = OT->getBaseType();
4858
John McCall8ccfcb52009-09-24 19:53:00 +00004859 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004860 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004861 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004862 S += '{';
4863 const IdentifierInfo *II = OI->getIdentifier();
4864 S += II->getName();
4865 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00004866 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004867 DeepCollectObjCIvars(OI, true, Ivars);
4868 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004869 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004870 if (Field->isBitField())
4871 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004872 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004873 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004874 }
4875 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004876 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004877 }
Mike Stump11289f42009-09-09 15:08:12 +00004878
John McCall9dd450b2009-09-21 23:43:11 +00004879 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004880 if (OPT->isObjCIdType()) {
4881 S += '@';
4882 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004883 }
Mike Stump11289f42009-09-09 15:08:12 +00004884
Steve Narofff0c86112009-10-28 22:03:49 +00004885 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4886 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4887 // Since this is a binary compatibility issue, need to consult with runtime
4888 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004889 S += '#';
4890 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004891 }
Mike Stump11289f42009-09-09 15:08:12 +00004892
Chris Lattnere7cabb92009-07-13 00:10:46 +00004893 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004894 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004895 ExpandPointedToStructures,
4896 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004897 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004898 // Note that we do extended encoding of protocol qualifer list
4899 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004900 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004901 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4902 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004903 S += '<';
4904 S += (*I)->getNameAsString();
4905 S += '>';
4906 }
4907 S += '"';
4908 }
4909 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004910 }
Mike Stump11289f42009-09-09 15:08:12 +00004911
Chris Lattnere7cabb92009-07-13 00:10:46 +00004912 QualType PointeeTy = OPT->getPointeeType();
4913 if (!EncodingProperty &&
4914 isa<TypedefType>(PointeeTy.getTypePtr())) {
4915 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004916 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004917 // {...};
4918 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004919 getObjCEncodingForTypeImpl(PointeeTy, S,
4920 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004921 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004922 return;
4923 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004924
4925 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004926 if (OPT->getInterfaceDecl() &&
4927 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004928 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004929 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004930 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4931 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004932 S += '<';
4933 S += (*I)->getNameAsString();
4934 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004935 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004936 S += '"';
4937 }
4938 return;
4939 }
Mike Stump11289f42009-09-09 15:08:12 +00004940
John McCalla9e6e8d2010-05-17 23:56:34 +00004941 // gcc just blithely ignores member pointers.
4942 // TODO: maybe there should be a mangling for these
4943 if (T->getAs<MemberPointerType>())
4944 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004945
4946 if (T->isVectorType()) {
4947 // This matches gcc's encoding, even though technically it is
4948 // insufficient.
4949 // FIXME. We should do a better job than gcc.
4950 return;
4951 }
4952
David Blaikie83d382b2011-09-23 05:06:16 +00004953 llvm_unreachable("@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004954}
4955
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004956void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4957 std::string &S,
4958 const FieldDecl *FD,
4959 bool includeVBases) const {
4960 assert(RDecl && "Expected non-null RecordDecl");
4961 assert(!RDecl->isUnion() && "Should not be called for unions");
4962 if (!RDecl->getDefinition())
4963 return;
4964
4965 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4966 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4967 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4968
4969 if (CXXRec) {
4970 for (CXXRecordDecl::base_class_iterator
4971 BI = CXXRec->bases_begin(),
4972 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4973 if (!BI->isVirtual()) {
4974 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004975 if (base->isEmpty())
4976 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00004977 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004978 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4979 std::make_pair(offs, base));
4980 }
4981 }
4982 }
4983
4984 unsigned i = 0;
4985 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4986 FieldEnd = RDecl->field_end();
4987 Field != FieldEnd; ++Field, ++i) {
4988 uint64_t offs = layout.getFieldOffset(i);
4989 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00004990 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004991 }
4992
4993 if (CXXRec && includeVBases) {
4994 for (CXXRecordDecl::base_class_iterator
4995 BI = CXXRec->vbases_begin(),
4996 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4997 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004998 if (base->isEmpty())
4999 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005000 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005001 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5002 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5003 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005004 }
5005 }
5006
5007 CharUnits size;
5008 if (CXXRec) {
5009 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5010 } else {
5011 size = layout.getSize();
5012 }
5013
5014 uint64_t CurOffs = 0;
5015 std::multimap<uint64_t, NamedDecl *>::iterator
5016 CurLayObj = FieldOrBaseOffsets.begin();
5017
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005018 if (CXXRec && CXXRec->isDynamicClass() &&
5019 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005020 if (FD) {
5021 S += "\"_vptr$";
5022 std::string recname = CXXRec->getNameAsString();
5023 if (recname.empty()) recname = "?";
5024 S += recname;
5025 S += '"';
5026 }
5027 S += "^^?";
5028 CurOffs += getTypeSize(VoidPtrTy);
5029 }
5030
5031 if (!RDecl->hasFlexibleArrayMember()) {
5032 // Mark the end of the structure.
5033 uint64_t offs = toBits(size);
5034 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5035 std::make_pair(offs, (NamedDecl*)0));
5036 }
5037
5038 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5039 assert(CurOffs <= CurLayObj->first);
5040
5041 if (CurOffs < CurLayObj->first) {
5042 uint64_t padding = CurLayObj->first - CurOffs;
5043 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5044 // packing/alignment of members is different that normal, in which case
5045 // the encoding will be out-of-sync with the real layout.
5046 // If the runtime switches to just consider the size of types without
5047 // taking into account alignment, we could make padding explicit in the
5048 // encoding (e.g. using arrays of chars). The encoding strings would be
5049 // longer then though.
5050 CurOffs += padding;
5051 }
5052
5053 NamedDecl *dcl = CurLayObj->second;
5054 if (dcl == 0)
5055 break; // reached end of structure.
5056
5057 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5058 // We expand the bases without their virtual bases since those are going
5059 // in the initial structure. Note that this differs from gcc which
5060 // expands virtual bases each time one is encountered in the hierarchy,
5061 // making the encoding type bigger than it really is.
5062 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005063 assert(!base->isEmpty());
5064 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005065 } else {
5066 FieldDecl *field = cast<FieldDecl>(dcl);
5067 if (FD) {
5068 S += '"';
5069 S += field->getNameAsString();
5070 S += '"';
5071 }
5072
5073 if (field->isBitField()) {
5074 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00005075 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005076 } else {
5077 QualType qt = field->getType();
5078 getLegacyIntegralTypeEncoding(qt);
5079 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5080 /*OutermostType*/false,
5081 /*EncodingProperty*/false,
5082 /*StructField*/true);
5083 CurOffs += getTypeSize(field->getType());
5084 }
5085 }
5086 }
5087}
5088
Mike Stump11289f42009-09-09 15:08:12 +00005089void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005090 std::string& S) const {
5091 if (QT & Decl::OBJC_TQ_In)
5092 S += 'n';
5093 if (QT & Decl::OBJC_TQ_Inout)
5094 S += 'N';
5095 if (QT & Decl::OBJC_TQ_Out)
5096 S += 'o';
5097 if (QT & Decl::OBJC_TQ_Bycopy)
5098 S += 'O';
5099 if (QT & Decl::OBJC_TQ_Byref)
5100 S += 'R';
5101 if (QT & Decl::OBJC_TQ_Oneway)
5102 S += 'V';
5103}
5104
Douglas Gregor3ea72692011-08-12 05:46:01 +00005105TypedefDecl *ASTContext::getObjCIdDecl() const {
5106 if (!ObjCIdDecl) {
5107 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5108 T = getObjCObjectPointerType(T);
5109 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5110 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5111 getTranslationUnitDecl(),
5112 SourceLocation(), SourceLocation(),
5113 &Idents.get("id"), IdInfo);
5114 }
5115
5116 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005117}
5118
Douglas Gregor52e02802011-08-12 06:17:30 +00005119TypedefDecl *ASTContext::getObjCSelDecl() const {
5120 if (!ObjCSelDecl) {
5121 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5122 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5123 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5124 getTranslationUnitDecl(),
5125 SourceLocation(), SourceLocation(),
5126 &Idents.get("SEL"), SelInfo);
5127 }
5128 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005129}
5130
Douglas Gregor0a586182011-08-12 05:59:41 +00005131TypedefDecl *ASTContext::getObjCClassDecl() const {
5132 if (!ObjCClassDecl) {
5133 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5134 T = getObjCObjectPointerType(T);
5135 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5136 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5137 getTranslationUnitDecl(),
5138 SourceLocation(), SourceLocation(),
5139 &Idents.get("Class"), ClassInfo);
5140 }
5141
5142 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005143}
5144
Douglas Gregord53ae832012-01-17 18:09:05 +00005145ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5146 if (!ObjCProtocolClassDecl) {
5147 ObjCProtocolClassDecl
5148 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5149 SourceLocation(),
5150 &Idents.get("Protocol"),
5151 /*PrevDecl=*/0,
5152 SourceLocation(), true);
5153 }
5154
5155 return ObjCProtocolClassDecl;
5156}
5157
Meador Inge5d3fb222012-06-16 03:34:49 +00005158//===----------------------------------------------------------------------===//
5159// __builtin_va_list Construction Functions
5160//===----------------------------------------------------------------------===//
5161
5162static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5163 // typedef char* __builtin_va_list;
5164 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5165 TypeSourceInfo *TInfo
5166 = Context->getTrivialTypeSourceInfo(CharPtrType);
5167
5168 TypedefDecl *VaListTypeDecl
5169 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5170 Context->getTranslationUnitDecl(),
5171 SourceLocation(), SourceLocation(),
5172 &Context->Idents.get("__builtin_va_list"),
5173 TInfo);
5174 return VaListTypeDecl;
5175}
5176
5177static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5178 // typedef void* __builtin_va_list;
5179 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5180 TypeSourceInfo *TInfo
5181 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5182
5183 TypedefDecl *VaListTypeDecl
5184 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5185 Context->getTranslationUnitDecl(),
5186 SourceLocation(), SourceLocation(),
5187 &Context->Idents.get("__builtin_va_list"),
5188 TInfo);
5189 return VaListTypeDecl;
5190}
5191
5192static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5193 // typedef struct __va_list_tag {
5194 RecordDecl *VaListTagDecl;
5195
5196 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5197 Context->getTranslationUnitDecl(),
5198 &Context->Idents.get("__va_list_tag"));
5199 VaListTagDecl->startDefinition();
5200
5201 const size_t NumFields = 5;
5202 QualType FieldTypes[NumFields];
5203 const char *FieldNames[NumFields];
5204
5205 // unsigned char gpr;
5206 FieldTypes[0] = Context->UnsignedCharTy;
5207 FieldNames[0] = "gpr";
5208
5209 // unsigned char fpr;
5210 FieldTypes[1] = Context->UnsignedCharTy;
5211 FieldNames[1] = "fpr";
5212
5213 // unsigned short reserved;
5214 FieldTypes[2] = Context->UnsignedShortTy;
5215 FieldNames[2] = "reserved";
5216
5217 // void* overflow_arg_area;
5218 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5219 FieldNames[3] = "overflow_arg_area";
5220
5221 // void* reg_save_area;
5222 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5223 FieldNames[4] = "reg_save_area";
5224
5225 // Create fields
5226 for (unsigned i = 0; i < NumFields; ++i) {
5227 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5228 SourceLocation(),
5229 SourceLocation(),
5230 &Context->Idents.get(FieldNames[i]),
5231 FieldTypes[i], /*TInfo=*/0,
5232 /*BitWidth=*/0,
5233 /*Mutable=*/false,
5234 ICIS_NoInit);
5235 Field->setAccess(AS_public);
5236 VaListTagDecl->addDecl(Field);
5237 }
5238 VaListTagDecl->completeDefinition();
5239 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005240 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005241
5242 // } __va_list_tag;
5243 TypedefDecl *VaListTagTypedefDecl
5244 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5245 Context->getTranslationUnitDecl(),
5246 SourceLocation(), SourceLocation(),
5247 &Context->Idents.get("__va_list_tag"),
5248 Context->getTrivialTypeSourceInfo(VaListTagType));
5249 QualType VaListTagTypedefType =
5250 Context->getTypedefType(VaListTagTypedefDecl);
5251
5252 // typedef __va_list_tag __builtin_va_list[1];
5253 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5254 QualType VaListTagArrayType
5255 = Context->getConstantArrayType(VaListTagTypedefType,
5256 Size, ArrayType::Normal, 0);
5257 TypeSourceInfo *TInfo
5258 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5259 TypedefDecl *VaListTypedefDecl
5260 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5261 Context->getTranslationUnitDecl(),
5262 SourceLocation(), SourceLocation(),
5263 &Context->Idents.get("__builtin_va_list"),
5264 TInfo);
5265
5266 return VaListTypedefDecl;
5267}
5268
5269static TypedefDecl *
5270CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5271 // typedef struct __va_list_tag {
5272 RecordDecl *VaListTagDecl;
5273 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5274 Context->getTranslationUnitDecl(),
5275 &Context->Idents.get("__va_list_tag"));
5276 VaListTagDecl->startDefinition();
5277
5278 const size_t NumFields = 4;
5279 QualType FieldTypes[NumFields];
5280 const char *FieldNames[NumFields];
5281
5282 // unsigned gp_offset;
5283 FieldTypes[0] = Context->UnsignedIntTy;
5284 FieldNames[0] = "gp_offset";
5285
5286 // unsigned fp_offset;
5287 FieldTypes[1] = Context->UnsignedIntTy;
5288 FieldNames[1] = "fp_offset";
5289
5290 // void* overflow_arg_area;
5291 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5292 FieldNames[2] = "overflow_arg_area";
5293
5294 // void* reg_save_area;
5295 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5296 FieldNames[3] = "reg_save_area";
5297
5298 // Create fields
5299 for (unsigned i = 0; i < NumFields; ++i) {
5300 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5301 VaListTagDecl,
5302 SourceLocation(),
5303 SourceLocation(),
5304 &Context->Idents.get(FieldNames[i]),
5305 FieldTypes[i], /*TInfo=*/0,
5306 /*BitWidth=*/0,
5307 /*Mutable=*/false,
5308 ICIS_NoInit);
5309 Field->setAccess(AS_public);
5310 VaListTagDecl->addDecl(Field);
5311 }
5312 VaListTagDecl->completeDefinition();
5313 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005314 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005315
5316 // } __va_list_tag;
5317 TypedefDecl *VaListTagTypedefDecl
5318 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5319 Context->getTranslationUnitDecl(),
5320 SourceLocation(), SourceLocation(),
5321 &Context->Idents.get("__va_list_tag"),
5322 Context->getTrivialTypeSourceInfo(VaListTagType));
5323 QualType VaListTagTypedefType =
5324 Context->getTypedefType(VaListTagTypedefDecl);
5325
5326 // typedef __va_list_tag __builtin_va_list[1];
5327 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5328 QualType VaListTagArrayType
5329 = Context->getConstantArrayType(VaListTagTypedefType,
5330 Size, ArrayType::Normal,0);
5331 TypeSourceInfo *TInfo
5332 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5333 TypedefDecl *VaListTypedefDecl
5334 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5335 Context->getTranslationUnitDecl(),
5336 SourceLocation(), SourceLocation(),
5337 &Context->Idents.get("__builtin_va_list"),
5338 TInfo);
5339
5340 return VaListTypedefDecl;
5341}
5342
5343static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5344 // typedef int __builtin_va_list[4];
5345 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5346 QualType IntArrayType
5347 = Context->getConstantArrayType(Context->IntTy,
5348 Size, ArrayType::Normal, 0);
5349 TypedefDecl *VaListTypedefDecl
5350 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5351 Context->getTranslationUnitDecl(),
5352 SourceLocation(), SourceLocation(),
5353 &Context->Idents.get("__builtin_va_list"),
5354 Context->getTrivialTypeSourceInfo(IntArrayType));
5355
5356 return VaListTypedefDecl;
5357}
5358
5359static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5360 TargetInfo::BuiltinVaListKind Kind) {
5361 switch (Kind) {
5362 case TargetInfo::CharPtrBuiltinVaList:
5363 return CreateCharPtrBuiltinVaListDecl(Context);
5364 case TargetInfo::VoidPtrBuiltinVaList:
5365 return CreateVoidPtrBuiltinVaListDecl(Context);
5366 case TargetInfo::PowerABIBuiltinVaList:
5367 return CreatePowerABIBuiltinVaListDecl(Context);
5368 case TargetInfo::X86_64ABIBuiltinVaList:
5369 return CreateX86_64ABIBuiltinVaListDecl(Context);
5370 case TargetInfo::PNaClABIBuiltinVaList:
5371 return CreatePNaClABIBuiltinVaListDecl(Context);
5372 }
5373
5374 llvm_unreachable("Unhandled __builtin_va_list type kind");
5375}
5376
5377TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5378 if (!BuiltinVaListDecl)
5379 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5380
5381 return BuiltinVaListDecl;
5382}
5383
Meador Ingecfb60902012-07-01 15:57:25 +00005384QualType ASTContext::getVaListTagType() const {
5385 // Force the creation of VaListTagTy by building the __builtin_va_list
5386 // declaration.
5387 if (VaListTagTy.isNull())
5388 (void) getBuiltinVaListDecl();
5389
5390 return VaListTagTy;
5391}
5392
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005393void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00005394 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00005395 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00005396
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005397 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00005398}
5399
John McCalld28ae272009-12-02 08:04:21 +00005400/// \brief Retrieve the template name that corresponds to a non-empty
5401/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00005402TemplateName
5403ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5404 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00005405 unsigned size = End - Begin;
5406 assert(size > 1 && "set is not overloaded!");
5407
5408 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5409 size * sizeof(FunctionTemplateDecl*));
5410 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5411
5412 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00005413 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00005414 NamedDecl *D = *I;
5415 assert(isa<FunctionTemplateDecl>(D) ||
5416 (isa<UsingShadowDecl>(D) &&
5417 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5418 *Storage++ = D;
5419 }
5420
5421 return TemplateName(OT);
5422}
5423
Douglas Gregordc572a32009-03-30 22:58:21 +00005424/// \brief Retrieve the template name that represents a qualified
5425/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00005426TemplateName
5427ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5428 bool TemplateKeyword,
5429 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00005430 assert(NNS && "Missing nested-name-specifier in qualified template name");
5431
Douglas Gregorc42075a2010-02-04 18:10:26 +00005432 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00005433 llvm::FoldingSetNodeID ID;
5434 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5435
5436 void *InsertPos = 0;
5437 QualifiedTemplateName *QTN =
5438 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5439 if (!QTN) {
5440 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
5441 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5442 }
5443
5444 return TemplateName(QTN);
5445}
5446
5447/// \brief Retrieve the template name that represents a dependent
5448/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00005449TemplateName
5450ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5451 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00005452 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00005453 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00005454
5455 llvm::FoldingSetNodeID ID;
5456 DependentTemplateName::Profile(ID, NNS, Name);
5457
5458 void *InsertPos = 0;
5459 DependentTemplateName *QTN =
5460 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5461
5462 if (QTN)
5463 return TemplateName(QTN);
5464
5465 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5466 if (CanonNNS == NNS) {
5467 QTN = new (*this,4) DependentTemplateName(NNS, Name);
5468 } else {
5469 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
5470 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005471 DependentTemplateName *CheckQTN =
5472 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5473 assert(!CheckQTN && "Dependent type name canonicalization broken");
5474 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00005475 }
5476
5477 DependentTemplateNames.InsertNode(QTN, InsertPos);
5478 return TemplateName(QTN);
5479}
5480
Douglas Gregor71395fa2009-11-04 00:56:37 +00005481/// \brief Retrieve the template name that represents a dependent
5482/// template name such as \c MetaFun::template operator+.
5483TemplateName
5484ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00005485 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00005486 assert((!NNS || NNS->isDependent()) &&
5487 "Nested name specifier must be dependent");
5488
5489 llvm::FoldingSetNodeID ID;
5490 DependentTemplateName::Profile(ID, NNS, Operator);
5491
5492 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00005493 DependentTemplateName *QTN
5494 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005495
5496 if (QTN)
5497 return TemplateName(QTN);
5498
5499 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5500 if (CanonNNS == NNS) {
5501 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
5502 } else {
5503 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
5504 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005505
5506 DependentTemplateName *CheckQTN
5507 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5508 assert(!CheckQTN && "Dependent template name canonicalization broken");
5509 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00005510 }
5511
5512 DependentTemplateNames.InsertNode(QTN, InsertPos);
5513 return TemplateName(QTN);
5514}
5515
Douglas Gregor5590be02011-01-15 06:45:20 +00005516TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00005517ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5518 TemplateName replacement) const {
5519 llvm::FoldingSetNodeID ID;
5520 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5521
5522 void *insertPos = 0;
5523 SubstTemplateTemplateParmStorage *subst
5524 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5525
5526 if (!subst) {
5527 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5528 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5529 }
5530
5531 return TemplateName(subst);
5532}
5533
5534TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00005535ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5536 const TemplateArgument &ArgPack) const {
5537 ASTContext &Self = const_cast<ASTContext &>(*this);
5538 llvm::FoldingSetNodeID ID;
5539 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5540
5541 void *InsertPos = 0;
5542 SubstTemplateTemplateParmPackStorage *Subst
5543 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5544
5545 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00005546 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00005547 ArgPack.pack_size(),
5548 ArgPack.pack_begin());
5549 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5550 }
5551
5552 return TemplateName(Subst);
5553}
5554
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005555/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00005556/// TargetInfo, produce the corresponding type. The unsigned @p Type
5557/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00005558CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005559 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00005560 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005561 case TargetInfo::SignedShort: return ShortTy;
5562 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5563 case TargetInfo::SignedInt: return IntTy;
5564 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5565 case TargetInfo::SignedLong: return LongTy;
5566 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5567 case TargetInfo::SignedLongLong: return LongLongTy;
5568 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5569 }
5570
David Blaikie83d382b2011-09-23 05:06:16 +00005571 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005572}
Ted Kremenek77c51b22008-07-24 23:58:27 +00005573
5574//===----------------------------------------------------------------------===//
5575// Type Predicates.
5576//===----------------------------------------------------------------------===//
5577
Fariborz Jahanian96207692009-02-18 21:49:28 +00005578/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5579/// garbage collection attribute.
5580///
John McCall553d45a2011-01-12 00:34:59 +00005581Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005582 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00005583 return Qualifiers::GCNone;
5584
David Blaikiebbafb8a2012-03-11 07:00:24 +00005585 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00005586 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5587
5588 // Default behaviour under objective-C's gc is for ObjC pointers
5589 // (or pointers to them) be treated as though they were declared
5590 // as __strong.
5591 if (GCAttrs == Qualifiers::GCNone) {
5592 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5593 return Qualifiers::Strong;
5594 else if (Ty->isPointerType())
5595 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5596 } else {
5597 // It's not valid to set GC attributes on anything that isn't a
5598 // pointer.
5599#ifndef NDEBUG
5600 QualType CT = Ty->getCanonicalTypeInternal();
5601 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5602 CT = AT->getElementType();
5603 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5604#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00005605 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00005606 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00005607}
5608
Chris Lattner49af6a42008-04-07 06:51:04 +00005609//===----------------------------------------------------------------------===//
5610// Type Compatibility Testing
5611//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00005612
Mike Stump11289f42009-09-09 15:08:12 +00005613/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005614/// compatible.
5615static bool areCompatVectorTypes(const VectorType *LHS,
5616 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00005617 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00005618 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00005619 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00005620}
5621
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005622bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5623 QualType SecondVec) {
5624 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5625 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5626
5627 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5628 return true;
5629
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005630 // Treat Neon vector types and most AltiVec vector types as if they are the
5631 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005632 const VectorType *First = FirstVec->getAs<VectorType>();
5633 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005634 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005635 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005636 First->getVectorKind() != VectorType::AltiVecPixel &&
5637 First->getVectorKind() != VectorType::AltiVecBool &&
5638 Second->getVectorKind() != VectorType::AltiVecPixel &&
5639 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005640 return true;
5641
5642 return false;
5643}
5644
Steve Naroff8e6aee52009-07-23 01:01:38 +00005645//===----------------------------------------------------------------------===//
5646// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5647//===----------------------------------------------------------------------===//
5648
5649/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5650/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00005651bool
5652ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5653 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00005654 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005655 return true;
5656 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5657 E = rProto->protocol_end(); PI != E; ++PI)
5658 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5659 return true;
5660 return false;
5661}
5662
Steve Naroff8e6aee52009-07-23 01:01:38 +00005663/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5664/// return true if lhs's protocols conform to rhs's protocol; false
5665/// otherwise.
5666bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5667 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5668 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5669 return false;
5670}
5671
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005672/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5673/// Class<p1, ...>.
5674bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5675 QualType rhs) {
5676 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5677 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5678 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5679
5680 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5681 E = lhsQID->qual_end(); I != E; ++I) {
5682 bool match = false;
5683 ObjCProtocolDecl *lhsProto = *I;
5684 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5685 E = rhsOPT->qual_end(); J != E; ++J) {
5686 ObjCProtocolDecl *rhsProto = *J;
5687 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5688 match = true;
5689 break;
5690 }
5691 }
5692 if (!match)
5693 return false;
5694 }
5695 return true;
5696}
5697
Steve Naroff8e6aee52009-07-23 01:01:38 +00005698/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5699/// ObjCQualifiedIDType.
5700bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5701 bool compare) {
5702 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00005703 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005704 lhs->isObjCIdType() || lhs->isObjCClassType())
5705 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005706 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005707 rhs->isObjCIdType() || rhs->isObjCClassType())
5708 return true;
5709
5710 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00005711 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005712
Steve Naroff8e6aee52009-07-23 01:01:38 +00005713 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00005714
Steve Naroff8e6aee52009-07-23 01:01:38 +00005715 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005716 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005717 // make sure we check the class hierarchy.
5718 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5719 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5720 E = lhsQID->qual_end(); I != E; ++I) {
5721 // when comparing an id<P> on lhs with a static type on rhs,
5722 // see if static class implements all of id's protocols, directly or
5723 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005724 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005725 return false;
5726 }
5727 }
5728 // If there are no qualifiers and no interface, we have an 'id'.
5729 return true;
5730 }
Mike Stump11289f42009-09-09 15:08:12 +00005731 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005732 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5733 E = lhsQID->qual_end(); I != E; ++I) {
5734 ObjCProtocolDecl *lhsProto = *I;
5735 bool match = false;
5736
5737 // when comparing an id<P> on lhs with a static type on rhs,
5738 // see if static class implements all of id's protocols, directly or
5739 // through its super class and categories.
5740 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5741 E = rhsOPT->qual_end(); J != E; ++J) {
5742 ObjCProtocolDecl *rhsProto = *J;
5743 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5744 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5745 match = true;
5746 break;
5747 }
5748 }
Mike Stump11289f42009-09-09 15:08:12 +00005749 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005750 // make sure we check the class hierarchy.
5751 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5752 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5753 E = lhsQID->qual_end(); I != E; ++I) {
5754 // when comparing an id<P> on lhs with a static type on rhs,
5755 // see if static class implements all of id's protocols, directly or
5756 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005757 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005758 match = true;
5759 break;
5760 }
5761 }
5762 }
5763 if (!match)
5764 return false;
5765 }
Mike Stump11289f42009-09-09 15:08:12 +00005766
Steve Naroff8e6aee52009-07-23 01:01:38 +00005767 return true;
5768 }
Mike Stump11289f42009-09-09 15:08:12 +00005769
Steve Naroff8e6aee52009-07-23 01:01:38 +00005770 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5771 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5772
Mike Stump11289f42009-09-09 15:08:12 +00005773 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00005774 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005775 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005776 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5777 E = lhsOPT->qual_end(); I != E; ++I) {
5778 ObjCProtocolDecl *lhsProto = *I;
5779 bool match = false;
5780
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005781 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00005782 // see if static class implements all of id's protocols, directly or
5783 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005784 // First, lhs protocols in the qualifier list must be found, direct
5785 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005786 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5787 E = rhsQID->qual_end(); J != E; ++J) {
5788 ObjCProtocolDecl *rhsProto = *J;
5789 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5790 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5791 match = true;
5792 break;
5793 }
5794 }
5795 if (!match)
5796 return false;
5797 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005798
5799 // Static class's protocols, or its super class or category protocols
5800 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5801 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5802 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5803 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5804 // This is rather dubious but matches gcc's behavior. If lhs has
5805 // no type qualifier and its class has no static protocol(s)
5806 // assume that it is mismatch.
5807 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5808 return false;
5809 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5810 LHSInheritedProtocols.begin(),
5811 E = LHSInheritedProtocols.end(); I != E; ++I) {
5812 bool match = false;
5813 ObjCProtocolDecl *lhsProto = (*I);
5814 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5815 E = rhsQID->qual_end(); J != E; ++J) {
5816 ObjCProtocolDecl *rhsProto = *J;
5817 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5818 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5819 match = true;
5820 break;
5821 }
5822 }
5823 if (!match)
5824 return false;
5825 }
5826 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00005827 return true;
5828 }
5829 return false;
5830}
5831
Eli Friedman47f77112008-08-22 00:56:42 +00005832/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005833/// compatible for assignment from RHS to LHS. This handles validation of any
5834/// protocol qualifiers on the LHS or RHS.
5835///
Steve Naroff7cae42b2009-07-10 23:34:53 +00005836bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5837 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00005838 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5839 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5840
Steve Naroff1329fa02009-07-15 18:40:39 +00005841 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00005842 if (LHS->isObjCUnqualifiedIdOrClass() ||
5843 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00005844 return true;
5845
John McCall8b07ec22010-05-15 11:32:37 +00005846 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00005847 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5848 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00005849 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005850
5851 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5852 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5853 QualType(RHSOPT,0));
5854
John McCall8b07ec22010-05-15 11:32:37 +00005855 // If we have 2 user-defined types, fall into that path.
5856 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00005857 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005858
Steve Naroff8e6aee52009-07-23 01:01:38 +00005859 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005860}
5861
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005862/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00005863/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005864/// arguments in block literals. When passed as arguments, passing 'A*' where
5865/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5866/// not OK. For the return type, the opposite is not OK.
5867bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5868 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005869 const ObjCObjectPointerType *RHSOPT,
5870 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005871 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005872 return true;
5873
5874 if (LHSOPT->isObjCBuiltinType()) {
5875 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5876 }
5877
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005878 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005879 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5880 QualType(RHSOPT,0),
5881 false);
5882
5883 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5884 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5885 if (LHS && RHS) { // We have 2 user-defined types.
5886 if (LHS != RHS) {
5887 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005888 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005889 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005890 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005891 }
5892 else
5893 return true;
5894 }
5895 return false;
5896}
5897
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005898/// getIntersectionOfProtocols - This routine finds the intersection of set
5899/// of protocols inherited from two distinct objective-c pointer objects.
5900/// It is used to build composite qualifier list of the composite type of
5901/// the conditional expression involving two objective-c pointer objects.
5902static
5903void getIntersectionOfProtocols(ASTContext &Context,
5904 const ObjCObjectPointerType *LHSOPT,
5905 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005906 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005907
John McCall8b07ec22010-05-15 11:32:37 +00005908 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5909 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5910 assert(LHS->getInterface() && "LHS must have an interface base");
5911 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005912
5913 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5914 unsigned LHSNumProtocols = LHS->getNumProtocols();
5915 if (LHSNumProtocols > 0)
5916 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5917 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005918 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005919 Context.CollectInheritedProtocols(LHS->getInterface(),
5920 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005921 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5922 LHSInheritedProtocols.end());
5923 }
5924
5925 unsigned RHSNumProtocols = RHS->getNumProtocols();
5926 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00005927 ObjCProtocolDecl **RHSProtocols =
5928 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005929 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5930 if (InheritedProtocolSet.count(RHSProtocols[i]))
5931 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00005932 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005933 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005934 Context.CollectInheritedProtocols(RHS->getInterface(),
5935 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005936 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5937 RHSInheritedProtocols.begin(),
5938 E = RHSInheritedProtocols.end(); I != E; ++I)
5939 if (InheritedProtocolSet.count((*I)))
5940 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005941 }
5942}
5943
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005944/// areCommonBaseCompatible - Returns common base class of the two classes if
5945/// one found. Note that this is O'2 algorithm. But it will be called as the
5946/// last type comparison in a ?-exp of ObjC pointer types before a
5947/// warning is issued. So, its invokation is extremely rare.
5948QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00005949 const ObjCObjectPointerType *Lptr,
5950 const ObjCObjectPointerType *Rptr) {
5951 const ObjCObjectType *LHS = Lptr->getObjectType();
5952 const ObjCObjectType *RHS = Rptr->getObjectType();
5953 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5954 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00005955 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005956 return QualType();
5957
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005958 do {
John McCall8b07ec22010-05-15 11:32:37 +00005959 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005960 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005961 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00005962 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5963
5964 QualType Result = QualType(LHS, 0);
5965 if (!Protocols.empty())
5966 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5967 Result = getObjCObjectPointerType(Result);
5968 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005969 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005970 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005971
5972 return QualType();
5973}
5974
John McCall8b07ec22010-05-15 11:32:37 +00005975bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5976 const ObjCObjectType *RHS) {
5977 assert(LHS->getInterface() && "LHS is not an interface type");
5978 assert(RHS->getInterface() && "RHS is not an interface type");
5979
Chris Lattner49af6a42008-04-07 06:51:04 +00005980 // Verify that the base decls are compatible: the RHS must be a subclass of
5981 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00005982 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00005983 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005984
Chris Lattner49af6a42008-04-07 06:51:04 +00005985 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5986 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00005987 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00005988 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005989
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005990 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5991 // more detailed analysis is required.
5992 if (RHS->getNumProtocols() == 0) {
5993 // OK, if LHS is a superclass of RHS *and*
5994 // this superclass is assignment compatible with LHS.
5995 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005996 bool IsSuperClass =
5997 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5998 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005999 // OK if conversion of LHS to SuperClass results in narrowing of types
6000 // ; i.e., SuperClass may implement at least one of the protocols
6001 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6002 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6003 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006004 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006005 // If super class has no protocols, it is not a match.
6006 if (SuperClassInheritedProtocols.empty())
6007 return false;
6008
6009 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6010 LHSPE = LHS->qual_end();
6011 LHSPI != LHSPE; LHSPI++) {
6012 bool SuperImplementsProtocol = false;
6013 ObjCProtocolDecl *LHSProto = (*LHSPI);
6014
6015 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6016 SuperClassInheritedProtocols.begin(),
6017 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6018 ObjCProtocolDecl *SuperClassProto = (*I);
6019 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6020 SuperImplementsProtocol = true;
6021 break;
6022 }
6023 }
6024 if (!SuperImplementsProtocol)
6025 return false;
6026 }
6027 return true;
6028 }
6029 return false;
6030 }
Mike Stump11289f42009-09-09 15:08:12 +00006031
John McCall8b07ec22010-05-15 11:32:37 +00006032 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6033 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00006034 LHSPI != LHSPE; LHSPI++) {
6035 bool RHSImplementsProtocol = false;
6036
6037 // If the RHS doesn't implement the protocol on the left, the types
6038 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00006039 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6040 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00006041 RHSPI != RHSPE; RHSPI++) {
6042 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006043 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00006044 break;
6045 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006046 }
6047 // FIXME: For better diagnostics, consider passing back the protocol name.
6048 if (!RHSImplementsProtocol)
6049 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006050 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006051 // The RHS implements all protocols listed on the LHS.
6052 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006053}
6054
Steve Naroffb7605152009-02-12 17:52:19 +00006055bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6056 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006057 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6058 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006059
Steve Naroff7cae42b2009-07-10 23:34:53 +00006060 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006061 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006062
6063 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6064 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006065}
6066
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006067bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6068 return canAssignObjCInterfaces(
6069 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6070 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6071}
6072
Mike Stump11289f42009-09-09 15:08:12 +00006073/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006074/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006075/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006076/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006077bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6078 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006079 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006080 return hasSameType(LHS, RHS);
6081
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006082 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006083}
6084
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006085bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006086 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006087}
6088
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006089bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6090 return !mergeTypes(LHS, RHS, true).isNull();
6091}
6092
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006093/// mergeTransparentUnionType - if T is a transparent union type and a member
6094/// of T is compatible with SubType, return the merged type, else return
6095/// QualType()
6096QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6097 bool OfBlockPointer,
6098 bool Unqualified) {
6099 if (const RecordType *UT = T->getAsUnionType()) {
6100 RecordDecl *UD = UT->getDecl();
6101 if (UD->hasAttr<TransparentUnionAttr>()) {
6102 for (RecordDecl::field_iterator it = UD->field_begin(),
6103 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00006104 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006105 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6106 if (!MT.isNull())
6107 return MT;
6108 }
6109 }
6110 }
6111
6112 return QualType();
6113}
6114
6115/// mergeFunctionArgumentTypes - merge two types which appear as function
6116/// argument types
6117QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6118 bool OfBlockPointer,
6119 bool Unqualified) {
6120 // GNU extension: two types are compatible if they appear as a function
6121 // argument, one of the types is a transparent union type and the other
6122 // type is compatible with a union member
6123 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6124 Unqualified);
6125 if (!lmerge.isNull())
6126 return lmerge;
6127
6128 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6129 Unqualified);
6130 if (!rmerge.isNull())
6131 return rmerge;
6132
6133 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6134}
6135
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006136QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006137 bool OfBlockPointer,
6138 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006139 const FunctionType *lbase = lhs->getAs<FunctionType>();
6140 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006141 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6142 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006143 bool allLTypes = true;
6144 bool allRTypes = true;
6145
6146 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006147 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006148 if (OfBlockPointer) {
6149 QualType RHS = rbase->getResultType();
6150 QualType LHS = lbase->getResultType();
6151 bool UnqualifiedResult = Unqualified;
6152 if (!UnqualifiedResult)
6153 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006154 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006155 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006156 else
John McCall8c6b56f2010-12-15 01:06:38 +00006157 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6158 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006159 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006160
6161 if (Unqualified)
6162 retType = retType.getUnqualifiedType();
6163
6164 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6165 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6166 if (Unqualified) {
6167 LRetType = LRetType.getUnqualifiedType();
6168 RRetType = RRetType.getUnqualifiedType();
6169 }
6170
6171 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006172 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006173 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006174 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006175
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006176 // FIXME: double check this
6177 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6178 // rbase->getRegParmAttr() != 0 &&
6179 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006180 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6181 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006182
Douglas Gregor8c940862010-01-18 17:14:39 +00006183 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00006184 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00006185 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006186
John McCall8c6b56f2010-12-15 01:06:38 +00006187 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006188 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6189 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006190 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6191 return QualType();
6192
John McCall31168b02011-06-15 23:02:42 +00006193 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6194 return QualType();
6195
Fariborz Jahanian48c69102011-10-05 00:05:34 +00006196 // functypes which return are preferred over those that do not.
6197 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
6198 allLTypes = false;
6199 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
6200 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006201 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6202 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006203
John McCall31168b02011-06-15 23:02:42 +00006204 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006205
Eli Friedman47f77112008-08-22 00:56:42 +00006206 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006207 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6208 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006209 unsigned lproto_nargs = lproto->getNumArgs();
6210 unsigned rproto_nargs = rproto->getNumArgs();
6211
6212 // Compatible functions must have the same number of arguments
6213 if (lproto_nargs != rproto_nargs)
6214 return QualType();
6215
6216 // Variadic and non-variadic functions aren't compatible
6217 if (lproto->isVariadic() != rproto->isVariadic())
6218 return QualType();
6219
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006220 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6221 return QualType();
6222
Fariborz Jahanian97676972011-09-28 21:52:05 +00006223 if (LangOpts.ObjCAutoRefCount &&
6224 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6225 return QualType();
6226
Eli Friedman47f77112008-08-22 00:56:42 +00006227 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006228 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00006229 for (unsigned i = 0; i < lproto_nargs; i++) {
6230 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6231 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006232 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6233 OfBlockPointer,
6234 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006235 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006236
6237 if (Unqualified)
6238 argtype = argtype.getUnqualifiedType();
6239
Eli Friedman47f77112008-08-22 00:56:42 +00006240 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006241 if (Unqualified) {
6242 largtype = largtype.getUnqualifiedType();
6243 rargtype = rargtype.getUnqualifiedType();
6244 }
6245
Chris Lattner465fa322008-10-05 17:34:18 +00006246 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6247 allLTypes = false;
6248 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6249 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006250 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006251
Eli Friedman47f77112008-08-22 00:56:42 +00006252 if (allLTypes) return lhs;
6253 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006254
6255 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6256 EPI.ExtInfo = einfo;
6257 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006258 }
6259
6260 if (lproto) allRTypes = false;
6261 if (rproto) allLTypes = false;
6262
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006263 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006264 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006265 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006266 if (proto->isVariadic()) return QualType();
6267 // Check that the types are compatible with the types that
6268 // would result from default argument promotions (C99 6.7.5.3p15).
6269 // The only types actually affected are promotable integer
6270 // types and floats, which would be passed as a different
6271 // type depending on whether the prototype is visible.
6272 unsigned proto_nargs = proto->getNumArgs();
6273 for (unsigned i = 0; i < proto_nargs; ++i) {
6274 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00006275
6276 // Look at the promotion type of enum types, since that is the type used
6277 // to pass enum values.
6278 if (const EnumType *Enum = argTy->getAs<EnumType>())
6279 argTy = Enum->getDecl()->getPromotionType();
6280
Eli Friedman47f77112008-08-22 00:56:42 +00006281 if (argTy->isPromotableIntegerType() ||
6282 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6283 return QualType();
6284 }
6285
6286 if (allLTypes) return lhs;
6287 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006288
6289 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6290 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00006291 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006292 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006293 }
6294
6295 if (allLTypes) return lhs;
6296 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00006297 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00006298}
6299
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006300QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006301 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006302 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00006303 // C++ [expr]: If an expression initially has the type "reference to T", the
6304 // type is adjusted to "T" prior to any further analysis, the expression
6305 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006306 // expression is an lvalue unless the reference is an rvalue reference and
6307 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00006308 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6309 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006310
6311 if (Unqualified) {
6312 LHS = LHS.getUnqualifiedType();
6313 RHS = RHS.getUnqualifiedType();
6314 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00006315
Eli Friedman47f77112008-08-22 00:56:42 +00006316 QualType LHSCan = getCanonicalType(LHS),
6317 RHSCan = getCanonicalType(RHS);
6318
6319 // If two types are identical, they are compatible.
6320 if (LHSCan == RHSCan)
6321 return LHS;
6322
John McCall8ccfcb52009-09-24 19:53:00 +00006323 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006324 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6325 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00006326 if (LQuals != RQuals) {
6327 // If any of these qualifiers are different, we have a type
6328 // mismatch.
6329 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00006330 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6331 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00006332 return QualType();
6333
6334 // Exactly one GC qualifier difference is allowed: __strong is
6335 // okay if the other type has no GC qualifier but is an Objective
6336 // C object pointer (i.e. implicitly strong by default). We fix
6337 // this by pretending that the unqualified type was actually
6338 // qualified __strong.
6339 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6340 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6341 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6342
6343 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6344 return QualType();
6345
6346 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6347 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6348 }
6349 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6350 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6351 }
Eli Friedman47f77112008-08-22 00:56:42 +00006352 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00006353 }
6354
6355 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00006356
Eli Friedmandcca6332009-06-01 01:22:52 +00006357 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6358 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00006359
Chris Lattnerfd652912008-01-14 05:45:46 +00006360 // We want to consider the two function types to be the same for these
6361 // comparisons, just force one to the other.
6362 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6363 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00006364
6365 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00006366 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6367 LHSClass = Type::ConstantArray;
6368 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6369 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00006370
John McCall8b07ec22010-05-15 11:32:37 +00006371 // ObjCInterfaces are just specialized ObjCObjects.
6372 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6373 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6374
Nate Begemance4d7fc2008-04-18 23:10:10 +00006375 // Canonicalize ExtVector -> Vector.
6376 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6377 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00006378
Chris Lattner95554662008-04-07 05:43:21 +00006379 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006380 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00006381 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00006382 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00006383 // Compatibility is based on the underlying type, not the promotion
6384 // type.
John McCall9dd450b2009-09-21 23:43:11 +00006385 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006386 QualType TINT = ETy->getDecl()->getIntegerType();
6387 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006388 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006389 }
John McCall9dd450b2009-09-21 23:43:11 +00006390 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006391 QualType TINT = ETy->getDecl()->getIntegerType();
6392 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006393 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006394 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006395 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00006396 if (OfBlockPointer && !BlockReturnType) {
6397 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6398 return LHS;
6399 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6400 return RHS;
6401 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006402
Eli Friedman47f77112008-08-22 00:56:42 +00006403 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00006404 }
Eli Friedman47f77112008-08-22 00:56:42 +00006405
Steve Naroffc6edcbd2008-01-09 22:43:08 +00006406 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006407 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006408#define TYPE(Class, Base)
6409#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00006410#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006411#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6412#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6413#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00006414 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006415
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006416 case Type::LValueReference:
6417 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006418 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00006419 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006420
John McCall8b07ec22010-05-15 11:32:37 +00006421 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006422 case Type::IncompleteArray:
6423 case Type::VariableArray:
6424 case Type::FunctionProto:
6425 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00006426 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006427
Chris Lattnerfd652912008-01-14 05:45:46 +00006428 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00006429 {
6430 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006431 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6432 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006433 if (Unqualified) {
6434 LHSPointee = LHSPointee.getUnqualifiedType();
6435 RHSPointee = RHSPointee.getUnqualifiedType();
6436 }
6437 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6438 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006439 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00006440 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006441 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00006442 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006443 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006444 return getPointerType(ResultType);
6445 }
Steve Naroff68e167d2008-12-10 17:49:55 +00006446 case Type::BlockPointer:
6447 {
6448 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006449 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6450 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006451 if (Unqualified) {
6452 LHSPointee = LHSPointee.getUnqualifiedType();
6453 RHSPointee = RHSPointee.getUnqualifiedType();
6454 }
6455 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6456 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00006457 if (ResultType.isNull()) return QualType();
6458 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6459 return LHS;
6460 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6461 return RHS;
6462 return getBlockPointerType(ResultType);
6463 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00006464 case Type::Atomic:
6465 {
6466 // Merge two pointer types, while trying to preserve typedef info
6467 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6468 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6469 if (Unqualified) {
6470 LHSValue = LHSValue.getUnqualifiedType();
6471 RHSValue = RHSValue.getUnqualifiedType();
6472 }
6473 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6474 Unqualified);
6475 if (ResultType.isNull()) return QualType();
6476 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6477 return LHS;
6478 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6479 return RHS;
6480 return getAtomicType(ResultType);
6481 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006482 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00006483 {
6484 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6485 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6486 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6487 return QualType();
6488
6489 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6490 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006491 if (Unqualified) {
6492 LHSElem = LHSElem.getUnqualifiedType();
6493 RHSElem = RHSElem.getUnqualifiedType();
6494 }
6495
6496 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006497 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00006498 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6499 return LHS;
6500 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6501 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00006502 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6503 ArrayType::ArraySizeModifier(), 0);
6504 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6505 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006506 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6507 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00006508 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6509 return LHS;
6510 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6511 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006512 if (LVAT) {
6513 // FIXME: This isn't correct! But tricky to implement because
6514 // the array's size has to be the size of LHS, but the type
6515 // has to be different.
6516 return LHS;
6517 }
6518 if (RVAT) {
6519 // FIXME: This isn't correct! But tricky to implement because
6520 // the array's size has to be the size of RHS, but the type
6521 // has to be different.
6522 return RHS;
6523 }
Eli Friedman3e62c212008-08-22 01:48:21 +00006524 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6525 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00006526 return getIncompleteArrayType(ResultType,
6527 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006528 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006529 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006530 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006531 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006532 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00006533 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00006534 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006535 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00006536 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00006537 case Type::Complex:
6538 // Distinct complex types are incompatible.
6539 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006540 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00006541 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00006542 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6543 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00006544 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00006545 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00006546 case Type::ObjCObject: {
6547 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00006548 // FIXME: This should be type compatibility, e.g. whether
6549 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00006550 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6551 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6552 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00006553 return LHS;
6554
Eli Friedman47f77112008-08-22 00:56:42 +00006555 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00006556 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006557 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006558 if (OfBlockPointer) {
6559 if (canAssignObjCInterfacesInBlockPointer(
6560 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006561 RHS->getAs<ObjCObjectPointerType>(),
6562 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00006563 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006564 return QualType();
6565 }
John McCall9dd450b2009-09-21 23:43:11 +00006566 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6567 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006568 return LHS;
6569
Steve Naroffc68cfcf2008-12-10 22:14:21 +00006570 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00006571 }
Steve Naroff32e44c02007-10-15 20:41:53 +00006572 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006573
David Blaikie8a40f702012-01-17 06:56:22 +00006574 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00006575}
Ted Kremenekfc581a92007-10-31 17:10:13 +00006576
Fariborz Jahanian97676972011-09-28 21:52:05 +00006577bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6578 const FunctionProtoType *FromFunctionType,
6579 const FunctionProtoType *ToFunctionType) {
6580 if (FromFunctionType->hasAnyConsumedArgs() !=
6581 ToFunctionType->hasAnyConsumedArgs())
6582 return false;
6583 FunctionProtoType::ExtProtoInfo FromEPI =
6584 FromFunctionType->getExtProtoInfo();
6585 FunctionProtoType::ExtProtoInfo ToEPI =
6586 ToFunctionType->getExtProtoInfo();
6587 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6588 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6589 ArgIdx != NumArgs; ++ArgIdx) {
6590 if (FromEPI.ConsumedArguments[ArgIdx] !=
6591 ToEPI.ConsumedArguments[ArgIdx])
6592 return false;
6593 }
6594 return true;
6595}
6596
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006597/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6598/// 'RHS' attributes and returns the merged version; including for function
6599/// return types.
6600QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6601 QualType LHSCan = getCanonicalType(LHS),
6602 RHSCan = getCanonicalType(RHS);
6603 // If two types are identical, they are compatible.
6604 if (LHSCan == RHSCan)
6605 return LHS;
6606 if (RHSCan->isFunctionType()) {
6607 if (!LHSCan->isFunctionType())
6608 return QualType();
6609 QualType OldReturnType =
6610 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6611 QualType NewReturnType =
6612 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6613 QualType ResReturnType =
6614 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6615 if (ResReturnType.isNull())
6616 return QualType();
6617 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6618 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6619 // In either case, use OldReturnType to build the new function type.
6620 const FunctionType *F = LHS->getAs<FunctionType>();
6621 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00006622 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6623 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006624 QualType ResultType
6625 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006626 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006627 return ResultType;
6628 }
6629 }
6630 return QualType();
6631 }
6632
6633 // If the qualifiers are different, the types can still be merged.
6634 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6635 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6636 if (LQuals != RQuals) {
6637 // If any of these qualifiers are different, we have a type mismatch.
6638 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6639 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6640 return QualType();
6641
6642 // Exactly one GC qualifier difference is allowed: __strong is
6643 // okay if the other type has no GC qualifier but is an Objective
6644 // C object pointer (i.e. implicitly strong by default). We fix
6645 // this by pretending that the unqualified type was actually
6646 // qualified __strong.
6647 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6648 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6649 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6650
6651 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6652 return QualType();
6653
6654 if (GC_L == Qualifiers::Strong)
6655 return LHS;
6656 if (GC_R == Qualifiers::Strong)
6657 return RHS;
6658 return QualType();
6659 }
6660
6661 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6662 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6663 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6664 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6665 if (ResQT == LHSBaseQT)
6666 return LHS;
6667 if (ResQT == RHSBaseQT)
6668 return RHS;
6669 }
6670 return QualType();
6671}
6672
Chris Lattner4ba0cef2008-04-07 07:01:58 +00006673//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006674// Integer Predicates
6675//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00006676
Jay Foad39c79802011-01-12 09:06:06 +00006677unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00006678 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00006679 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00006680 if (T->isBooleanType())
6681 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00006682 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006683 return (unsigned)getTypeSize(T);
6684}
6685
6686QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006687 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00006688
6689 // Turn <4 x signed int> -> <4 x unsigned int>
6690 if (const VectorType *VTy = T->getAs<VectorType>())
6691 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00006692 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00006693
6694 // For enums, we return the unsigned version of the base type.
6695 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006696 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00006697
6698 const BuiltinType *BTy = T->getAs<BuiltinType>();
6699 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006700 switch (BTy->getKind()) {
6701 case BuiltinType::Char_S:
6702 case BuiltinType::SChar:
6703 return UnsignedCharTy;
6704 case BuiltinType::Short:
6705 return UnsignedShortTy;
6706 case BuiltinType::Int:
6707 return UnsignedIntTy;
6708 case BuiltinType::Long:
6709 return UnsignedLongTy;
6710 case BuiltinType::LongLong:
6711 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00006712 case BuiltinType::Int128:
6713 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006714 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006715 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006716 }
6717}
6718
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00006719ASTMutationListener::~ASTMutationListener() { }
6720
Chris Lattnerecd79c62009-06-14 00:45:47 +00006721
6722//===----------------------------------------------------------------------===//
6723// Builtin Type Computation
6724//===----------------------------------------------------------------------===//
6725
6726/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00006727/// pointer over the consumed characters. This returns the resultant type. If
6728/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6729/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6730/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006731///
6732/// RequiresICE is filled in on return to indicate whether the value is required
6733/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00006734static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00006735 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006736 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00006737 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00006738 // Modifiers.
6739 int HowLong = 0;
6740 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006741 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00006742
Chris Lattnerdc226c22010-10-01 22:42:38 +00006743 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00006744 bool Done = false;
6745 while (!Done) {
6746 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00006747 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00006748 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006749 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00006750 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006751 case 'S':
6752 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6753 assert(!Signed && "Can't use 'S' modifier multiple times!");
6754 Signed = true;
6755 break;
6756 case 'U':
6757 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6758 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6759 Unsigned = true;
6760 break;
6761 case 'L':
6762 assert(HowLong <= 2 && "Can't have LLLL modifier");
6763 ++HowLong;
6764 break;
6765 }
6766 }
6767
6768 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00006769
Chris Lattnerecd79c62009-06-14 00:45:47 +00006770 // Read the base type.
6771 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00006772 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006773 case 'v':
6774 assert(HowLong == 0 && !Signed && !Unsigned &&
6775 "Bad modifiers used with 'v'!");
6776 Type = Context.VoidTy;
6777 break;
6778 case 'f':
6779 assert(HowLong == 0 && !Signed && !Unsigned &&
6780 "Bad modifiers used with 'f'!");
6781 Type = Context.FloatTy;
6782 break;
6783 case 'd':
6784 assert(HowLong < 2 && !Signed && !Unsigned &&
6785 "Bad modifiers used with 'd'!");
6786 if (HowLong)
6787 Type = Context.LongDoubleTy;
6788 else
6789 Type = Context.DoubleTy;
6790 break;
6791 case 's':
6792 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6793 if (Unsigned)
6794 Type = Context.UnsignedShortTy;
6795 else
6796 Type = Context.ShortTy;
6797 break;
6798 case 'i':
6799 if (HowLong == 3)
6800 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6801 else if (HowLong == 2)
6802 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6803 else if (HowLong == 1)
6804 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6805 else
6806 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6807 break;
6808 case 'c':
6809 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6810 if (Signed)
6811 Type = Context.SignedCharTy;
6812 else if (Unsigned)
6813 Type = Context.UnsignedCharTy;
6814 else
6815 Type = Context.CharTy;
6816 break;
6817 case 'b': // boolean
6818 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6819 Type = Context.BoolTy;
6820 break;
6821 case 'z': // size_t.
6822 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6823 Type = Context.getSizeType();
6824 break;
6825 case 'F':
6826 Type = Context.getCFConstantStringType();
6827 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00006828 case 'G':
6829 Type = Context.getObjCIdType();
6830 break;
6831 case 'H':
6832 Type = Context.getObjCSelType();
6833 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006834 case 'a':
6835 Type = Context.getBuiltinVaListType();
6836 assert(!Type.isNull() && "builtin va list type not initialized!");
6837 break;
6838 case 'A':
6839 // This is a "reference" to a va_list; however, what exactly
6840 // this means depends on how va_list is defined. There are two
6841 // different kinds of va_list: ones passed by value, and ones
6842 // passed by reference. An example of a by-value va_list is
6843 // x86, where va_list is a char*. An example of by-ref va_list
6844 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6845 // we want this argument to be a char*&; for x86-64, we want
6846 // it to be a __va_list_tag*.
6847 Type = Context.getBuiltinVaListType();
6848 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006849 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00006850 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006851 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00006852 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006853 break;
6854 case 'V': {
6855 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006856 unsigned NumElements = strtoul(Str, &End, 10);
6857 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006858 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00006859
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006860 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6861 RequiresICE, false);
6862 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00006863
6864 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00006865 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00006866 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006867 break;
6868 }
Douglas Gregorfed66992012-06-07 18:08:25 +00006869 case 'E': {
6870 char *End;
6871
6872 unsigned NumElements = strtoul(Str, &End, 10);
6873 assert(End != Str && "Missing vector size");
6874
6875 Str = End;
6876
6877 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6878 false);
6879 Type = Context.getExtVectorType(ElementType, NumElements);
6880 break;
6881 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006882 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006883 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6884 false);
6885 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006886 Type = Context.getComplexType(ElementType);
6887 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00006888 }
6889 case 'Y' : {
6890 Type = Context.getPointerDiffType();
6891 break;
6892 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00006893 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00006894 Type = Context.getFILEType();
6895 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006896 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006897 return QualType();
6898 }
Mike Stump2adb4da2009-07-28 23:47:15 +00006899 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00006900 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00006901 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00006902 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00006903 else
6904 Type = Context.getjmp_bufType();
6905
Mike Stump2adb4da2009-07-28 23:47:15 +00006906 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006907 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00006908 return QualType();
6909 }
6910 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00006911 case 'K':
6912 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
6913 Type = Context.getucontext_tType();
6914
6915 if (Type.isNull()) {
6916 Error = ASTContext::GE_Missing_ucontext;
6917 return QualType();
6918 }
6919 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00006920 }
Mike Stump11289f42009-09-09 15:08:12 +00006921
Chris Lattnerdc226c22010-10-01 22:42:38 +00006922 // If there are modifiers and if we're allowed to parse them, go for it.
6923 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006924 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00006925 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006926 default: Done = true; --Str; break;
6927 case '*':
6928 case '&': {
6929 // Both pointers and references can have their pointee types
6930 // qualified with an address space.
6931 char *End;
6932 unsigned AddrSpace = strtoul(Str, &End, 10);
6933 if (End != Str && AddrSpace != 0) {
6934 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6935 Str = End;
6936 }
6937 if (c == '*')
6938 Type = Context.getPointerType(Type);
6939 else
6940 Type = Context.getLValueReferenceType(Type);
6941 break;
6942 }
6943 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6944 case 'C':
6945 Type = Type.withConst();
6946 break;
6947 case 'D':
6948 Type = Context.getVolatileType(Type);
6949 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00006950 case 'R':
6951 Type = Type.withRestrict();
6952 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006953 }
6954 }
Chris Lattner84733392010-10-01 07:13:18 +00006955
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006956 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00006957 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00006958
Chris Lattnerecd79c62009-06-14 00:45:47 +00006959 return Type;
6960}
6961
6962/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00006963QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006964 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00006965 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006966 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00006967
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006968 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00006969
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006970 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006971 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006972 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6973 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006974 if (Error != GE_None)
6975 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006976
6977 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6978
Chris Lattnerecd79c62009-06-14 00:45:47 +00006979 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006980 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006981 if (Error != GE_None)
6982 return QualType();
6983
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006984 // If this argument is required to be an IntegerConstantExpression and the
6985 // caller cares, fill in the bitmask we return.
6986 if (RequiresICE && IntegerConstantArgs)
6987 *IntegerConstantArgs |= 1 << ArgTypes.size();
6988
Chris Lattnerecd79c62009-06-14 00:45:47 +00006989 // Do array -> pointer decay. The builtin should use the decayed type.
6990 if (Ty->isArrayType())
6991 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00006992
Chris Lattnerecd79c62009-06-14 00:45:47 +00006993 ArgTypes.push_back(Ty);
6994 }
6995
6996 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6997 "'.' should only occur at end of builtin type list!");
6998
John McCall991eb4b2010-12-21 00:44:39 +00006999 FunctionType::ExtInfo EI;
7000 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7001
7002 bool Variadic = (TypeStr[0] == '.');
7003
7004 // We really shouldn't be making a no-proto type here, especially in C++.
7005 if (ArgTypes.empty() && Variadic)
7006 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007007
John McCalldb40c7f2010-12-14 08:05:40 +00007008 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007009 EPI.ExtInfo = EI;
7010 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007011
7012 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007013}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007014
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007015GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
7016 GVALinkage External = GVA_StrongExternal;
7017
7018 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007019 switch (L) {
7020 case NoLinkage:
7021 case InternalLinkage:
7022 case UniqueExternalLinkage:
7023 return GVA_Internal;
7024
7025 case ExternalLinkage:
7026 switch (FD->getTemplateSpecializationKind()) {
7027 case TSK_Undeclared:
7028 case TSK_ExplicitSpecialization:
7029 External = GVA_StrongExternal;
7030 break;
7031
7032 case TSK_ExplicitInstantiationDefinition:
7033 return GVA_ExplicitTemplateInstantiation;
7034
7035 case TSK_ExplicitInstantiationDeclaration:
7036 case TSK_ImplicitInstantiation:
7037 External = GVA_TemplateInstantiation;
7038 break;
7039 }
7040 }
7041
7042 if (!FD->isInlined())
7043 return External;
7044
David Blaikiebbafb8a2012-03-11 07:00:24 +00007045 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007046 // GNU or C99 inline semantics. Determine whether this symbol should be
7047 // externally visible.
7048 if (FD->isInlineDefinitionExternallyVisible())
7049 return External;
7050
7051 // C99 inline semantics, where the symbol is not externally visible.
7052 return GVA_C99Inline;
7053 }
7054
7055 // C++0x [temp.explicit]p9:
7056 // [ Note: The intent is that an inline function that is the subject of
7057 // an explicit instantiation declaration will still be implicitly
7058 // instantiated when used so that the body can be considered for
7059 // inlining, but that no out-of-line copy of the inline function would be
7060 // generated in the translation unit. -- end note ]
7061 if (FD->getTemplateSpecializationKind()
7062 == TSK_ExplicitInstantiationDeclaration)
7063 return GVA_C99Inline;
7064
7065 return GVA_CXXInline;
7066}
7067
7068GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7069 // If this is a static data member, compute the kind of template
7070 // specialization. Otherwise, this variable is not part of a
7071 // template.
7072 TemplateSpecializationKind TSK = TSK_Undeclared;
7073 if (VD->isStaticDataMember())
7074 TSK = VD->getTemplateSpecializationKind();
7075
7076 Linkage L = VD->getLinkage();
David Blaikiebbafb8a2012-03-11 07:00:24 +00007077 if (L == ExternalLinkage && getLangOpts().CPlusPlus &&
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007078 VD->getType()->getLinkage() == UniqueExternalLinkage)
7079 L = UniqueExternalLinkage;
7080
7081 switch (L) {
7082 case NoLinkage:
7083 case InternalLinkage:
7084 case UniqueExternalLinkage:
7085 return GVA_Internal;
7086
7087 case ExternalLinkage:
7088 switch (TSK) {
7089 case TSK_Undeclared:
7090 case TSK_ExplicitSpecialization:
7091 return GVA_StrongExternal;
7092
7093 case TSK_ExplicitInstantiationDeclaration:
7094 llvm_unreachable("Variable should not be instantiated");
7095 // Fall through to treat this like any other instantiation.
7096
7097 case TSK_ExplicitInstantiationDefinition:
7098 return GVA_ExplicitTemplateInstantiation;
7099
7100 case TSK_ImplicitInstantiation:
7101 return GVA_TemplateInstantiation;
7102 }
7103 }
7104
David Blaikie8a40f702012-01-17 06:56:22 +00007105 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007106}
7107
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007108bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007109 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7110 if (!VD->isFileVarDecl())
7111 return false;
Argyrios Kyrtzidisa98e8612011-09-13 21:35:00 +00007112 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007113 return false;
7114
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007115 // Weak references don't produce any output by themselves.
7116 if (D->hasAttr<WeakRefAttr>())
7117 return false;
7118
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007119 // Aliases and used decls are required.
7120 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7121 return true;
7122
7123 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7124 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007125 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007126 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007127
7128 // Constructors and destructors are required.
7129 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7130 return true;
7131
7132 // The key function for a class is required.
7133 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7134 const CXXRecordDecl *RD = MD->getParent();
7135 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7136 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
7137 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7138 return true;
7139 }
7140 }
7141
7142 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7143
7144 // static, static inline, always_inline, and extern inline functions can
7145 // always be deferred. Normal inline functions can be deferred in C99/C++.
7146 // Implicit template instantiations can also be deferred in C++.
7147 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007148 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007149 return false;
7150 return true;
7151 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007152
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007153 const VarDecl *VD = cast<VarDecl>(D);
7154 assert(VD->isFileVarDecl() && "Expected file scoped var");
7155
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007156 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7157 return false;
7158
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007159 // Structs that have non-trivial constructors or destructors are required.
7160
7161 // FIXME: Handle references.
Alexis Huntf479f1b2011-05-09 18:22:59 +00007162 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007163 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
7164 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Alexis Huntf479f1b2011-05-09 18:22:59 +00007165 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
7166 RD->hasTrivialCopyConstructor() &&
7167 RD->hasTrivialMoveConstructor() &&
7168 RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007169 return true;
7170 }
7171 }
7172
7173 GVALinkage L = GetGVALinkageForVariable(VD);
7174 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
7175 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
7176 return false;
7177 }
7178
7179 return true;
7180}
Charles Davis53c59df2010-08-16 03:33:14 +00007181
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007182CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davis99202b32010-11-09 18:04:24 +00007183 // Pass through to the C++ ABI object
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007184 return ABI->getDefaultMethodCallConv(isVariadic);
7185}
7186
7187CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
7188 if (CC == CC_C && !LangOpts.MRTD && getTargetInfo().getCXXABI() != CXXABI_Microsoft)
7189 return CC_Default;
7190 return CC;
Charles Davis99202b32010-11-09 18:04:24 +00007191}
7192
Jay Foad39c79802011-01-12 09:06:06 +00007193bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007194 // Pass through to the C++ ABI object
7195 return ABI->isNearlyEmpty(RD);
7196}
7197
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007198MangleContext *ASTContext::createMangleContext() {
Douglas Gregore8bbc122011-09-02 00:18:52 +00007199 switch (Target->getCXXABI()) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007200 case CXXABI_ARM:
7201 case CXXABI_Itanium:
7202 return createItaniumMangleContext(*this, getDiagnostics());
7203 case CXXABI_Microsoft:
7204 return createMicrosoftMangleContext(*this, getDiagnostics());
7205 }
David Blaikie83d382b2011-09-23 05:06:16 +00007206 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007207}
7208
Charles Davis53c59df2010-08-16 03:33:14 +00007209CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007210
7211size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00007212 return ASTRecordLayouts.getMemorySize()
7213 + llvm::capacity_in_bytes(ObjCLayouts)
7214 + llvm::capacity_in_bytes(KeyFunctions)
7215 + llvm::capacity_in_bytes(ObjCImpls)
7216 + llvm::capacity_in_bytes(BlockVarCopyInits)
7217 + llvm::capacity_in_bytes(DeclAttrs)
7218 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7219 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7220 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7221 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7222 + llvm::capacity_in_bytes(OverriddenMethods)
7223 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007224 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00007225 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007226}
Ted Kremenek540017e2011-10-06 05:00:56 +00007227
Douglas Gregor63798542012-02-20 19:44:39 +00007228unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7229 CXXRecordDecl *Lambda = CallOperator->getParent();
7230 return LambdaMangleContexts[Lambda->getDeclContext()]
7231 .getManglingNumber(CallOperator);
7232}
7233
7234
Ted Kremenek540017e2011-10-06 05:00:56 +00007235void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7236 ParamIndices[D] = index;
7237}
7238
7239unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7240 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7241 assert(I != ParamIndices.end() &&
7242 "ParmIndices lacks entry set by ParmVarDecl");
7243 return I->second;
7244}