blob: c02132329e6df0521a8b171b1cb31c1146befd90 [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 Gribenkob2610882012-08-14 17:17:18 +000069 // User can not attach documentation to implicit instantiations.
70 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
71 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
72 return NULL;
73 }
74
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000075 // TODO: handle comments for function parameters properly.
76 if (isa<ParmVarDecl>(D))
77 return NULL;
78
Dmitri Gribenko34df2202012-07-31 22:37:06 +000079 // TODO: we could look up template parameter documentation in the template
80 // documentation.
81 if (isa<TemplateTypeParmDecl>(D) ||
82 isa<NonTypeTemplateParmDecl>(D) ||
83 isa<TemplateTemplateParmDecl>(D))
84 return NULL;
85
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +000086 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000087
88 // If there are no comments anywhere, we won't find anything.
89 if (RawComments.empty())
90 return NULL;
91
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +000092 // Find declaration location.
93 // For Objective-C declarations we generally don't expect to have multiple
94 // declarators, thus use declaration starting location as the "declaration
95 // location".
96 // For all other declarations multiple declarators are used quite frequently,
97 // so we use the location of the identifier as the "declaration location".
98 SourceLocation DeclLoc;
99 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000100 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000101 isa<RedeclarableTemplateDecl>(D) ||
102 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000103 DeclLoc = D->getLocStart();
104 else
105 DeclLoc = D->getLocation();
106
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000107 // If the declaration doesn't map directly to a location in a file, we
108 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000109 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
110 return NULL;
111
112 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000113 ArrayRef<RawComment *>::iterator Comment;
114 {
115 // When searching for comments during parsing, the comment we are looking
116 // for is usually among the last two comments we parsed -- check them
117 // first.
118 RawComment CommentAtDeclLoc(SourceMgr, SourceRange(DeclLoc));
119 BeforeThanCompare<RawComment> Compare(SourceMgr);
120 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
121 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
122 if (!Found && RawComments.size() >= 2) {
123 MaybeBeforeDecl--;
124 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
125 }
126
127 if (Found) {
128 Comment = MaybeBeforeDecl + 1;
129 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
130 &CommentAtDeclLoc, Compare));
131 } else {
132 // Slow path.
133 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
134 &CommentAtDeclLoc, Compare);
135 }
136 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000137
138 // Decompose the location for the declaration and find the beginning of the
139 // file buffer.
140 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
141
142 // First check whether we have a trailing comment.
143 if (Comment != RawComments.end() &&
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000144 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Dmitri Gribenko44cd7e62012-07-06 23:27:33 +0000145 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000146 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000147 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000148 // Check that Doxygen trailing comment comes after the declaration, starts
149 // on the same line and in the same file as the declaration.
150 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
151 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
152 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
153 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000154 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000155 }
156 }
157
158 // The comment just after the declaration was not a trailing comment.
159 // Let's look at the previous comment.
160 if (Comment == RawComments.begin())
161 return NULL;
162 --Comment;
163
164 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000165 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000166 return NULL;
167
168 // Decompose the end of the comment.
169 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000170 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000171
172 // If the comment and the declaration aren't in the same file, then they
173 // aren't related.
174 if (DeclLocDecomp.first != CommentEndDecomp.first)
175 return NULL;
176
177 // Get the corresponding buffer.
178 bool Invalid = false;
179 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
180 &Invalid).data();
181 if (Invalid)
182 return NULL;
183
184 // Extract text between the comment and declaration.
185 StringRef Text(Buffer + CommentEndDecomp.second,
186 DeclLocDecomp.second - CommentEndDecomp.second);
187
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000188 // There should be no other declarations or preprocessor directives between
189 // comment and declaration.
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000190 if (Text.find_first_of(",;{}#@") != StringRef::npos)
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000191 return NULL;
192
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000193 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000194}
195
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000196namespace {
197/// If we have a 'templated' declaration for a template, adjust 'D' to
198/// refer to the actual template.
199const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregor35ceb272012-08-13 16:37:30 +0000200 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
201 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
202 D = FTD;
203 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
204 if (const ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
205 D = CTD;
206 }
207 // FIXME: Alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000208 return D;
209}
210} // unnamed namespace
211
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000212const RawComment *ASTContext::getRawCommentForAnyRedecl(
213 const Decl *D,
214 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000215 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000216
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000217 // Check whether we have cached a comment for this declaration already.
218 {
219 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
220 RedeclComments.find(D);
221 if (Pos != RedeclComments.end()) {
222 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000223 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
224 if (OriginalDecl)
225 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000226 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000227 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000228 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000229 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000230
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000231 // Search for comments attached to declarations in the redeclaration chain.
232 const RawComment *RC = NULL;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000233 const Decl *OriginalDeclForRC = NULL;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000234 for (Decl::redecl_iterator I = D->redecls_begin(),
235 E = D->redecls_end();
236 I != E; ++I) {
237 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
238 RedeclComments.find(*I);
239 if (Pos != RedeclComments.end()) {
240 const RawCommentAndCacheFlags &Raw = Pos->second;
241 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
242 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000243 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000244 break;
245 }
246 } else {
247 RC = getRawCommentForDeclNoCache(*I);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000248 OriginalDeclForRC = *I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000249 RawCommentAndCacheFlags Raw;
250 if (RC) {
251 Raw.setRaw(RC);
252 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
253 } else
254 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000255 Raw.setOriginalDecl(*I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000256 RedeclComments[*I] = Raw;
257 if (RC)
258 break;
259 }
260 }
261
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000262 // If we found a comment, it should be a documentation comment.
263 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000264
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000265 if (OriginalDecl)
266 *OriginalDecl = OriginalDeclForRC;
267
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000268 // Update cache for every declaration in the redeclaration chain.
269 RawCommentAndCacheFlags Raw;
270 Raw.setRaw(RC);
271 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000272 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000273
274 for (Decl::redecl_iterator I = D->redecls_begin(),
275 E = D->redecls_end();
276 I != E; ++I) {
277 RawCommentAndCacheFlags &R = RedeclComments[*I];
278 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
279 R = Raw;
280 }
281
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000282 return RC;
283}
284
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000285comments::FullComment *ASTContext::getCommentForDecl(const Decl *D) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000286 D = adjustDeclToTemplate(D);
287 const Decl *Canonical = D->getCanonicalDecl();
288 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
289 ParsedComments.find(Canonical);
290 if (Pos != ParsedComments.end())
291 return Pos->second;
292
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000293 const Decl *OriginalDecl;
294 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000295 if (!RC)
296 return NULL;
297
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000298 if (D != OriginalDecl)
299 return getCommentForDecl(OriginalDecl);
300
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000301 comments::FullComment *FC = RC->parse(*this, D);
302 ParsedComments[Canonical] = FC;
303 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000304}
305
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000306void
307ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
308 TemplateTemplateParmDecl *Parm) {
309 ID.AddInteger(Parm->getDepth());
310 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000311 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000312
313 TemplateParameterList *Params = Parm->getTemplateParameters();
314 ID.AddInteger(Params->size());
315 for (TemplateParameterList::const_iterator P = Params->begin(),
316 PEnd = Params->end();
317 P != PEnd; ++P) {
318 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
319 ID.AddInteger(0);
320 ID.AddBoolean(TTP->isParameterPack());
321 continue;
322 }
323
324 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
325 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000326 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000327 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000328 if (NTTP->isExpandedParameterPack()) {
329 ID.AddBoolean(true);
330 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000331 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
332 QualType T = NTTP->getExpansionType(I);
333 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
334 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000335 } else
336 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000337 continue;
338 }
339
340 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
341 ID.AddInteger(2);
342 Profile(ID, TTP);
343 }
344}
345
346TemplateTemplateParmDecl *
347ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000348 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000349 // Check if we already have a canonical template template parameter.
350 llvm::FoldingSetNodeID ID;
351 CanonicalTemplateTemplateParm::Profile(ID, TTP);
352 void *InsertPos = 0;
353 CanonicalTemplateTemplateParm *Canonical
354 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
355 if (Canonical)
356 return Canonical->getParam();
357
358 // Build a canonical template parameter list.
359 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000360 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000361 CanonParams.reserve(Params->size());
362 for (TemplateParameterList::const_iterator P = Params->begin(),
363 PEnd = Params->end();
364 P != PEnd; ++P) {
365 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
366 CanonParams.push_back(
367 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000368 SourceLocation(),
369 SourceLocation(),
370 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000371 TTP->getIndex(), 0, false,
372 TTP->isParameterPack()));
373 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000374 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
375 QualType T = getCanonicalType(NTTP->getType());
376 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
377 NonTypeTemplateParmDecl *Param;
378 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000379 SmallVector<QualType, 2> ExpandedTypes;
380 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000381 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
382 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
383 ExpandedTInfos.push_back(
384 getTrivialTypeSourceInfo(ExpandedTypes.back()));
385 }
386
387 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000388 SourceLocation(),
389 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000390 NTTP->getDepth(),
391 NTTP->getPosition(), 0,
392 T,
393 TInfo,
394 ExpandedTypes.data(),
395 ExpandedTypes.size(),
396 ExpandedTInfos.data());
397 } else {
398 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000399 SourceLocation(),
400 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000401 NTTP->getDepth(),
402 NTTP->getPosition(), 0,
403 T,
404 NTTP->isParameterPack(),
405 TInfo);
406 }
407 CanonParams.push_back(Param);
408
409 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000410 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
411 cast<TemplateTemplateParmDecl>(*P)));
412 }
413
414 TemplateTemplateParmDecl *CanonTTP
415 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
416 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000417 TTP->getPosition(),
418 TTP->isParameterPack(),
419 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000420 TemplateParameterList::Create(*this, SourceLocation(),
421 SourceLocation(),
422 CanonParams.data(),
423 CanonParams.size(),
424 SourceLocation()));
425
426 // Get the new insert position for the node we care about.
427 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
428 assert(Canonical == 0 && "Shouldn't be in the map!");
429 (void)Canonical;
430
431 // Create the canonical template template parameter entry.
432 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
433 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
434 return CanonTTP;
435}
436
Charles Davis53c59df2010-08-16 03:33:14 +0000437CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000438 if (!LangOpts.CPlusPlus) return 0;
439
Charles Davis6bcb07a2010-08-19 02:18:14 +0000440 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000441 case CXXABI_ARM:
442 return CreateARMCXXABI(*this);
443 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000444 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000445 case CXXABI_Microsoft:
446 return CreateMicrosoftCXXABI(*this);
447 }
David Blaikie8a40f702012-01-17 06:56:22 +0000448 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000449}
450
Douglas Gregore8bbc122011-09-02 00:18:52 +0000451static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000452 const LangOptions &LOpts) {
453 if (LOpts.FakeAddressSpaceMap) {
454 // The fake address space map must have a distinct entry for each
455 // language-specific address space.
456 static const unsigned FakeAddrSpaceMap[] = {
457 1, // opencl_global
458 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000459 3, // opencl_constant
460 4, // cuda_device
461 5, // cuda_constant
462 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000463 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000464 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000465 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000466 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000467 }
468}
469
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000470ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000471 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000472 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000473 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000474 unsigned size_reserve,
475 bool DelayInitialization)
476 : FunctionProtoTypes(this_()),
477 TemplateSpecializationTypes(this_()),
478 DependentTemplateSpecializationTypes(this_()),
479 SubstTemplateTemplateParmPacks(this_()),
480 GlobalNestedNameSpecifier(0),
481 Int128Decl(0), UInt128Decl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000482 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000483 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000484 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000485 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000486 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
487 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
488 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000489 NullTypeSourceInfo(QualType()),
490 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000491 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000492 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000493 Idents(idents), Selectors(sels),
494 BuiltinInfo(builtins),
495 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000496 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000497 Comments(SM), CommentsLoaded(false),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000498 LastSDM(0, 0),
499 UniqueBlockByRefTypeID(0)
500{
Mike Stump11289f42009-09-09 15:08:12 +0000501 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000502 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000503
504 if (!DelayInitialization) {
505 assert(t && "No target supplied for ASTContext initialization");
506 InitBuiltinTypes(*t);
507 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000508}
509
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000510ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000511 // Release the DenseMaps associated with DeclContext objects.
512 // FIXME: Is this the ideal solution?
513 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000514
Douglas Gregor5b11d492010-07-25 17:53:33 +0000515 // Call all of the deallocation functions.
516 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
517 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000518
Ted Kremenek076baeb2010-06-08 23:00:58 +0000519 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000520 // because they can contain DenseMaps.
521 for (llvm::DenseMap<const ObjCContainerDecl*,
522 const ASTRecordLayout*>::iterator
523 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
524 // Increment in loop to prevent using deallocated memory.
525 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
526 R->Destroy(*this);
527
Ted Kremenek076baeb2010-06-08 23:00:58 +0000528 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
529 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
530 // Increment in loop to prevent using deallocated memory.
531 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
532 R->Destroy(*this);
533 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000534
535 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
536 AEnd = DeclAttrs.end();
537 A != AEnd; ++A)
538 A->second->~AttrVec();
539}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000540
Douglas Gregor1a809332010-05-23 18:26:36 +0000541void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
542 Deallocations.push_back(std::make_pair(Callback, Data));
543}
544
Mike Stump11289f42009-09-09 15:08:12 +0000545void
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000546ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000547 ExternalSource.reset(Source.take());
548}
549
Chris Lattner4eb445d2007-01-26 01:27:23 +0000550void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000551 llvm::errs() << "\n*** AST Context Stats:\n";
552 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000553
Douglas Gregora30d0462009-05-26 14:40:08 +0000554 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000555#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000556#define ABSTRACT_TYPE(Name, Parent)
557#include "clang/AST/TypeNodes.def"
558 0 // Extra
559 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000560
Chris Lattner4eb445d2007-01-26 01:27:23 +0000561 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
562 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000563 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000564 }
565
Douglas Gregora30d0462009-05-26 14:40:08 +0000566 unsigned Idx = 0;
567 unsigned TotalBytes = 0;
568#define TYPE(Name, Parent) \
569 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000570 llvm::errs() << " " << counts[Idx] << " " << #Name \
571 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000572 TotalBytes += counts[Idx] * sizeof(Name##Type); \
573 ++Idx;
574#define ABSTRACT_TYPE(Name, Parent)
575#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000576
Chandler Carruth3c147a72011-07-04 05:32:14 +0000577 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
578
Douglas Gregor7454c562010-07-02 20:37:36 +0000579 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000580 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
581 << NumImplicitDefaultConstructors
582 << " implicit default constructors created\n";
583 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
584 << NumImplicitCopyConstructors
585 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000586 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000587 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
588 << NumImplicitMoveConstructors
589 << " implicit move constructors created\n";
590 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
591 << NumImplicitCopyAssignmentOperators
592 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000593 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000594 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
595 << NumImplicitMoveAssignmentOperators
596 << " implicit move assignment operators created\n";
597 llvm::errs() << NumImplicitDestructorsDeclared << "/"
598 << NumImplicitDestructors
599 << " implicit destructors created\n";
600
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000601 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000602 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000603 ExternalSource->PrintStats();
604 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000605
Douglas Gregor5b11d492010-07-25 17:53:33 +0000606 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000607}
608
Douglas Gregor801c99d2011-08-12 06:49:56 +0000609TypedefDecl *ASTContext::getInt128Decl() const {
610 if (!Int128Decl) {
611 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
612 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
613 getTranslationUnitDecl(),
614 SourceLocation(),
615 SourceLocation(),
616 &Idents.get("__int128_t"),
617 TInfo);
618 }
619
620 return Int128Decl;
621}
622
623TypedefDecl *ASTContext::getUInt128Decl() const {
624 if (!UInt128Decl) {
625 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
626 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
627 getTranslationUnitDecl(),
628 SourceLocation(),
629 SourceLocation(),
630 &Idents.get("__uint128_t"),
631 TInfo);
632 }
633
634 return UInt128Decl;
635}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000636
John McCall48f2d582009-10-23 23:03:21 +0000637void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000638 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000639 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000640 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000641}
642
Douglas Gregore8bbc122011-09-02 00:18:52 +0000643void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
644 assert((!this->Target || this->Target == &Target) &&
645 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000646 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000647
Douglas Gregore8bbc122011-09-02 00:18:52 +0000648 this->Target = &Target;
649
650 ABI.reset(createCXXABI(Target));
651 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
652
Chris Lattner970e54e2006-11-12 00:37:36 +0000653 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000654 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000655
Chris Lattner970e54e2006-11-12 00:37:36 +0000656 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000657 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000658 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000659 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000660 InitBuiltinType(CharTy, BuiltinType::Char_S);
661 else
662 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000663 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000664 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
665 InitBuiltinType(ShortTy, BuiltinType::Short);
666 InitBuiltinType(IntTy, BuiltinType::Int);
667 InitBuiltinType(LongTy, BuiltinType::Long);
668 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000669
Chris Lattner970e54e2006-11-12 00:37:36 +0000670 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000671 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
672 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
673 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
674 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
675 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000676
Chris Lattner970e54e2006-11-12 00:37:36 +0000677 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000678 InitBuiltinType(FloatTy, BuiltinType::Float);
679 InitBuiltinType(DoubleTy, BuiltinType::Double);
680 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000681
Chris Lattnerf122cef2009-04-30 02:43:43 +0000682 // GNU extension, 128-bit integers.
683 InitBuiltinType(Int128Ty, BuiltinType::Int128);
684 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
685
Chris Lattnerad3467e2010-12-25 23:25:43 +0000686 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedman786d0872011-04-30 19:24:24 +0000687 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000688 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
689 else // -fshort-wchar makes wchar_t be unsigned.
690 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
691 } else // C99
Chris Lattner007cb022009-02-26 23:43:47 +0000692 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000693
James Molloy36365542012-05-04 10:55:22 +0000694 WIntTy = getFromTargetType(Target.getWIntType());
695
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000696 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
697 InitBuiltinType(Char16Ty, BuiltinType::Char16);
698 else // C99
699 Char16Ty = getFromTargetType(Target.getChar16Type());
700
701 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
702 InitBuiltinType(Char32Ty, BuiltinType::Char32);
703 else // C99
704 Char32Ty = getFromTargetType(Target.getChar32Type());
705
Douglas Gregor4619e432008-12-05 23:32:09 +0000706 // Placeholder type for type-dependent expressions whose type is
707 // completely unknown. No code should ever check a type against
708 // DependentTy and users should never see it; however, it is here to
709 // help diagnose failures to properly check for type-dependent
710 // expressions.
711 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000712
John McCall36e7fe32010-10-12 00:20:44 +0000713 // Placeholder type for functions.
714 InitBuiltinType(OverloadTy, BuiltinType::Overload);
715
John McCall0009fcc2011-04-26 20:42:42 +0000716 // Placeholder type for bound members.
717 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
718
John McCall526ab472011-10-25 17:37:35 +0000719 // Placeholder type for pseudo-objects.
720 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
721
John McCall31996342011-04-07 08:22:57 +0000722 // "any" type; useful for debugger-like clients.
723 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
724
John McCall8a6b59a2011-10-17 18:09:15 +0000725 // Placeholder type for unbridged ARC casts.
726 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
727
Chris Lattner970e54e2006-11-12 00:37:36 +0000728 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000729 FloatComplexTy = getComplexType(FloatTy);
730 DoubleComplexTy = getComplexType(DoubleTy);
731 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000732
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000733 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000734 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
735 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000736 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000737
738 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +0000739 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
740 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000741
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000742 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000743
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000744 // void * type
745 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000746
747 // nullptr type (C++0x 2.14.7)
748 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000749
750 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
751 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +0000752
753 // Builtin type used to help define __builtin_va_list.
754 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +0000755}
756
David Blaikie9c902b52011-09-25 23:23:43 +0000757DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000758 return SourceMgr.getDiagnostics();
759}
760
Douglas Gregor561eceb2010-08-30 16:49:28 +0000761AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
762 AttrVec *&Result = DeclAttrs[D];
763 if (!Result) {
764 void *Mem = Allocate(sizeof(AttrVec));
765 Result = new (Mem) AttrVec;
766 }
767
768 return *Result;
769}
770
771/// \brief Erase the attributes corresponding to the given declaration.
772void ASTContext::eraseDeclAttrs(const Decl *D) {
773 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
774 if (Pos != DeclAttrs.end()) {
775 Pos->second->~AttrVec();
776 DeclAttrs.erase(Pos);
777 }
778}
779
Douglas Gregor86d142a2009-10-08 07:24:58 +0000780MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000781ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000782 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000783 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000784 = InstantiatedFromStaticDataMember.find(Var);
785 if (Pos == InstantiatedFromStaticDataMember.end())
786 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000787
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000788 return Pos->second;
789}
790
Mike Stump11289f42009-09-09 15:08:12 +0000791void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000792ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000793 TemplateSpecializationKind TSK,
794 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000795 assert(Inst->isStaticDataMember() && "Not a static data member");
796 assert(Tmpl->isStaticDataMember() && "Not a static data member");
797 assert(!InstantiatedFromStaticDataMember[Inst] &&
798 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000799 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000800 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000801}
802
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000803FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
804 const FunctionDecl *FD){
805 assert(FD && "Specialization is 0");
806 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +0000807 = ClassScopeSpecializationPattern.find(FD);
808 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000809 return 0;
810
811 return Pos->second;
812}
813
814void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
815 FunctionDecl *Pattern) {
816 assert(FD && "Specialization is 0");
817 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +0000818 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000819}
820
John McCalle61f2ba2009-11-18 02:36:19 +0000821NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000822ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000823 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000824 = InstantiatedFromUsingDecl.find(UUD);
825 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000826 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000827
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000828 return Pos->second;
829}
830
831void
John McCallb96ec562009-12-04 22:46:56 +0000832ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
833 assert((isa<UsingDecl>(Pattern) ||
834 isa<UnresolvedUsingValueDecl>(Pattern) ||
835 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
836 "pattern decl is not a using decl");
837 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
838 InstantiatedFromUsingDecl[Inst] = Pattern;
839}
840
841UsingShadowDecl *
842ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
843 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
844 = InstantiatedFromUsingShadowDecl.find(Inst);
845 if (Pos == InstantiatedFromUsingShadowDecl.end())
846 return 0;
847
848 return Pos->second;
849}
850
851void
852ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
853 UsingShadowDecl *Pattern) {
854 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
855 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000856}
857
Anders Carlsson5da84842009-09-01 04:26:58 +0000858FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
859 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
860 = InstantiatedFromUnnamedFieldDecl.find(Field);
861 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
862 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000863
Anders Carlsson5da84842009-09-01 04:26:58 +0000864 return Pos->second;
865}
866
867void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
868 FieldDecl *Tmpl) {
869 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
870 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
871 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
872 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000873
Anders Carlsson5da84842009-09-01 04:26:58 +0000874 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
875}
876
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000877bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
878 const FieldDecl *LastFD) const {
879 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000880 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000881}
882
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000883bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
884 const FieldDecl *LastFD) const {
885 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000886 FD->getBitWidthValue(*this) == 0 &&
887 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000888}
889
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000890bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
891 const FieldDecl *LastFD) const {
892 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000893 FD->getBitWidthValue(*this) &&
894 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000895}
896
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000897bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000898 const FieldDecl *LastFD) const {
899 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000900 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000901}
902
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000903bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000904 const FieldDecl *LastFD) const {
905 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000906 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000907}
908
Douglas Gregor832940b2010-03-02 23:58:15 +0000909ASTContext::overridden_cxx_method_iterator
910ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
911 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
912 = OverriddenMethods.find(Method);
913 if (Pos == OverriddenMethods.end())
914 return 0;
915
916 return Pos->second.begin();
917}
918
919ASTContext::overridden_cxx_method_iterator
920ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
921 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
922 = OverriddenMethods.find(Method);
923 if (Pos == OverriddenMethods.end())
924 return 0;
925
926 return Pos->second.end();
927}
928
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000929unsigned
930ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
931 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
932 = OverriddenMethods.find(Method);
933 if (Pos == OverriddenMethods.end())
934 return 0;
935
936 return Pos->second.size();
937}
938
Douglas Gregor832940b2010-03-02 23:58:15 +0000939void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
940 const CXXMethodDecl *Overridden) {
941 OverriddenMethods[Method].push_back(Overridden);
942}
943
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000944void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
945 assert(!Import->NextLocalImport && "Import declaration already in the chain");
946 assert(!Import->isFromASTFile() && "Non-local import declaration");
947 if (!FirstLocalImport) {
948 FirstLocalImport = Import;
949 LastLocalImport = Import;
950 return;
951 }
952
953 LastLocalImport->NextLocalImport = Import;
954 LastLocalImport = Import;
955}
956
Chris Lattner53cfe802007-07-18 17:52:12 +0000957//===----------------------------------------------------------------------===//
958// Type Sizing and Analysis
959//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000960
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000961/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
962/// scalar floating point type.
963const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000964 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000965 assert(BT && "Not a floating point type!");
966 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +0000967 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000968 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +0000969 case BuiltinType::Float: return Target->getFloatFormat();
970 case BuiltinType::Double: return Target->getDoubleFormat();
971 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000972 }
973}
974
Ken Dyck160146e2010-01-27 17:10:57 +0000975/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000976/// specified decl. Note that bitfields do not have a valid alignment, so
977/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000978/// If @p RefAsPointee, references are treated like their underlying type
979/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000980CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000981 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +0000982
John McCall94268702010-10-08 18:24:19 +0000983 bool UseAlignAttrOnly = false;
984 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
985 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000986
John McCall94268702010-10-08 18:24:19 +0000987 // __attribute__((aligned)) can increase or decrease alignment
988 // *except* on a struct or struct member, where it only increases
989 // alignment unless 'packed' is also specified.
990 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +0000991 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +0000992 // ignore that possibility; Sema should diagnose it.
993 if (isa<FieldDecl>(D)) {
994 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
995 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
996 } else {
997 UseAlignAttrOnly = true;
998 }
999 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001000 else if (isa<FieldDecl>(D))
1001 UseAlignAttrOnly =
1002 D->hasAttr<PackedAttr>() ||
1003 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001004
John McCall4e819612011-01-20 07:57:12 +00001005 // If we're using the align attribute only, just ignore everything
1006 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001007 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001008 // do nothing
1009
John McCall94268702010-10-08 18:24:19 +00001010 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001011 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001012 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001013 if (RefAsPointee)
1014 T = RT->getPointeeType();
1015 else
1016 T = getPointerType(RT->getPointeeType());
1017 }
1018 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001019 // Adjust alignments of declarations with array type by the
1020 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +00001021 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +00001022 const ArrayType *arrayType;
1023 if (MinWidth && (arrayType = getAsArrayType(T))) {
1024 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001025 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +00001026 else if (isa<ConstantArrayType>(arrayType) &&
1027 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001028 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +00001029
John McCall33ddac02011-01-19 10:06:00 +00001030 // Walk through any array types while we're at it.
1031 T = getBaseElementType(arrayType);
1032 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001033 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +00001034 }
John McCall4e819612011-01-20 07:57:12 +00001035
1036 // Fields can be subject to extra alignment constraints, like if
1037 // the field is packed, the struct is packed, or the struct has a
1038 // a max-field-alignment constraint (#pragma pack). So calculate
1039 // the actual alignment of the field within the struct, and then
1040 // (as we're expected to) constrain that by the alignment of the type.
1041 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
1042 // So calculate the alignment of the field.
1043 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
1044
1045 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +00001046 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001047
1048 // Use the GCD of that and the offset within the record.
1049 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
1050 if (offset > 0) {
1051 // Alignment is always a power of 2, so the GCD will be a power of 2,
1052 // which means we get to do this crazy thing instead of Euclid's.
1053 uint64_t lowBitOfOffset = offset & (~offset + 1);
1054 if (lowBitOfOffset < fieldAlign)
1055 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
1056 }
1057
1058 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +00001059 }
Chris Lattner68061312009-01-24 21:53:27 +00001060 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001061
Ken Dyckcc56c542011-01-15 18:38:59 +00001062 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001063}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001064
John McCall87fe5d52010-05-20 01:18:31 +00001065std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001066ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001067 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +00001068 return std::make_pair(toCharUnitsFromBits(Info.first),
1069 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +00001070}
1071
1072std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001073ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001074 return getTypeInfoInChars(T.getTypePtr());
1075}
1076
Daniel Dunbarc6475872012-03-09 04:12:54 +00001077std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1078 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1079 if (it != MemoizedTypeInfo.end())
1080 return it->second;
1081
1082 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1083 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1084 return Info;
1085}
1086
1087/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1088/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001089///
1090/// FIXME: Pointers into different addr spaces could have different sizes and
1091/// alignment requirements: getPointerInfo should take an AddrSpace, this
1092/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +00001093std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +00001094ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +00001095 uint64_t Width=0;
1096 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001097 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001098#define TYPE(Class, Base)
1099#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001100#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001101#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1102#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001103 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001104
Chris Lattner355332d2007-07-13 22:27:08 +00001105 case Type::FunctionNoProto:
1106 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001107 // GCC extension: alignof(function) = 32 bits
1108 Width = 0;
1109 Align = 32;
1110 break;
1111
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001112 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001113 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001114 Width = 0;
1115 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1116 break;
1117
Steve Naroff5c131802007-08-30 01:06:46 +00001118 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001119 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001120
Chris Lattner37e05872008-03-05 18:54:05 +00001121 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001122 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +00001123 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1124 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001125 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001126 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +00001127 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001128 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001129 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001130 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001131 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001132 const VectorType *VT = cast<VectorType>(T);
1133 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1134 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001135 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001136 // If the alignment is not a power of 2, round up to the next power of 2.
1137 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001138 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001139 Align = llvm::NextPowerOf2(Align);
1140 Width = llvm::RoundUpToAlignment(Width, Align);
1141 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001142 // Adjust the alignment based on the target max.
1143 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1144 if (TargetVectorAlign && TargetVectorAlign < Align)
1145 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001146 break;
1147 }
Chris Lattner647fb222007-07-18 18:26:58 +00001148
Chris Lattner7570e9c2008-03-08 08:52:55 +00001149 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001150 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001151 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001152 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001153 // GCC extension: alignof(void) = 8 bits.
1154 Width = 0;
1155 Align = 8;
1156 break;
1157
Chris Lattner6a4f7452007-12-19 19:23:28 +00001158 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001159 Width = Target->getBoolWidth();
1160 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001161 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001162 case BuiltinType::Char_S:
1163 case BuiltinType::Char_U:
1164 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001165 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001166 Width = Target->getCharWidth();
1167 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001168 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001169 case BuiltinType::WChar_S:
1170 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001171 Width = Target->getWCharWidth();
1172 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001173 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001174 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001175 Width = Target->getChar16Width();
1176 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001177 break;
1178 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001179 Width = Target->getChar32Width();
1180 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001181 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001182 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001183 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001184 Width = Target->getShortWidth();
1185 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001186 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001187 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001188 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001189 Width = Target->getIntWidth();
1190 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001191 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001192 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001193 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001194 Width = Target->getLongWidth();
1195 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001196 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001197 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001198 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001199 Width = Target->getLongLongWidth();
1200 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001201 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001202 case BuiltinType::Int128:
1203 case BuiltinType::UInt128:
1204 Width = 128;
1205 Align = 128; // int128_t is 128-bit aligned on all targets.
1206 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001207 case BuiltinType::Half:
1208 Width = Target->getHalfWidth();
1209 Align = Target->getHalfAlign();
1210 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001211 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001212 Width = Target->getFloatWidth();
1213 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001214 break;
1215 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001216 Width = Target->getDoubleWidth();
1217 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001218 break;
1219 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001220 Width = Target->getLongDoubleWidth();
1221 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001222 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001223 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001224 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1225 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001226 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001227 case BuiltinType::ObjCId:
1228 case BuiltinType::ObjCClass:
1229 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001230 Width = Target->getPointerWidth(0);
1231 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001232 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001233 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001234 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001235 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001236 Width = Target->getPointerWidth(0);
1237 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001238 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001239 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001240 unsigned AS = getTargetAddressSpace(
1241 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001242 Width = Target->getPointerWidth(AS);
1243 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001244 break;
1245 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001246 case Type::LValueReference:
1247 case Type::RValueReference: {
1248 // alignof and sizeof should never enter this code path here, so we go
1249 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001250 unsigned AS = getTargetAddressSpace(
1251 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001252 Width = Target->getPointerWidth(AS);
1253 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001254 break;
1255 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001256 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001257 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001258 Width = Target->getPointerWidth(AS);
1259 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001260 break;
1261 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001262 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001263 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001264 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +00001265 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +00001266 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001267 Align = PtrDiffInfo.second;
1268 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001269 }
Chris Lattner647fb222007-07-18 18:26:58 +00001270 case Type::Complex: {
1271 // Complex types have the same alignment as their elements, but twice the
1272 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001273 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001274 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001275 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001276 Align = EltInfo.second;
1277 break;
1278 }
John McCall8b07ec22010-05-15 11:32:37 +00001279 case Type::ObjCObject:
1280 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001281 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001282 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001283 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001284 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001285 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001286 break;
1287 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001288 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001289 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001290 const TagType *TT = cast<TagType>(T);
1291
1292 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001293 Width = 8;
1294 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001295 break;
1296 }
Mike Stump11289f42009-09-09 15:08:12 +00001297
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001298 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001299 return getTypeInfo(ET->getDecl()->getIntegerType());
1300
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001301 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001302 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001303 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001304 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001305 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001306 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001307
Chris Lattner63d2b362009-10-22 05:17:15 +00001308 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001309 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1310 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001311
Richard Smith30482bc2011-02-20 03:19:35 +00001312 case Type::Auto: {
1313 const AutoType *A = cast<AutoType>(T);
1314 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001315 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001316 }
1317
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001318 case Type::Paren:
1319 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1320
Douglas Gregoref462e62009-04-30 17:32:17 +00001321 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001322 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001323 std::pair<uint64_t, unsigned> Info
1324 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001325 // If the typedef has an aligned attribute on it, it overrides any computed
1326 // alignment we have. This violates the GCC documentation (which says that
1327 // attribute(aligned) can only round up) but matches its implementation.
1328 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1329 Align = AttrAlign;
1330 else
1331 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001332 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001333 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001334 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001335
1336 case Type::TypeOfExpr:
1337 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1338 .getTypePtr());
1339
1340 case Type::TypeOf:
1341 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1342
Anders Carlsson81df7b82009-06-24 19:06:50 +00001343 case Type::Decltype:
1344 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1345 .getTypePtr());
1346
Alexis Hunte852b102011-05-24 22:41:36 +00001347 case Type::UnaryTransform:
1348 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1349
Abramo Bagnara6150c882010-05-11 21:36:43 +00001350 case Type::Elaborated:
1351 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001352
John McCall81904512011-01-06 01:58:22 +00001353 case Type::Attributed:
1354 return getTypeInfo(
1355 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1356
Richard Smith3f1b5d02011-05-05 21:57:07 +00001357 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001358 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001359 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001360 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1361 // A type alias template specialization may refer to a typedef with the
1362 // aligned attribute on it.
1363 if (TST->isTypeAlias())
1364 return getTypeInfo(TST->getAliasedType().getTypePtr());
1365 else
1366 return getTypeInfo(getCanonicalType(T));
1367 }
1368
Eli Friedman0dfb8892011-10-06 23:00:33 +00001369 case Type::Atomic: {
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001370 std::pair<uint64_t, unsigned> Info
1371 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1372 Width = Info.first;
1373 Align = Info.second;
1374 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1375 llvm::isPowerOf2_64(Width)) {
1376 // We can potentially perform lock-free atomic operations for this
1377 // type; promote the alignment appropriately.
1378 // FIXME: We could potentially promote the width here as well...
1379 // is that worthwhile? (Non-struct atomic types generally have
1380 // power-of-two size anyway, but structs might not. Requires a bit
1381 // of implementation work to make sure we zero out the extra bits.)
1382 Align = static_cast<unsigned>(Width);
1383 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001384 }
1385
Douglas Gregoref462e62009-04-30 17:32:17 +00001386 }
Mike Stump11289f42009-09-09 15:08:12 +00001387
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001388 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001389 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001390}
1391
Ken Dyckcc56c542011-01-15 18:38:59 +00001392/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1393CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1394 return CharUnits::fromQuantity(BitSize / getCharWidth());
1395}
1396
Ken Dyckb0fcc592011-02-11 01:54:29 +00001397/// toBits - Convert a size in characters to a size in characters.
1398int64_t ASTContext::toBits(CharUnits CharSize) const {
1399 return CharSize.getQuantity() * getCharWidth();
1400}
1401
Ken Dyck8c89d592009-12-22 14:23:30 +00001402/// getTypeSizeInChars - Return the size of the specified type, in characters.
1403/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001404CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001405 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001406}
Jay Foad39c79802011-01-12 09:06:06 +00001407CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001408 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001409}
1410
Ken Dycka6046ab2010-01-26 17:25:18 +00001411/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001412/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001413CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001414 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001415}
Jay Foad39c79802011-01-12 09:06:06 +00001416CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001417 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001418}
1419
Chris Lattnera3402cd2009-01-27 18:08:34 +00001420/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1421/// type for the current target in bits. This can be different than the ABI
1422/// alignment in cases where it is beneficial for performance to overalign
1423/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001424unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001425 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001426
1427 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001428 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001429 T = CT->getElementType().getTypePtr();
1430 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001431 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1432 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001433 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1434
Chris Lattnera3402cd2009-01-27 18:08:34 +00001435 return ABIAlign;
1436}
1437
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001438/// DeepCollectObjCIvars -
1439/// This routine first collects all declared, but not synthesized, ivars in
1440/// super class and then collects all ivars, including those synthesized for
1441/// current class. This routine is used for implementation of current class
1442/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001443///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001444void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1445 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001446 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001447 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1448 DeepCollectObjCIvars(SuperClass, false, Ivars);
1449 if (!leafClass) {
1450 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1451 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001452 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001453 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001454 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001455 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001456 Iv= Iv->getNextIvar())
1457 Ivars.push_back(Iv);
1458 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001459}
1460
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001461/// CollectInheritedProtocols - Collect all protocols in current class and
1462/// those inherited by it.
1463void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001464 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001465 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001466 // We can use protocol_iterator here instead of
1467 // all_referenced_protocol_iterator since we are walking all categories.
1468 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1469 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001470 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001471 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001472 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001473 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001474 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001475 CollectInheritedProtocols(*P, Protocols);
1476 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001477 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001478
1479 // Categories of this Interface.
1480 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1481 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1482 CollectInheritedProtocols(CDeclChain, Protocols);
1483 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1484 while (SD) {
1485 CollectInheritedProtocols(SD, Protocols);
1486 SD = SD->getSuperClass();
1487 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001488 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001489 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001490 PE = OC->protocol_end(); P != PE; ++P) {
1491 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001492 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001493 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1494 PE = Proto->protocol_end(); P != PE; ++P)
1495 CollectInheritedProtocols(*P, Protocols);
1496 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001497 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001498 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1499 PE = OP->protocol_end(); P != PE; ++P) {
1500 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001501 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001502 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1503 PE = Proto->protocol_end(); P != PE; ++P)
1504 CollectInheritedProtocols(*P, Protocols);
1505 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001506 }
1507}
1508
Jay Foad39c79802011-01-12 09:06:06 +00001509unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001510 unsigned count = 0;
1511 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001512 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1513 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001514 count += CDecl->ivar_size();
1515
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001516 // Count ivar defined in this class's implementation. This
1517 // includes synthesized ivars.
1518 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001519 count += ImplDecl->ivar_size();
1520
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001521 return count;
1522}
1523
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001524bool ASTContext::isSentinelNullExpr(const Expr *E) {
1525 if (!E)
1526 return false;
1527
1528 // nullptr_t is always treated as null.
1529 if (E->getType()->isNullPtrType()) return true;
1530
1531 if (E->getType()->isAnyPointerType() &&
1532 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1533 Expr::NPC_ValueDependentIsNull))
1534 return true;
1535
1536 // Unfortunately, __null has type 'int'.
1537 if (isa<GNUNullExpr>(E)) return true;
1538
1539 return false;
1540}
1541
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001542/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1543ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1544 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1545 I = ObjCImpls.find(D);
1546 if (I != ObjCImpls.end())
1547 return cast<ObjCImplementationDecl>(I->second);
1548 return 0;
1549}
1550/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1551ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1552 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1553 I = ObjCImpls.find(D);
1554 if (I != ObjCImpls.end())
1555 return cast<ObjCCategoryImplDecl>(I->second);
1556 return 0;
1557}
1558
1559/// \brief Set the implementation of ObjCInterfaceDecl.
1560void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1561 ObjCImplementationDecl *ImplD) {
1562 assert(IFaceD && ImplD && "Passed null params");
1563 ObjCImpls[IFaceD] = ImplD;
1564}
1565/// \brief Set the implementation of ObjCCategoryDecl.
1566void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1567 ObjCCategoryImplDecl *ImplD) {
1568 assert(CatD && ImplD && "Passed null params");
1569 ObjCImpls[CatD] = ImplD;
1570}
1571
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001572ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1573 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1574 return ID;
1575 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1576 return CD->getClassInterface();
1577 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1578 return IMD->getClassInterface();
1579
1580 return 0;
1581}
1582
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001583/// \brief Get the copy initialization expression of VarDecl,or NULL if
1584/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001585Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001586 assert(VD && "Passed null params");
1587 assert(VD->hasAttr<BlocksAttr>() &&
1588 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001589 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001590 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001591 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1592}
1593
1594/// \brief Set the copy inialization expression of a block var decl.
1595void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1596 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001597 assert(VD->hasAttr<BlocksAttr>() &&
1598 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001599 BlockVarCopyInits[VD] = Init;
1600}
1601
John McCallbcd03502009-12-07 02:54:59 +00001602TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001603 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001604 if (!DataSize)
1605 DataSize = TypeLoc::getFullDataSizeForType(T);
1606 else
1607 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001608 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001609
John McCallbcd03502009-12-07 02:54:59 +00001610 TypeSourceInfo *TInfo =
1611 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1612 new (TInfo) TypeSourceInfo(T);
1613 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001614}
1615
John McCallbcd03502009-12-07 02:54:59 +00001616TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001617 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001618 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001619 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001620 return DI;
1621}
1622
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001623const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001624ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001625 return getObjCLayout(D, 0);
1626}
1627
1628const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001629ASTContext::getASTObjCImplementationLayout(
1630 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001631 return getObjCLayout(D->getClassInterface(), D);
1632}
1633
Chris Lattner983a8bb2007-07-13 22:13:22 +00001634//===----------------------------------------------------------------------===//
1635// Type creation/memoization methods
1636//===----------------------------------------------------------------------===//
1637
Jay Foad39c79802011-01-12 09:06:06 +00001638QualType
John McCall33ddac02011-01-19 10:06:00 +00001639ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1640 unsigned fastQuals = quals.getFastQualifiers();
1641 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001642
1643 // Check if we've already instantiated this type.
1644 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001645 ExtQuals::Profile(ID, baseType, quals);
1646 void *insertPos = 0;
1647 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1648 assert(eq->getQualifiers() == quals);
1649 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001650 }
1651
John McCall33ddac02011-01-19 10:06:00 +00001652 // If the base type is not canonical, make the appropriate canonical type.
1653 QualType canon;
1654 if (!baseType->isCanonicalUnqualified()) {
1655 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00001656 canonSplit.Quals.addConsistentQualifiers(quals);
1657 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001658
1659 // Re-find the insert position.
1660 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1661 }
1662
1663 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1664 ExtQualNodes.InsertNode(eq, insertPos);
1665 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001666}
1667
Jay Foad39c79802011-01-12 09:06:06 +00001668QualType
1669ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001670 QualType CanT = getCanonicalType(T);
1671 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001672 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001673
John McCall8ccfcb52009-09-24 19:53:00 +00001674 // If we are composing extended qualifiers together, merge together
1675 // into one ExtQuals node.
1676 QualifierCollector Quals;
1677 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001678
John McCall8ccfcb52009-09-24 19:53:00 +00001679 // If this type already has an address space specified, it cannot get
1680 // another one.
1681 assert(!Quals.hasAddressSpace() &&
1682 "Type cannot be in multiple addr spaces!");
1683 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001684
John McCall8ccfcb52009-09-24 19:53:00 +00001685 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001686}
1687
Chris Lattnerd60183d2009-02-18 22:53:11 +00001688QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001689 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001690 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001691 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001692 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001693
John McCall53fa7142010-12-24 02:08:15 +00001694 if (const PointerType *ptr = T->getAs<PointerType>()) {
1695 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001696 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001697 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1698 return getPointerType(ResultType);
1699 }
1700 }
Mike Stump11289f42009-09-09 15:08:12 +00001701
John McCall8ccfcb52009-09-24 19:53:00 +00001702 // If we are composing extended qualifiers together, merge together
1703 // into one ExtQuals node.
1704 QualifierCollector Quals;
1705 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001706
John McCall8ccfcb52009-09-24 19:53:00 +00001707 // If this type already has an ObjCGC specified, it cannot get
1708 // another one.
1709 assert(!Quals.hasObjCGCAttr() &&
1710 "Type cannot have multiple ObjCGCs!");
1711 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001712
John McCall8ccfcb52009-09-24 19:53:00 +00001713 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001714}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001715
John McCall4f5019e2010-12-19 02:44:49 +00001716const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1717 FunctionType::ExtInfo Info) {
1718 if (T->getExtInfo() == Info)
1719 return T;
1720
1721 QualType Result;
1722 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1723 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1724 } else {
1725 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1726 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1727 EPI.ExtInfo = Info;
1728 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1729 FPT->getNumArgs(), EPI);
1730 }
1731
1732 return cast<FunctionType>(Result.getTypePtr());
1733}
1734
Chris Lattnerc6395932007-06-22 20:56:16 +00001735/// getComplexType - Return the uniqued reference to the type for a complex
1736/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001737QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001738 // Unique pointers, to guarantee there is only one pointer of a particular
1739 // structure.
1740 llvm::FoldingSetNodeID ID;
1741 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001742
Chris Lattnerc6395932007-06-22 20:56:16 +00001743 void *InsertPos = 0;
1744 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1745 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001746
Chris Lattnerc6395932007-06-22 20:56:16 +00001747 // If the pointee type isn't canonical, this won't be a canonical type either,
1748 // so fill in the canonical type field.
1749 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001750 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001751 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001752
Chris Lattnerc6395932007-06-22 20:56:16 +00001753 // Get the new insert position for the node we care about.
1754 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001755 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001756 }
John McCall90d1c2d2009-09-24 23:30:46 +00001757 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001758 Types.push_back(New);
1759 ComplexTypes.InsertNode(New, InsertPos);
1760 return QualType(New, 0);
1761}
1762
Chris Lattner970e54e2006-11-12 00:37:36 +00001763/// getPointerType - Return the uniqued reference to the type for a pointer to
1764/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001765QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001766 // Unique pointers, to guarantee there is only one pointer of a particular
1767 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001768 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001769 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001770
Chris Lattner67521df2007-01-27 01:29:36 +00001771 void *InsertPos = 0;
1772 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001773 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001774
Chris Lattner7ccecb92006-11-12 08:50:50 +00001775 // If the pointee type isn't canonical, this won't be a canonical type either,
1776 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001777 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001778 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001779 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001780
Chris Lattner67521df2007-01-27 01:29:36 +00001781 // Get the new insert position for the node we care about.
1782 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001783 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001784 }
John McCall90d1c2d2009-09-24 23:30:46 +00001785 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001786 Types.push_back(New);
1787 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001788 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001789}
1790
Mike Stump11289f42009-09-09 15:08:12 +00001791/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001792/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001793QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001794 assert(T->isFunctionType() && "block of function types only");
1795 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001796 // structure.
1797 llvm::FoldingSetNodeID ID;
1798 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001799
Steve Naroffec33ed92008-08-27 16:04:49 +00001800 void *InsertPos = 0;
1801 if (BlockPointerType *PT =
1802 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1803 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001804
1805 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001806 // type either so fill in the canonical type field.
1807 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001808 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001809 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001810
Steve Naroffec33ed92008-08-27 16:04:49 +00001811 // Get the new insert position for the node we care about.
1812 BlockPointerType *NewIP =
1813 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001814 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001815 }
John McCall90d1c2d2009-09-24 23:30:46 +00001816 BlockPointerType *New
1817 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001818 Types.push_back(New);
1819 BlockPointerTypes.InsertNode(New, InsertPos);
1820 return QualType(New, 0);
1821}
1822
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001823/// getLValueReferenceType - Return the uniqued reference to the type for an
1824/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001825QualType
1826ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00001827 assert(getCanonicalType(T) != OverloadTy &&
1828 "Unresolved overloaded function type");
1829
Bill Wendling3708c182007-05-27 10:15:43 +00001830 // Unique pointers, to guarantee there is only one pointer of a particular
1831 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001832 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001833 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001834
1835 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001836 if (LValueReferenceType *RT =
1837 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001838 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001839
John McCallfc93cf92009-10-22 22:37:11 +00001840 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1841
Bill Wendling3708c182007-05-27 10:15:43 +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 (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1846 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1847 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001848
Bill Wendling3708c182007-05-27 10:15:43 +00001849 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001850 LValueReferenceType *NewIP =
1851 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001852 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001853 }
1854
John McCall90d1c2d2009-09-24 23:30:46 +00001855 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001856 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1857 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001858 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001859 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001860
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001861 return QualType(New, 0);
1862}
1863
1864/// getRValueReferenceType - Return the uniqued reference to the type for an
1865/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001866QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001867 // Unique pointers, to guarantee there is only one pointer of a particular
1868 // structure.
1869 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001870 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001871
1872 void *InsertPos = 0;
1873 if (RValueReferenceType *RT =
1874 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1875 return QualType(RT, 0);
1876
John McCallfc93cf92009-10-22 22:37:11 +00001877 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1878
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001879 // If the referencee type isn't canonical, this won't be a canonical type
1880 // either, so fill in the canonical type field.
1881 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001882 if (InnerRef || !T.isCanonical()) {
1883 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1884 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001885
1886 // Get the new insert position for the node we care about.
1887 RValueReferenceType *NewIP =
1888 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001889 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001890 }
1891
John McCall90d1c2d2009-09-24 23:30:46 +00001892 RValueReferenceType *New
1893 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001894 Types.push_back(New);
1895 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001896 return QualType(New, 0);
1897}
1898
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001899/// getMemberPointerType - Return the uniqued reference to the type for a
1900/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001901QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001902 // Unique pointers, to guarantee there is only one pointer of a particular
1903 // structure.
1904 llvm::FoldingSetNodeID ID;
1905 MemberPointerType::Profile(ID, T, Cls);
1906
1907 void *InsertPos = 0;
1908 if (MemberPointerType *PT =
1909 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1910 return QualType(PT, 0);
1911
1912 // If the pointee or class type isn't canonical, this won't be a canonical
1913 // type either, so fill in the canonical type field.
1914 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001915 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001916 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1917
1918 // Get the new insert position for the node we care about.
1919 MemberPointerType *NewIP =
1920 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001921 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001922 }
John McCall90d1c2d2009-09-24 23:30:46 +00001923 MemberPointerType *New
1924 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001925 Types.push_back(New);
1926 MemberPointerTypes.InsertNode(New, InsertPos);
1927 return QualType(New, 0);
1928}
1929
Mike Stump11289f42009-09-09 15:08:12 +00001930/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001931/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001932QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001933 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001934 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001935 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001936 assert((EltTy->isDependentType() ||
1937 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001938 "Constant array of VLAs is illegal!");
1939
Chris Lattnere2df3f92009-05-13 04:12:56 +00001940 // Convert the array size into a canonical width matching the pointer size for
1941 // the target.
1942 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001943 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001944 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00001945
Chris Lattner23b7eb62007-06-15 23:05:46 +00001946 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001947 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001948
Chris Lattner36f8e652007-01-27 08:31:04 +00001949 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001950 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001951 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001952 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001953
John McCall33ddac02011-01-19 10:06:00 +00001954 // If the element type isn't canonical or has qualifiers, this won't
1955 // be a canonical type either, so fill in the canonical type field.
1956 QualType Canon;
1957 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1958 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00001959 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001960 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00001961 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001962
Chris Lattner36f8e652007-01-27 08:31:04 +00001963 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001964 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001965 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001966 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001967 }
Mike Stump11289f42009-09-09 15:08:12 +00001968
John McCall90d1c2d2009-09-24 23:30:46 +00001969 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001970 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001971 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001972 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001973 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001974}
1975
John McCall06549462011-01-18 08:40:38 +00001976/// getVariableArrayDecayedType - Turns the given type, which may be
1977/// variably-modified, into the corresponding type with all the known
1978/// sizes replaced with [*].
1979QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1980 // Vastly most common case.
1981 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001982
John McCall06549462011-01-18 08:40:38 +00001983 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001984
John McCall06549462011-01-18 08:40:38 +00001985 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00001986 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00001987 switch (ty->getTypeClass()) {
1988#define TYPE(Class, Base)
1989#define ABSTRACT_TYPE(Class, Base)
1990#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1991#include "clang/AST/TypeNodes.def"
1992 llvm_unreachable("didn't desugar past all non-canonical types?");
1993
1994 // These types should never be variably-modified.
1995 case Type::Builtin:
1996 case Type::Complex:
1997 case Type::Vector:
1998 case Type::ExtVector:
1999 case Type::DependentSizedExtVector:
2000 case Type::ObjCObject:
2001 case Type::ObjCInterface:
2002 case Type::ObjCObjectPointer:
2003 case Type::Record:
2004 case Type::Enum:
2005 case Type::UnresolvedUsing:
2006 case Type::TypeOfExpr:
2007 case Type::TypeOf:
2008 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002009 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002010 case Type::DependentName:
2011 case Type::InjectedClassName:
2012 case Type::TemplateSpecialization:
2013 case Type::DependentTemplateSpecialization:
2014 case Type::TemplateTypeParm:
2015 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002016 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002017 case Type::PackExpansion:
2018 llvm_unreachable("type should never be variably-modified");
2019
2020 // These types can be variably-modified but should never need to
2021 // further decay.
2022 case Type::FunctionNoProto:
2023 case Type::FunctionProto:
2024 case Type::BlockPointer:
2025 case Type::MemberPointer:
2026 return type;
2027
2028 // These types can be variably-modified. All these modifications
2029 // preserve structure except as noted by comments.
2030 // TODO: if we ever care about optimizing VLAs, there are no-op
2031 // optimizations available here.
2032 case Type::Pointer:
2033 result = getPointerType(getVariableArrayDecayedType(
2034 cast<PointerType>(ty)->getPointeeType()));
2035 break;
2036
2037 case Type::LValueReference: {
2038 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2039 result = getLValueReferenceType(
2040 getVariableArrayDecayedType(lv->getPointeeType()),
2041 lv->isSpelledAsLValue());
2042 break;
2043 }
2044
2045 case Type::RValueReference: {
2046 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2047 result = getRValueReferenceType(
2048 getVariableArrayDecayedType(lv->getPointeeType()));
2049 break;
2050 }
2051
Eli Friedman0dfb8892011-10-06 23:00:33 +00002052 case Type::Atomic: {
2053 const AtomicType *at = cast<AtomicType>(ty);
2054 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2055 break;
2056 }
2057
John McCall06549462011-01-18 08:40:38 +00002058 case Type::ConstantArray: {
2059 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2060 result = getConstantArrayType(
2061 getVariableArrayDecayedType(cat->getElementType()),
2062 cat->getSize(),
2063 cat->getSizeModifier(),
2064 cat->getIndexTypeCVRQualifiers());
2065 break;
2066 }
2067
2068 case Type::DependentSizedArray: {
2069 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2070 result = getDependentSizedArrayType(
2071 getVariableArrayDecayedType(dat->getElementType()),
2072 dat->getSizeExpr(),
2073 dat->getSizeModifier(),
2074 dat->getIndexTypeCVRQualifiers(),
2075 dat->getBracketsRange());
2076 break;
2077 }
2078
2079 // Turn incomplete types into [*] types.
2080 case Type::IncompleteArray: {
2081 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2082 result = getVariableArrayType(
2083 getVariableArrayDecayedType(iat->getElementType()),
2084 /*size*/ 0,
2085 ArrayType::Normal,
2086 iat->getIndexTypeCVRQualifiers(),
2087 SourceRange());
2088 break;
2089 }
2090
2091 // Turn VLA types into [*] types.
2092 case Type::VariableArray: {
2093 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2094 result = getVariableArrayType(
2095 getVariableArrayDecayedType(vat->getElementType()),
2096 /*size*/ 0,
2097 ArrayType::Star,
2098 vat->getIndexTypeCVRQualifiers(),
2099 vat->getBracketsRange());
2100 break;
2101 }
2102 }
2103
2104 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002105 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002106}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002107
Steve Naroffcadebd02007-08-30 18:14:25 +00002108/// getVariableArrayType - Returns a non-unique reference to the type for a
2109/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002110QualType ASTContext::getVariableArrayType(QualType EltTy,
2111 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002112 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002113 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002114 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002115 // Since we don't unique expressions, it isn't possible to unique VLA's
2116 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002117 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002118
John McCall33ddac02011-01-19 10:06:00 +00002119 // Be sure to pull qualifiers off the element type.
2120 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2121 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002122 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002123 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002124 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002125 }
2126
John McCall90d1c2d2009-09-24 23:30:46 +00002127 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002128 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002129
2130 VariableArrayTypes.push_back(New);
2131 Types.push_back(New);
2132 return QualType(New, 0);
2133}
2134
Douglas Gregor4619e432008-12-05 23:32:09 +00002135/// getDependentSizedArrayType - Returns a non-unique reference to
2136/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002137/// type.
John McCall33ddac02011-01-19 10:06:00 +00002138QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2139 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002140 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002141 unsigned elementTypeQuals,
2142 SourceRange brackets) const {
2143 assert((!numElements || numElements->isTypeDependent() ||
2144 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002145 "Size must be type- or value-dependent!");
2146
John McCall33ddac02011-01-19 10:06:00 +00002147 // Dependently-sized array types that do not have a specified number
2148 // of elements will have their sizes deduced from a dependent
2149 // initializer. We do no canonicalization here at all, which is okay
2150 // because they can't be used in most locations.
2151 if (!numElements) {
2152 DependentSizedArrayType *newType
2153 = new (*this, TypeAlignment)
2154 DependentSizedArrayType(*this, elementType, QualType(),
2155 numElements, ASM, elementTypeQuals,
2156 brackets);
2157 Types.push_back(newType);
2158 return QualType(newType, 0);
2159 }
2160
2161 // Otherwise, we actually build a new type every time, but we
2162 // also build a canonical type.
2163
2164 SplitQualType canonElementType = getCanonicalType(elementType).split();
2165
2166 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002167 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002168 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002169 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002170 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002171
John McCall33ddac02011-01-19 10:06:00 +00002172 // Look for an existing type with these properties.
2173 DependentSizedArrayType *canonTy =
2174 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002175
John McCall33ddac02011-01-19 10:06:00 +00002176 // If we don't have one, build one.
2177 if (!canonTy) {
2178 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002179 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002180 QualType(), numElements, ASM, elementTypeQuals,
2181 brackets);
2182 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2183 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002184 }
2185
John McCall33ddac02011-01-19 10:06:00 +00002186 // Apply qualifiers from the element type to the array.
2187 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002188 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002189
John McCall33ddac02011-01-19 10:06:00 +00002190 // If we didn't need extra canonicalization for the element type,
2191 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002192 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002193 return canon;
2194
2195 // Otherwise, we need to build a type which follows the spelling
2196 // of the element type.
2197 DependentSizedArrayType *sugaredType
2198 = new (*this, TypeAlignment)
2199 DependentSizedArrayType(*this, elementType, canon, numElements,
2200 ASM, elementTypeQuals, brackets);
2201 Types.push_back(sugaredType);
2202 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002203}
2204
John McCall33ddac02011-01-19 10:06:00 +00002205QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002206 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002207 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002208 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002209 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002210
John McCall33ddac02011-01-19 10:06:00 +00002211 void *insertPos = 0;
2212 if (IncompleteArrayType *iat =
2213 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2214 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002215
2216 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002217 // either, so fill in the canonical type field. We also have to pull
2218 // qualifiers off the element type.
2219 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002220
John McCall33ddac02011-01-19 10:06:00 +00002221 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2222 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002223 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002224 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002225 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002226
2227 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002228 IncompleteArrayType *existing =
2229 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2230 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002231 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002232
John McCall33ddac02011-01-19 10:06:00 +00002233 IncompleteArrayType *newType = new (*this, TypeAlignment)
2234 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002235
John McCall33ddac02011-01-19 10:06:00 +00002236 IncompleteArrayTypes.InsertNode(newType, insertPos);
2237 Types.push_back(newType);
2238 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002239}
2240
Steve Naroff91fcddb2007-07-18 18:00:27 +00002241/// getVectorType - Return the unique reference to a vector type of
2242/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002243QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002244 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002245 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002246
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002247 // Check if we've already instantiated a vector of this type.
2248 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002249 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002250
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002251 void *InsertPos = 0;
2252 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2253 return QualType(VTP, 0);
2254
2255 // If the element type isn't canonical, this won't be a canonical type either,
2256 // so fill in the canonical type field.
2257 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002258 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002259 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002260
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002261 // Get the new insert position for the node we care about.
2262 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002263 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002264 }
John McCall90d1c2d2009-09-24 23:30:46 +00002265 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002266 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002267 VectorTypes.InsertNode(New, InsertPos);
2268 Types.push_back(New);
2269 return QualType(New, 0);
2270}
2271
Nate Begemance4d7fc2008-04-18 23:10:10 +00002272/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002273/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002274QualType
2275ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002276 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002277
Steve Naroff91fcddb2007-07-18 18:00:27 +00002278 // Check if we've already instantiated a vector of this type.
2279 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002280 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002281 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002282 void *InsertPos = 0;
2283 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2284 return QualType(VTP, 0);
2285
2286 // If the element type isn't canonical, this won't be a canonical type either,
2287 // so fill in the canonical type field.
2288 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002289 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002290 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002291
Steve Naroff91fcddb2007-07-18 18:00:27 +00002292 // Get the new insert position for the node we care about.
2293 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002294 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002295 }
John McCall90d1c2d2009-09-24 23:30:46 +00002296 ExtVectorType *New = new (*this, TypeAlignment)
2297 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002298 VectorTypes.InsertNode(New, InsertPos);
2299 Types.push_back(New);
2300 return QualType(New, 0);
2301}
2302
Jay Foad39c79802011-01-12 09:06:06 +00002303QualType
2304ASTContext::getDependentSizedExtVectorType(QualType vecType,
2305 Expr *SizeExpr,
2306 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002307 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002308 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002309 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002310
Douglas Gregor352169a2009-07-31 03:54:25 +00002311 void *InsertPos = 0;
2312 DependentSizedExtVectorType *Canon
2313 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2314 DependentSizedExtVectorType *New;
2315 if (Canon) {
2316 // We already have a canonical version of this array type; use it as
2317 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002318 New = new (*this, TypeAlignment)
2319 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2320 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002321 } else {
2322 QualType CanonVecTy = getCanonicalType(vecType);
2323 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002324 New = new (*this, TypeAlignment)
2325 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2326 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002327
2328 DependentSizedExtVectorType *CanonCheck
2329 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2330 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2331 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002332 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2333 } else {
2334 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2335 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002336 New = new (*this, TypeAlignment)
2337 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002338 }
2339 }
Mike Stump11289f42009-09-09 15:08:12 +00002340
Douglas Gregor758a8692009-06-17 21:51:59 +00002341 Types.push_back(New);
2342 return QualType(New, 0);
2343}
2344
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002345/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002346///
Jay Foad39c79802011-01-12 09:06:06 +00002347QualType
2348ASTContext::getFunctionNoProtoType(QualType ResultTy,
2349 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002350 const CallingConv DefaultCC = Info.getCC();
2351 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2352 CC_X86StdCall : DefaultCC;
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;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002356 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002357
Chris Lattner47955de2007-01-27 08:37:20 +00002358 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002359 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002360 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002361 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002362
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002363 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002364 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002365 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002366 Canonical =
2367 getFunctionNoProtoType(getCanonicalType(ResultTy),
2368 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002369
Chris Lattner47955de2007-01-27 08:37:20 +00002370 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002371 FunctionNoProtoType *NewIP =
2372 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002373 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002374 }
Mike Stump11289f42009-09-09 15:08:12 +00002375
Roman Divacky65b88cd2011-03-01 17:40:53 +00002376 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002377 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002378 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002379 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002380 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002381 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002382}
2383
2384/// getFunctionType - Return a normal function type with a typed argument
2385/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002386QualType
2387ASTContext::getFunctionType(QualType ResultTy,
2388 const QualType *ArgArray, unsigned NumArgs,
2389 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002390 // Unique functions, to guarantee there is only one function of a particular
2391 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002392 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002393 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002394
2395 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002396 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002397 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002398 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002399
2400 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002401 bool isCanonical =
2402 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2403 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002404 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002405 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002406 isCanonical = false;
2407
Roman Divacky65b88cd2011-03-01 17:40:53 +00002408 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2409 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2410 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002411
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002412 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002413 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002414 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002415 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002416 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002417 CanonicalArgs.reserve(NumArgs);
2418 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002419 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002420
John McCalldb40c7f2010-12-14 08:05:40 +00002421 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002422 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002423 CanonicalEPI.ExceptionSpecType = EST_None;
2424 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002425 CanonicalEPI.ExtInfo
2426 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2427
Chris Lattner76a00cf2008-04-06 22:59:24 +00002428 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002429 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002430 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002431
Chris Lattnerfd4de792007-01-27 01:15:32 +00002432 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002433 FunctionProtoType *NewIP =
2434 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002435 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002436 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002437
John McCall31168b02011-06-15 23:02:42 +00002438 // FunctionProtoType objects are allocated with extra bytes after
2439 // them for three variable size arrays at the end:
2440 // - parameter types
2441 // - exception types
2442 // - consumed-arguments flags
2443 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002444 // expression, or information used to resolve the exception
2445 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002446 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002447 NumArgs * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002448 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002449 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002450 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002451 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002452 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002453 Size += 2 * sizeof(FunctionDecl*);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002454 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2455 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002456 }
John McCall31168b02011-06-15 23:02:42 +00002457 if (EPI.ConsumedArguments)
2458 Size += NumArgs * sizeof(bool);
2459
John McCalldb40c7f2010-12-14 08:05:40 +00002460 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002461 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2462 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002463 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002464 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002465 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002466 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002467}
Chris Lattneref51c202006-11-10 07:17:23 +00002468
John McCalle78aac42010-03-10 03:28:59 +00002469#ifndef NDEBUG
2470static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2471 if (!isa<CXXRecordDecl>(D)) return false;
2472 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2473 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2474 return true;
2475 if (RD->getDescribedClassTemplate() &&
2476 !isa<ClassTemplateSpecializationDecl>(RD))
2477 return true;
2478 return false;
2479}
2480#endif
2481
2482/// getInjectedClassNameType - Return the unique reference to the
2483/// injected class name type for the specified templated declaration.
2484QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002485 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002486 assert(NeedsInjectedClassNameType(Decl));
2487 if (Decl->TypeForDecl) {
2488 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002489 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002490 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2491 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2492 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2493 } else {
John McCall424cec92011-01-19 06:33:43 +00002494 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002495 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002496 Decl->TypeForDecl = newType;
2497 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002498 }
2499 return QualType(Decl->TypeForDecl, 0);
2500}
2501
Douglas Gregor83a586e2008-04-13 21:07:44 +00002502/// getTypeDeclType - Return the unique reference to the type for the
2503/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002504QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002505 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002506 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002507
Richard Smithdda56e42011-04-15 14:24:37 +00002508 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002509 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002510
John McCall96f0b5f2010-03-10 06:48:02 +00002511 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2512 "Template type parameter types are always available.");
2513
John McCall81e38502010-02-16 03:57:14 +00002514 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002515 assert(!Record->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002516 "struct/union has previous declaration");
2517 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002518 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002519 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002520 assert(!Enum->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002521 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002522 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002523 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002524 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002525 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2526 Decl->TypeForDecl = newType;
2527 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002528 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002529 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002530
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002531 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002532}
2533
Chris Lattner32d920b2007-01-26 02:01:53 +00002534/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002535/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002536QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002537ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2538 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002539 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002540
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002541 if (Canonical.isNull())
2542 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002543 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002544 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002545 Decl->TypeForDecl = newType;
2546 Types.push_back(newType);
2547 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002548}
2549
Jay Foad39c79802011-01-12 09:06:06 +00002550QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002551 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2552
Douglas Gregorec9fd132012-01-14 16:38:05 +00002553 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002554 if (PrevDecl->TypeForDecl)
2555 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2556
John McCall424cec92011-01-19 06:33:43 +00002557 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2558 Decl->TypeForDecl = newType;
2559 Types.push_back(newType);
2560 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002561}
2562
Jay Foad39c79802011-01-12 09:06:06 +00002563QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002564 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2565
Douglas Gregorec9fd132012-01-14 16:38:05 +00002566 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002567 if (PrevDecl->TypeForDecl)
2568 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2569
John McCall424cec92011-01-19 06:33:43 +00002570 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2571 Decl->TypeForDecl = newType;
2572 Types.push_back(newType);
2573 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002574}
2575
John McCall81904512011-01-06 01:58:22 +00002576QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2577 QualType modifiedType,
2578 QualType equivalentType) {
2579 llvm::FoldingSetNodeID id;
2580 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2581
2582 void *insertPos = 0;
2583 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2584 if (type) return QualType(type, 0);
2585
2586 QualType canon = getCanonicalType(equivalentType);
2587 type = new (*this, TypeAlignment)
2588 AttributedType(canon, attrKind, modifiedType, equivalentType);
2589
2590 Types.push_back(type);
2591 AttributedTypes.InsertNode(type, insertPos);
2592
2593 return QualType(type, 0);
2594}
2595
2596
John McCallcebee162009-10-18 09:09:24 +00002597/// \brief Retrieve a substitution-result type.
2598QualType
2599ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002600 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002601 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002602 && "replacement types must always be canonical");
2603
2604 llvm::FoldingSetNodeID ID;
2605 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2606 void *InsertPos = 0;
2607 SubstTemplateTypeParmType *SubstParm
2608 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2609
2610 if (!SubstParm) {
2611 SubstParm = new (*this, TypeAlignment)
2612 SubstTemplateTypeParmType(Parm, Replacement);
2613 Types.push_back(SubstParm);
2614 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2615 }
2616
2617 return QualType(SubstParm, 0);
2618}
2619
Douglas Gregorada4b792011-01-14 02:55:32 +00002620/// \brief Retrieve a
2621QualType ASTContext::getSubstTemplateTypeParmPackType(
2622 const TemplateTypeParmType *Parm,
2623 const TemplateArgument &ArgPack) {
2624#ifndef NDEBUG
2625 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2626 PEnd = ArgPack.pack_end();
2627 P != PEnd; ++P) {
2628 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2629 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2630 }
2631#endif
2632
2633 llvm::FoldingSetNodeID ID;
2634 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2635 void *InsertPos = 0;
2636 if (SubstTemplateTypeParmPackType *SubstParm
2637 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2638 return QualType(SubstParm, 0);
2639
2640 QualType Canon;
2641 if (!Parm->isCanonicalUnqualified()) {
2642 Canon = getCanonicalType(QualType(Parm, 0));
2643 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2644 ArgPack);
2645 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2646 }
2647
2648 SubstTemplateTypeParmPackType *SubstParm
2649 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2650 ArgPack);
2651 Types.push_back(SubstParm);
2652 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2653 return QualType(SubstParm, 0);
2654}
2655
Douglas Gregoreff93e02009-02-05 23:33:38 +00002656/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002657/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002658/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002659QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002660 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002661 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002662 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002663 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002664 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002665 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002666 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2667
2668 if (TypeParm)
2669 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002670
Chandler Carruth08836322011-05-01 00:51:33 +00002671 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002672 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002673 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002674
2675 TemplateTypeParmType *TypeCheck
2676 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2677 assert(!TypeCheck && "Template type parameter canonical type broken");
2678 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002679 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002680 TypeParm = new (*this, TypeAlignment)
2681 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002682
2683 Types.push_back(TypeParm);
2684 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2685
2686 return QualType(TypeParm, 0);
2687}
2688
John McCalle78aac42010-03-10 03:28:59 +00002689TypeSourceInfo *
2690ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2691 SourceLocation NameLoc,
2692 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002693 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002694 assert(!Name.getAsDependentTemplateName() &&
2695 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002696 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002697
2698 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2699 TemplateSpecializationTypeLoc TL
2700 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002701 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00002702 TL.setTemplateNameLoc(NameLoc);
2703 TL.setLAngleLoc(Args.getLAngleLoc());
2704 TL.setRAngleLoc(Args.getRAngleLoc());
2705 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2706 TL.setArgLocInfo(i, Args[i].getLocInfo());
2707 return DI;
2708}
2709
Mike Stump11289f42009-09-09 15:08:12 +00002710QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002711ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002712 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002713 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002714 assert(!Template.getAsDependentTemplateName() &&
2715 "No dependent template names here!");
2716
John McCall6b51f282009-11-23 01:53:49 +00002717 unsigned NumArgs = Args.size();
2718
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002719 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002720 ArgVec.reserve(NumArgs);
2721 for (unsigned i = 0; i != NumArgs; ++i)
2722 ArgVec.push_back(Args[i].getArgument());
2723
John McCall2408e322010-04-27 00:57:59 +00002724 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002725 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002726}
2727
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002728#ifndef NDEBUG
2729static bool hasAnyPackExpansions(const TemplateArgument *Args,
2730 unsigned NumArgs) {
2731 for (unsigned I = 0; I != NumArgs; ++I)
2732 if (Args[I].isPackExpansion())
2733 return true;
2734
2735 return true;
2736}
2737#endif
2738
John McCall0ad16662009-10-29 08:12:44 +00002739QualType
2740ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002741 const TemplateArgument *Args,
2742 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002743 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002744 assert(!Template.getAsDependentTemplateName() &&
2745 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002746 // Look through qualified template names.
2747 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2748 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002749
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002750 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00002751 Template.getAsTemplateDecl() &&
2752 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00002753 QualType CanonType;
2754 if (!Underlying.isNull())
2755 CanonType = getCanonicalType(Underlying);
2756 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002757 // We can get here with an alias template when the specialization contains
2758 // a pack expansion that does not match up with a parameter pack.
2759 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2760 "Caller must compute aliased type");
2761 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00002762 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2763 NumArgs);
2764 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002765
Douglas Gregora8e02e72009-07-28 23:00:59 +00002766 // Allocate the (non-canonical) template specialization type, but don't
2767 // try to unique it: these types typically have location information that
2768 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002769 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2770 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002771 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002772 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002773 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002774 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2775 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002776
Douglas Gregor8bf42052009-02-09 18:46:07 +00002777 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002778 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002779}
2780
Mike Stump11289f42009-09-09 15:08:12 +00002781QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002782ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2783 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002784 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002785 assert(!Template.getAsDependentTemplateName() &&
2786 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002787
Douglas Gregore29139c2011-03-03 17:04:51 +00002788 // Look through qualified template names.
2789 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2790 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002791
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002792 // Build the canonical template specialization type.
2793 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002794 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002795 CanonArgs.reserve(NumArgs);
2796 for (unsigned I = 0; I != NumArgs; ++I)
2797 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2798
2799 // Determine whether this canonical template specialization type already
2800 // exists.
2801 llvm::FoldingSetNodeID ID;
2802 TemplateSpecializationType::Profile(ID, CanonTemplate,
2803 CanonArgs.data(), NumArgs, *this);
2804
2805 void *InsertPos = 0;
2806 TemplateSpecializationType *Spec
2807 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2808
2809 if (!Spec) {
2810 // Allocate a new canonical template specialization type.
2811 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2812 sizeof(TemplateArgument) * NumArgs),
2813 TypeAlignment);
2814 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2815 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002816 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002817 Types.push_back(Spec);
2818 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2819 }
2820
2821 assert(Spec->isDependentType() &&
2822 "Non-dependent template-id type must have a canonical type");
2823 return QualType(Spec, 0);
2824}
2825
2826QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002827ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2828 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002829 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002830 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002831 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002832
2833 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002834 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002835 if (T)
2836 return QualType(T, 0);
2837
Douglas Gregorc42075a2010-02-04 18:10:26 +00002838 QualType Canon = NamedType;
2839 if (!Canon.isCanonical()) {
2840 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002841 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2842 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002843 (void)CheckT;
2844 }
2845
Abramo Bagnara6150c882010-05-11 21:36:43 +00002846 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002847 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002848 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002849 return QualType(T, 0);
2850}
2851
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002852QualType
Jay Foad39c79802011-01-12 09:06:06 +00002853ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002854 llvm::FoldingSetNodeID ID;
2855 ParenType::Profile(ID, InnerType);
2856
2857 void *InsertPos = 0;
2858 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2859 if (T)
2860 return QualType(T, 0);
2861
2862 QualType Canon = InnerType;
2863 if (!Canon.isCanonical()) {
2864 Canon = getCanonicalType(InnerType);
2865 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2866 assert(!CheckT && "Paren canonical type broken");
2867 (void)CheckT;
2868 }
2869
2870 T = new (*this) ParenType(InnerType, Canon);
2871 Types.push_back(T);
2872 ParenTypes.InsertNode(T, InsertPos);
2873 return QualType(T, 0);
2874}
2875
Douglas Gregor02085352010-03-31 20:19:30 +00002876QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2877 NestedNameSpecifier *NNS,
2878 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002879 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002880 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2881
2882 if (Canon.isNull()) {
2883 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002884 ElaboratedTypeKeyword CanonKeyword = Keyword;
2885 if (Keyword == ETK_None)
2886 CanonKeyword = ETK_Typename;
2887
2888 if (CanonNNS != NNS || CanonKeyword != Keyword)
2889 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002890 }
2891
2892 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002893 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002894
2895 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002896 DependentNameType *T
2897 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002898 if (T)
2899 return QualType(T, 0);
2900
Douglas Gregor02085352010-03-31 20:19:30 +00002901 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002902 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002903 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002904 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002905}
2906
Mike Stump11289f42009-09-09 15:08:12 +00002907QualType
John McCallc392f372010-06-11 00:33:02 +00002908ASTContext::getDependentTemplateSpecializationType(
2909 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002910 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002911 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002912 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002913 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002914 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00002915 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2916 ArgCopy.push_back(Args[I].getArgument());
2917 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2918 ArgCopy.size(),
2919 ArgCopy.data());
2920}
2921
2922QualType
2923ASTContext::getDependentTemplateSpecializationType(
2924 ElaboratedTypeKeyword Keyword,
2925 NestedNameSpecifier *NNS,
2926 const IdentifierInfo *Name,
2927 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002928 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00002929 assert((!NNS || NNS->isDependent()) &&
2930 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00002931
Douglas Gregorc42075a2010-02-04 18:10:26 +00002932 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002933 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2934 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002935
2936 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002937 DependentTemplateSpecializationType *T
2938 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002939 if (T)
2940 return QualType(T, 0);
2941
John McCallc392f372010-06-11 00:33:02 +00002942 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002943
John McCallc392f372010-06-11 00:33:02 +00002944 ElaboratedTypeKeyword CanonKeyword = Keyword;
2945 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2946
2947 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002948 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00002949 for (unsigned I = 0; I != NumArgs; ++I) {
2950 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2951 if (!CanonArgs[I].structurallyEquals(Args[I]))
2952 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002953 }
2954
John McCallc392f372010-06-11 00:33:02 +00002955 QualType Canon;
2956 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2957 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2958 Name, NumArgs,
2959 CanonArgs.data());
2960
2961 // Find the insert position again.
2962 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2963 }
2964
2965 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2966 sizeof(TemplateArgument) * NumArgs),
2967 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002968 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002969 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002970 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002971 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002972 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002973}
2974
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002975QualType ASTContext::getPackExpansionType(QualType Pattern,
2976 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002977 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002978 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002979
2980 assert(Pattern->containsUnexpandedParameterPack() &&
2981 "Pack expansions must expand one or more parameter packs");
2982 void *InsertPos = 0;
2983 PackExpansionType *T
2984 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2985 if (T)
2986 return QualType(T, 0);
2987
2988 QualType Canon;
2989 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00002990 Canon = getCanonicalType(Pattern);
2991 // The canonical type might not contain an unexpanded parameter pack, if it
2992 // contains an alias template specialization which ignores one of its
2993 // parameters.
2994 if (Canon->containsUnexpandedParameterPack()) {
2995 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002996
Richard Smith68eea502012-07-16 00:20:35 +00002997 // Find the insert position again, in case we inserted an element into
2998 // PackExpansionTypes and invalidated our insert position.
2999 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3000 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003001 }
3002
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003003 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003004 Types.push_back(T);
3005 PackExpansionTypes.InsertNode(T, InsertPos);
3006 return QualType(T, 0);
3007}
3008
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003009/// CmpProtocolNames - Comparison predicate for sorting protocols
3010/// alphabetically.
3011static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3012 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003013 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003014}
3015
John McCall8b07ec22010-05-15 11:32:37 +00003016static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003017 unsigned NumProtocols) {
3018 if (NumProtocols == 0) return true;
3019
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003020 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3021 return false;
3022
John McCallfc93cf92009-10-22 22:37:11 +00003023 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003024 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3025 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003026 return false;
3027 return true;
3028}
3029
3030static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003031 unsigned &NumProtocols) {
3032 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003033
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003034 // Sort protocols, keyed by name.
3035 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3036
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003037 // Canonicalize.
3038 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3039 Protocols[I] = Protocols[I]->getCanonicalDecl();
3040
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003041 // Remove duplicates.
3042 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3043 NumProtocols = ProtocolsEnd-Protocols;
3044}
3045
John McCall8b07ec22010-05-15 11:32:37 +00003046QualType ASTContext::getObjCObjectType(QualType BaseType,
3047 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003048 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003049 // If the base type is an interface and there aren't any protocols
3050 // to add, then the interface type will do just fine.
3051 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3052 return BaseType;
3053
3054 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003055 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003056 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00003057 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00003058 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3059 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003060
John McCall8b07ec22010-05-15 11:32:37 +00003061 // Build the canonical type, which has the canonical base type and
3062 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003063 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003064 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3065 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3066 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003067 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003068 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003069 unsigned UniqueCount = NumProtocols;
3070
John McCallfc93cf92009-10-22 22:37:11 +00003071 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003072 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3073 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003074 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003075 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3076 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003077 }
3078
3079 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003080 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3081 }
3082
3083 unsigned Size = sizeof(ObjCObjectTypeImpl);
3084 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3085 void *Mem = Allocate(Size, TypeAlignment);
3086 ObjCObjectTypeImpl *T =
3087 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3088
3089 Types.push_back(T);
3090 ObjCObjectTypes.InsertNode(T, InsertPos);
3091 return QualType(T, 0);
3092}
3093
3094/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3095/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003096QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003097 llvm::FoldingSetNodeID ID;
3098 ObjCObjectPointerType::Profile(ID, ObjectT);
3099
3100 void *InsertPos = 0;
3101 if (ObjCObjectPointerType *QT =
3102 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3103 return QualType(QT, 0);
3104
3105 // Find the canonical object type.
3106 QualType Canonical;
3107 if (!ObjectT.isCanonical()) {
3108 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3109
3110 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003111 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3112 }
3113
Douglas Gregorf85bee62010-02-08 22:59:26 +00003114 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003115 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3116 ObjCObjectPointerType *QType =
3117 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003118
Steve Narofffb4330f2009-06-17 22:40:22 +00003119 Types.push_back(QType);
3120 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003121 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003122}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003123
Douglas Gregor1c283312010-08-11 12:19:30 +00003124/// getObjCInterfaceType - Return the unique reference to the type for the
3125/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003126QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3127 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003128 if (Decl->TypeForDecl)
3129 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003130
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003131 if (PrevDecl) {
3132 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3133 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3134 return QualType(PrevDecl->TypeForDecl, 0);
3135 }
3136
Douglas Gregor7671e532011-12-16 16:34:57 +00003137 // Prefer the definition, if there is one.
3138 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3139 Decl = Def;
3140
Douglas Gregor1c283312010-08-11 12:19:30 +00003141 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3142 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3143 Decl->TypeForDecl = T;
3144 Types.push_back(T);
3145 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003146}
3147
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003148/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3149/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003150/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003151/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003152/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003153QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003154 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003155 if (tofExpr->isTypeDependent()) {
3156 llvm::FoldingSetNodeID ID;
3157 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003158
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003159 void *InsertPos = 0;
3160 DependentTypeOfExprType *Canon
3161 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3162 if (Canon) {
3163 // We already have a "canonical" version of an identical, dependent
3164 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003165 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003166 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003167 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003168 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003169 Canon
3170 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003171 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3172 toe = Canon;
3173 }
3174 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003175 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003176 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003177 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003178 Types.push_back(toe);
3179 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003180}
3181
Steve Naroffa773cd52007-08-01 18:02:17 +00003182/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3183/// TypeOfType AST's. The only motivation to unique these nodes would be
3184/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003185/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003186/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003187QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003188 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003189 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003190 Types.push_back(tot);
3191 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003192}
3193
Anders Carlssonad6bd352009-06-24 21:24:56 +00003194
Anders Carlsson81df7b82009-06-24 19:06:50 +00003195/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3196/// DecltypeType AST's. The only motivation to unique these nodes would be
3197/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003198/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003199/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003200QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003201 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003202
3203 // C++0x [temp.type]p2:
3204 // If an expression e involves a template parameter, decltype(e) denotes a
3205 // unique dependent type. Two such decltype-specifiers refer to the same
3206 // type only if their expressions are equivalent (14.5.6.1).
3207 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003208 llvm::FoldingSetNodeID ID;
3209 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003210
Douglas Gregora21f6c32009-07-30 23:36:40 +00003211 void *InsertPos = 0;
3212 DependentDecltypeType *Canon
3213 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3214 if (Canon) {
3215 // We already have a "canonical" version of an equivalent, dependent
3216 // decltype type. Use that as our canonical type.
Richard Smithef8bf432012-08-13 20:08:14 +00003217 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003218 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003219 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003220 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003221 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003222 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3223 dt = Canon;
3224 }
3225 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003226 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3227 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003228 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003229 Types.push_back(dt);
3230 return QualType(dt, 0);
3231}
3232
Alexis Hunte852b102011-05-24 22:41:36 +00003233/// getUnaryTransformationType - We don't unique these, since the memory
3234/// savings are minimal and these are rare.
3235QualType ASTContext::getUnaryTransformType(QualType BaseType,
3236 QualType UnderlyingType,
3237 UnaryTransformType::UTTKind Kind)
3238 const {
3239 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003240 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3241 Kind,
3242 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003243 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003244 Types.push_back(Ty);
3245 return QualType(Ty, 0);
3246}
3247
Richard Smithb2bc2e62011-02-21 20:05:19 +00003248/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003249QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00003250 void *InsertPos = 0;
3251 if (!DeducedType.isNull()) {
3252 // Look in the folding set for an existing type.
3253 llvm::FoldingSetNodeID ID;
3254 AutoType::Profile(ID, DeducedType);
3255 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3256 return QualType(AT, 0);
3257 }
3258
3259 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3260 Types.push_back(AT);
3261 if (InsertPos)
3262 AutoTypes.InsertNode(AT, InsertPos);
3263 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003264}
3265
Eli Friedman0dfb8892011-10-06 23:00:33 +00003266/// getAtomicType - Return the uniqued reference to the atomic type for
3267/// the given value type.
3268QualType ASTContext::getAtomicType(QualType T) const {
3269 // Unique pointers, to guarantee there is only one pointer of a particular
3270 // structure.
3271 llvm::FoldingSetNodeID ID;
3272 AtomicType::Profile(ID, T);
3273
3274 void *InsertPos = 0;
3275 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3276 return QualType(AT, 0);
3277
3278 // If the atomic value type isn't canonical, this won't be a canonical type
3279 // either, so fill in the canonical type field.
3280 QualType Canonical;
3281 if (!T.isCanonical()) {
3282 Canonical = getAtomicType(getCanonicalType(T));
3283
3284 // Get the new insert position for the node we care about.
3285 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3286 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3287 }
3288 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3289 Types.push_back(New);
3290 AtomicTypes.InsertNode(New, InsertPos);
3291 return QualType(New, 0);
3292}
3293
Richard Smith02e85f32011-04-14 22:09:26 +00003294/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3295QualType ASTContext::getAutoDeductType() const {
3296 if (AutoDeductTy.isNull())
3297 AutoDeductTy = getAutoType(QualType());
3298 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3299 return AutoDeductTy;
3300}
3301
3302/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3303QualType ASTContext::getAutoRRefDeductType() const {
3304 if (AutoRRefDeductTy.isNull())
3305 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3306 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3307 return AutoRRefDeductTy;
3308}
3309
Chris Lattnerfb072462007-01-23 05:45:31 +00003310/// getTagDeclType - Return the unique reference to the type for the
3311/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003312QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003313 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003314 // FIXME: What is the design on getTagDeclType when it requires casting
3315 // away const? mutable?
3316 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003317}
3318
Mike Stump11289f42009-09-09 15:08:12 +00003319/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3320/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3321/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003322CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003323 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003324}
Chris Lattnerfb072462007-01-23 05:45:31 +00003325
Hans Wennborg27541db2011-10-27 08:29:09 +00003326/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3327CanQualType ASTContext::getIntMaxType() const {
3328 return getFromTargetType(Target->getIntMaxType());
3329}
3330
3331/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3332CanQualType ASTContext::getUIntMaxType() const {
3333 return getFromTargetType(Target->getUIntMaxType());
3334}
3335
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003336/// getSignedWCharType - Return the type of "signed wchar_t".
3337/// Used when in C++, as a GCC extension.
3338QualType ASTContext::getSignedWCharType() const {
3339 // FIXME: derive from "Target" ?
3340 return WCharTy;
3341}
3342
3343/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3344/// Used when in C++, as a GCC extension.
3345QualType ASTContext::getUnsignedWCharType() const {
3346 // FIXME: derive from "Target" ?
3347 return UnsignedIntTy;
3348}
3349
Hans Wennborg27541db2011-10-27 08:29:09 +00003350/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003351/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3352QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003353 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003354}
3355
Chris Lattnera21ad802008-04-02 05:18:44 +00003356//===----------------------------------------------------------------------===//
3357// Type Operators
3358//===----------------------------------------------------------------------===//
3359
Jay Foad39c79802011-01-12 09:06:06 +00003360CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003361 // Push qualifiers into arrays, and then discard any remaining
3362 // qualifiers.
3363 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003364 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003365 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003366 QualType Result;
3367 if (isa<ArrayType>(Ty)) {
3368 Result = getArrayDecayedType(QualType(Ty,0));
3369 } else if (isa<FunctionType>(Ty)) {
3370 Result = getPointerType(QualType(Ty, 0));
3371 } else {
3372 Result = QualType(Ty, 0);
3373 }
3374
3375 return CanQualType::CreateUnsafe(Result);
3376}
3377
John McCall6c9dd522011-01-18 07:41:22 +00003378QualType ASTContext::getUnqualifiedArrayType(QualType type,
3379 Qualifiers &quals) {
3380 SplitQualType splitType = type.getSplitUnqualifiedType();
3381
3382 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3383 // the unqualified desugared type and then drops it on the floor.
3384 // We then have to strip that sugar back off with
3385 // getUnqualifiedDesugaredType(), which is silly.
3386 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003387 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003388
3389 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003390 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003391 quals = splitType.Quals;
3392 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003393 }
3394
John McCall6c9dd522011-01-18 07:41:22 +00003395 // Otherwise, recurse on the array's element type.
3396 QualType elementType = AT->getElementType();
3397 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3398
3399 // If that didn't change the element type, AT has no qualifiers, so we
3400 // can just use the results in splitType.
3401 if (elementType == unqualElementType) {
3402 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003403 quals = splitType.Quals;
3404 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003405 }
3406
3407 // Otherwise, add in the qualifiers from the outermost type, then
3408 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003409 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003410
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003411 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003412 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003413 CAT->getSizeModifier(), 0);
3414 }
3415
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003416 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003417 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003418 }
3419
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003420 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003421 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003422 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003423 VAT->getSizeModifier(),
3424 VAT->getIndexTypeCVRQualifiers(),
3425 VAT->getBracketsRange());
3426 }
3427
3428 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003429 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003430 DSAT->getSizeModifier(), 0,
3431 SourceRange());
3432}
3433
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003434/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3435/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3436/// they point to and return true. If T1 and T2 aren't pointer types
3437/// or pointer-to-member types, or if they are not similar at this
3438/// level, returns false and leaves T1 and T2 unchanged. Top-level
3439/// qualifiers on T1 and T2 are ignored. This function will typically
3440/// be called in a loop that successively "unwraps" pointer and
3441/// pointer-to-member types to compare them at each level.
3442bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3443 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3444 *T2PtrType = T2->getAs<PointerType>();
3445 if (T1PtrType && T2PtrType) {
3446 T1 = T1PtrType->getPointeeType();
3447 T2 = T2PtrType->getPointeeType();
3448 return true;
3449 }
3450
3451 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3452 *T2MPType = T2->getAs<MemberPointerType>();
3453 if (T1MPType && T2MPType &&
3454 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3455 QualType(T2MPType->getClass(), 0))) {
3456 T1 = T1MPType->getPointeeType();
3457 T2 = T2MPType->getPointeeType();
3458 return true;
3459 }
3460
David Blaikiebbafb8a2012-03-11 07:00:24 +00003461 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003462 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3463 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3464 if (T1OPType && T2OPType) {
3465 T1 = T1OPType->getPointeeType();
3466 T2 = T2OPType->getPointeeType();
3467 return true;
3468 }
3469 }
3470
3471 // FIXME: Block pointers, too?
3472
3473 return false;
3474}
3475
Jay Foad39c79802011-01-12 09:06:06 +00003476DeclarationNameInfo
3477ASTContext::getNameForTemplate(TemplateName Name,
3478 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003479 switch (Name.getKind()) {
3480 case TemplateName::QualifiedTemplate:
3481 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003482 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003483 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3484 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003485
John McCalld9dfe3a2011-06-30 08:33:18 +00003486 case TemplateName::OverloadedTemplate: {
3487 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3488 // DNInfo work in progress: CHECKME: what about DNLoc?
3489 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3490 }
3491
3492 case TemplateName::DependentTemplate: {
3493 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003494 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003495 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003496 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3497 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003498 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003499 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3500 // DNInfo work in progress: FIXME: source locations?
3501 DeclarationNameLoc DNLoc;
3502 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3503 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3504 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003505 }
3506 }
3507
John McCalld9dfe3a2011-06-30 08:33:18 +00003508 case TemplateName::SubstTemplateTemplateParm: {
3509 SubstTemplateTemplateParmStorage *subst
3510 = Name.getAsSubstTemplateTemplateParm();
3511 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3512 NameLoc);
3513 }
3514
3515 case TemplateName::SubstTemplateTemplateParmPack: {
3516 SubstTemplateTemplateParmPackStorage *subst
3517 = Name.getAsSubstTemplateTemplateParmPack();
3518 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3519 NameLoc);
3520 }
3521 }
3522
3523 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003524}
3525
Jay Foad39c79802011-01-12 09:06:06 +00003526TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003527 switch (Name.getKind()) {
3528 case TemplateName::QualifiedTemplate:
3529 case TemplateName::Template: {
3530 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003531 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003532 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003533 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3534
3535 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003536 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003537 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003538
John McCalld9dfe3a2011-06-30 08:33:18 +00003539 case TemplateName::OverloadedTemplate:
3540 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003541
John McCalld9dfe3a2011-06-30 08:33:18 +00003542 case TemplateName::DependentTemplate: {
3543 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3544 assert(DTN && "Non-dependent template names must refer to template decls.");
3545 return DTN->CanonicalTemplateName;
3546 }
3547
3548 case TemplateName::SubstTemplateTemplateParm: {
3549 SubstTemplateTemplateParmStorage *subst
3550 = Name.getAsSubstTemplateTemplateParm();
3551 return getCanonicalTemplateName(subst->getReplacement());
3552 }
3553
3554 case TemplateName::SubstTemplateTemplateParmPack: {
3555 SubstTemplateTemplateParmPackStorage *subst
3556 = Name.getAsSubstTemplateTemplateParmPack();
3557 TemplateTemplateParmDecl *canonParameter
3558 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3559 TemplateArgument canonArgPack
3560 = getCanonicalTemplateArgument(subst->getArgumentPack());
3561 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3562 }
3563 }
3564
3565 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003566}
3567
Douglas Gregoradee3e32009-11-11 23:06:43 +00003568bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3569 X = getCanonicalTemplateName(X);
3570 Y = getCanonicalTemplateName(Y);
3571 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3572}
3573
Mike Stump11289f42009-09-09 15:08:12 +00003574TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003575ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003576 switch (Arg.getKind()) {
3577 case TemplateArgument::Null:
3578 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003579
Douglas Gregora8e02e72009-07-28 23:00:59 +00003580 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003581 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003582
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003583 case TemplateArgument::Declaration: {
3584 if (Decl *D = Arg.getAsDecl())
3585 return TemplateArgument(D->getCanonicalDecl());
3586 return TemplateArgument((Decl*)0);
3587 }
Mike Stump11289f42009-09-09 15:08:12 +00003588
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003589 case TemplateArgument::Template:
3590 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003591
3592 case TemplateArgument::TemplateExpansion:
3593 return TemplateArgument(getCanonicalTemplateName(
3594 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003595 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003596
Douglas Gregora8e02e72009-07-28 23:00:59 +00003597 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00003598 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003599
Douglas Gregora8e02e72009-07-28 23:00:59 +00003600 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003601 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003602
Douglas Gregora8e02e72009-07-28 23:00:59 +00003603 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003604 if (Arg.pack_size() == 0)
3605 return Arg;
3606
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003607 TemplateArgument *CanonArgs
3608 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003609 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003610 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003611 AEnd = Arg.pack_end();
3612 A != AEnd; (void)++A, ++Idx)
3613 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003614
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003615 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003616 }
3617 }
3618
3619 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003620 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003621}
3622
Douglas Gregor333489b2009-03-27 23:10:48 +00003623NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003624ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003625 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003626 return 0;
3627
3628 switch (NNS->getKind()) {
3629 case NestedNameSpecifier::Identifier:
3630 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003631 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003632 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3633 NNS->getAsIdentifier());
3634
3635 case NestedNameSpecifier::Namespace:
3636 // A namespace is canonical; build a nested-name-specifier with
3637 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003638 return NestedNameSpecifier::Create(*this, 0,
3639 NNS->getAsNamespace()->getOriginalNamespace());
3640
3641 case NestedNameSpecifier::NamespaceAlias:
3642 // A namespace is canonical; build a nested-name-specifier with
3643 // this namespace and no prefix.
3644 return NestedNameSpecifier::Create(*this, 0,
3645 NNS->getAsNamespaceAlias()->getNamespace()
3646 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003647
3648 case NestedNameSpecifier::TypeSpec:
3649 case NestedNameSpecifier::TypeSpecWithTemplate: {
3650 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003651
3652 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3653 // break it apart into its prefix and identifier, then reconsititute those
3654 // as the canonical nested-name-specifier. This is required to canonicalize
3655 // a dependent nested-name-specifier involving typedefs of dependent-name
3656 // types, e.g.,
3657 // typedef typename T::type T1;
3658 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00003659 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3660 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00003661 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003662
Eli Friedman5358a0a2012-03-03 04:09:56 +00003663 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3664 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3665 // first place?
John McCall33ddac02011-01-19 10:06:00 +00003666 return NestedNameSpecifier::Create(*this, 0, false,
3667 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003668 }
3669
3670 case NestedNameSpecifier::Global:
3671 // The global specifier is canonical and unique.
3672 return NNS;
3673 }
3674
David Blaikie8a40f702012-01-17 06:56:22 +00003675 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00003676}
3677
Chris Lattner7adf0762008-08-04 07:31:14 +00003678
Jay Foad39c79802011-01-12 09:06:06 +00003679const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003680 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003681 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003682 // Handle the common positive case fast.
3683 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3684 return AT;
3685 }
Mike Stump11289f42009-09-09 15:08:12 +00003686
John McCall8ccfcb52009-09-24 19:53:00 +00003687 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003688 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003689 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003690
John McCall8ccfcb52009-09-24 19:53:00 +00003691 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003692 // implements C99 6.7.3p8: "If the specification of an array type includes
3693 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003694
Chris Lattner7adf0762008-08-04 07:31:14 +00003695 // If we get here, we either have type qualifiers on the type, or we have
3696 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003697 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003698
John McCall33ddac02011-01-19 10:06:00 +00003699 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003700 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00003701
Chris Lattner7adf0762008-08-04 07:31:14 +00003702 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00003703 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00003704 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003705 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003706
Chris Lattner7adf0762008-08-04 07:31:14 +00003707 // Otherwise, we have an array and we have qualifiers on it. Push the
3708 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003709 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003710
Chris Lattner7adf0762008-08-04 07:31:14 +00003711 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3712 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3713 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003714 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003715 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3716 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3717 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003718 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003719
Mike Stump11289f42009-09-09 15:08:12 +00003720 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003721 = dyn_cast<DependentSizedArrayType>(ATy))
3722 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003723 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003724 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003725 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003726 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003727 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003728
Chris Lattner7adf0762008-08-04 07:31:14 +00003729 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003730 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003731 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003732 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003733 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003734 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003735}
3736
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003737QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003738 // C99 6.7.5.3p7:
3739 // A declaration of a parameter as "array of type" shall be
3740 // adjusted to "qualified pointer to type", where the type
3741 // qualifiers (if any) are those specified within the [ and ] of
3742 // the array type derivation.
3743 if (T->isArrayType())
3744 return getArrayDecayedType(T);
3745
3746 // C99 6.7.5.3p8:
3747 // A declaration of a parameter as "function returning type"
3748 // shall be adjusted to "pointer to function returning type", as
3749 // in 6.3.2.1.
3750 if (T->isFunctionType())
3751 return getPointerType(T);
3752
3753 return T;
3754}
3755
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003756QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003757 T = getVariableArrayDecayedType(T);
3758 T = getAdjustedParameterType(T);
3759 return T.getUnqualifiedType();
3760}
3761
Chris Lattnera21ad802008-04-02 05:18:44 +00003762/// getArrayDecayedType - Return the properly qualified result of decaying the
3763/// specified array type to a pointer. This operation is non-trivial when
3764/// handling typedefs etc. The canonical type of "T" must be an array type,
3765/// this returns a pointer to a properly qualified element of the array.
3766///
3767/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003768QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003769 // Get the element type with 'getAsArrayType' so that we don't lose any
3770 // typedefs in the element type of the array. This also handles propagation
3771 // of type qualifiers from the array type into the element type if present
3772 // (C99 6.7.3p8).
3773 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3774 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003775
Chris Lattner7adf0762008-08-04 07:31:14 +00003776 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003777
3778 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003779 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003780}
3781
John McCall33ddac02011-01-19 10:06:00 +00003782QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3783 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003784}
3785
John McCall33ddac02011-01-19 10:06:00 +00003786QualType ASTContext::getBaseElementType(QualType type) const {
3787 Qualifiers qs;
3788 while (true) {
3789 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003790 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00003791 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003792
John McCall33ddac02011-01-19 10:06:00 +00003793 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00003794 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003795 }
Mike Stump11289f42009-09-09 15:08:12 +00003796
John McCall33ddac02011-01-19 10:06:00 +00003797 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003798}
3799
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003800/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003801uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003802ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3803 uint64_t ElementCount = 1;
3804 do {
3805 ElementCount *= CA->getSize().getZExtValue();
3806 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3807 } while (CA);
3808 return ElementCount;
3809}
3810
Steve Naroff0af91202007-04-27 21:51:21 +00003811/// getFloatingRank - Return a relative rank for floating point types.
3812/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003813static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003814 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003815 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003816
John McCall9dd450b2009-09-21 23:43:11 +00003817 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3818 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003819 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003820 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00003821 case BuiltinType::Float: return FloatRank;
3822 case BuiltinType::Double: return DoubleRank;
3823 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003824 }
3825}
3826
Mike Stump11289f42009-09-09 15:08:12 +00003827/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3828/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003829/// 'typeDomain' is a real floating point or complex type.
3830/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003831QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3832 QualType Domain) const {
3833 FloatingRank EltRank = getFloatingRank(Size);
3834 if (Domain->isComplexType()) {
3835 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003836 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00003837 case FloatRank: return FloatComplexTy;
3838 case DoubleRank: return DoubleComplexTy;
3839 case LongDoubleRank: return LongDoubleComplexTy;
3840 }
Steve Naroff0af91202007-04-27 21:51:21 +00003841 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003842
3843 assert(Domain->isRealFloatingType() && "Unknown domain!");
3844 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003845 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003846 case FloatRank: return FloatTy;
3847 case DoubleRank: return DoubleTy;
3848 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003849 }
David Blaikief47fa302012-01-17 02:30:50 +00003850 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00003851}
3852
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003853/// getFloatingTypeOrder - Compare the rank of the two specified floating
3854/// point types, ignoring the domain of the type (i.e. 'double' ==
3855/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003856/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003857int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003858 FloatingRank LHSR = getFloatingRank(LHS);
3859 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003860
Chris Lattnerb90739d2008-04-06 23:38:49 +00003861 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003862 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003863 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003864 return 1;
3865 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003866}
3867
Chris Lattner76a00cf2008-04-06 22:59:24 +00003868/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3869/// routine will assert if passed a built-in type that isn't an integer or enum,
3870/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003871unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003872 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003873
Chris Lattner76a00cf2008-04-06 22:59:24 +00003874 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003875 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003876 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003877 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003878 case BuiltinType::Char_S:
3879 case BuiltinType::Char_U:
3880 case BuiltinType::SChar:
3881 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003882 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003883 case BuiltinType::Short:
3884 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003885 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003886 case BuiltinType::Int:
3887 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003888 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003889 case BuiltinType::Long:
3890 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003891 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003892 case BuiltinType::LongLong:
3893 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003894 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003895 case BuiltinType::Int128:
3896 case BuiltinType::UInt128:
3897 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003898 }
3899}
3900
Eli Friedman629ffb92009-08-20 04:21:42 +00003901/// \brief Whether this is a promotable bitfield reference according
3902/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3903///
3904/// \returns the type this bit-field will promote to, or NULL if no
3905/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003906QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003907 if (E->isTypeDependent() || E->isValueDependent())
3908 return QualType();
3909
Eli Friedman629ffb92009-08-20 04:21:42 +00003910 FieldDecl *Field = E->getBitField();
3911 if (!Field)
3912 return QualType();
3913
3914 QualType FT = Field->getType();
3915
Richard Smithcaf33902011-10-10 18:28:20 +00003916 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00003917 uint64_t IntSize = getTypeSize(IntTy);
3918 // GCC extension compatibility: if the bit-field size is less than or equal
3919 // to the size of int, it gets promoted no matter what its type is.
3920 // For instance, unsigned long bf : 4 gets promoted to signed int.
3921 if (BitWidth < IntSize)
3922 return IntTy;
3923
3924 if (BitWidth == IntSize)
3925 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3926
3927 // Types bigger than int are not subject to promotions, and therefore act
3928 // like the base type.
3929 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3930 // is ridiculous.
3931 return QualType();
3932}
3933
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003934/// getPromotedIntegerType - Returns the type that Promotable will
3935/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3936/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003937QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003938 assert(!Promotable.isNull());
3939 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003940 if (const EnumType *ET = Promotable->getAs<EnumType>())
3941 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00003942
3943 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3944 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3945 // (3.9.1) can be converted to a prvalue of the first of the following
3946 // types that can represent all the values of its underlying type:
3947 // int, unsigned int, long int, unsigned long int, long long int, or
3948 // unsigned long long int [...]
3949 // FIXME: Is there some better way to compute this?
3950 if (BT->getKind() == BuiltinType::WChar_S ||
3951 BT->getKind() == BuiltinType::WChar_U ||
3952 BT->getKind() == BuiltinType::Char16 ||
3953 BT->getKind() == BuiltinType::Char32) {
3954 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3955 uint64_t FromSize = getTypeSize(BT);
3956 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3957 LongLongTy, UnsignedLongLongTy };
3958 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3959 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3960 if (FromSize < ToSize ||
3961 (FromSize == ToSize &&
3962 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3963 return PromoteTypes[Idx];
3964 }
3965 llvm_unreachable("char type should fit into long long");
3966 }
3967 }
3968
3969 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003970 if (Promotable->isSignedIntegerType())
3971 return IntTy;
3972 uint64_t PromotableSize = getTypeSize(Promotable);
3973 uint64_t IntSize = getTypeSize(IntTy);
3974 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3975 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3976}
3977
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003978/// \brief Recurses in pointer/array types until it finds an objc retainable
3979/// type and returns its ownership.
3980Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3981 while (!T.isNull()) {
3982 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3983 return T.getObjCLifetime();
3984 if (T->isArrayType())
3985 T = getBaseElementType(T);
3986 else if (const PointerType *PT = T->getAs<PointerType>())
3987 T = PT->getPointeeType();
3988 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00003989 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003990 else
3991 break;
3992 }
3993
3994 return Qualifiers::OCL_None;
3995}
3996
Mike Stump11289f42009-09-09 15:08:12 +00003997/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003998/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003999/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004000int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004001 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4002 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004003 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004004
Chris Lattner76a00cf2008-04-06 22:59:24 +00004005 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4006 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004007
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004008 unsigned LHSRank = getIntegerRank(LHSC);
4009 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004010
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004011 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4012 if (LHSRank == RHSRank) return 0;
4013 return LHSRank > RHSRank ? 1 : -1;
4014 }
Mike Stump11289f42009-09-09 15:08:12 +00004015
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004016 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4017 if (LHSUnsigned) {
4018 // If the unsigned [LHS] type is larger, return it.
4019 if (LHSRank >= RHSRank)
4020 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004021
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004022 // If the signed type can represent all values of the unsigned type, it
4023 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004024 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004025 return -1;
4026 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004027
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004028 // If the unsigned [RHS] type is larger, return it.
4029 if (RHSRank >= LHSRank)
4030 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004031
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004032 // If the signed type can represent all values of the unsigned type, it
4033 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004034 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004035 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004036}
Anders Carlsson98f07902007-08-17 05:31:46 +00004037
Anders Carlsson6d417272009-11-14 21:45:58 +00004038static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004039CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4040 DeclContext *DC, IdentifierInfo *Id) {
4041 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004042 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004043 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004044 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004045 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004046}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004047
Mike Stump11289f42009-09-09 15:08:12 +00004048// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004049QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004050 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00004051 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004052 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004053 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00004054 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004055
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004056 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004057
Anders Carlsson98f07902007-08-17 05:31:46 +00004058 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004059 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004060 // int flags;
4061 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004062 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004063 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004064 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004065 FieldTypes[3] = LongTy;
4066
Anders Carlsson98f07902007-08-17 05:31:46 +00004067 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004068 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004069 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004070 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004071 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00004072 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00004073 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004074 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004075 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004076 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004077 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004078 }
4079
Douglas Gregord5058122010-02-11 01:19:42 +00004080 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004081 }
Mike Stump11289f42009-09-09 15:08:12 +00004082
Anders Carlsson98f07902007-08-17 05:31:46 +00004083 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004084}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004085
Douglas Gregor512b0772009-04-23 22:29:11 +00004086void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004087 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004088 assert(Rec && "Invalid CFConstantStringType");
4089 CFConstantStringTypeDecl = Rec->getDecl();
4090}
4091
Jay Foad39c79802011-01-12 09:06:06 +00004092QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004093 if (BlockDescriptorType)
4094 return getTagDeclType(BlockDescriptorType);
4095
4096 RecordDecl *T;
4097 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004098 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004099 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00004100 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004101
4102 QualType FieldTypes[] = {
4103 UnsignedLongTy,
4104 UnsignedLongTy,
4105 };
4106
4107 const char *FieldNames[] = {
4108 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004109 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004110 };
4111
4112 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004113 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00004114 SourceLocation(),
4115 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004116 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00004117 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004118 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004119 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004120 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00004121 T->addDecl(Field);
4122 }
4123
Douglas Gregord5058122010-02-11 01:19:42 +00004124 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004125
4126 BlockDescriptorType = T;
4127
4128 return getTagDeclType(BlockDescriptorType);
4129}
4130
Jay Foad39c79802011-01-12 09:06:06 +00004131QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004132 if (BlockDescriptorExtendedType)
4133 return getTagDeclType(BlockDescriptorExtendedType);
4134
4135 RecordDecl *T;
4136 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004137 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004138 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00004139 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004140
4141 QualType FieldTypes[] = {
4142 UnsignedLongTy,
4143 UnsignedLongTy,
4144 getPointerType(VoidPtrTy),
4145 getPointerType(VoidPtrTy)
4146 };
4147
4148 const char *FieldNames[] = {
4149 "reserved",
4150 "Size",
4151 "CopyFuncPtr",
4152 "DestroyFuncPtr"
4153 };
4154
4155 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004156 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004157 SourceLocation(),
4158 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004159 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004160 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004161 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004162 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004163 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004164 T->addDecl(Field);
4165 }
4166
Douglas Gregord5058122010-02-11 01:19:42 +00004167 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004168
4169 BlockDescriptorExtendedType = T;
4170
4171 return getTagDeclType(BlockDescriptorExtendedType);
4172}
4173
Jay Foad39c79802011-01-12 09:06:06 +00004174bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCall31168b02011-06-15 23:02:42 +00004175 if (Ty->isObjCRetainableType())
Mike Stump94967902009-10-21 18:16:27 +00004176 return true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004177 if (getLangOpts().CPlusPlus) {
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004178 if (const RecordType *RT = Ty->getAs<RecordType>()) {
4179 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntfcaeae42011-05-25 20:50:04 +00004180 return RD->hasConstCopyConstructor();
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004181
4182 }
4183 }
Mike Stump94967902009-10-21 18:16:27 +00004184 return false;
4185}
4186
Jay Foad39c79802011-01-12 09:06:06 +00004187QualType
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004188ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00004189 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00004190 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00004191 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00004192 // unsigned int __flags;
4193 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00004194 // void *__copy_helper; // as needed
4195 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00004196 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00004197 // } *
4198
Mike Stump94967902009-10-21 18:16:27 +00004199 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
4200
4201 // FIXME: Move up
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004202 SmallString<36> Name;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00004203 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
4204 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00004205 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004206 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00004207 T->startDefinition();
4208 QualType Int32Ty = IntTy;
4209 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
4210 QualType FieldTypes[] = {
4211 getPointerType(VoidPtrTy),
4212 getPointerType(getTagDeclType(T)),
4213 Int32Ty,
4214 Int32Ty,
4215 getPointerType(VoidPtrTy),
4216 getPointerType(VoidPtrTy),
4217 Ty
4218 };
4219
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004220 StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00004221 "__isa",
4222 "__forwarding",
4223 "__flags",
4224 "__size",
4225 "__copy_helper",
4226 "__destroy_helper",
4227 DeclName,
4228 };
4229
4230 for (size_t i = 0; i < 7; ++i) {
4231 if (!HasCopyAndDispose && i >=4 && i <= 5)
4232 continue;
4233 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00004234 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00004235 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004236 FieldTypes[i], /*TInfo=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004237 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004238 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004239 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00004240 T->addDecl(Field);
4241 }
4242
Douglas Gregord5058122010-02-11 01:19:42 +00004243 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00004244
4245 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00004246}
4247
Douglas Gregorbab8a962011-09-08 01:46:34 +00004248TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4249 if (!ObjCInstanceTypeDecl)
4250 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4251 getTranslationUnitDecl(),
4252 SourceLocation(),
4253 SourceLocation(),
4254 &Idents.get("instancetype"),
4255 getTrivialTypeSourceInfo(getObjCIdType()));
4256 return ObjCInstanceTypeDecl;
4257}
4258
Anders Carlsson18acd442007-10-29 06:33:42 +00004259// This returns true if a type has been typedefed to BOOL:
4260// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004261static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004262 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004263 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4264 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004265
Anders Carlssond8499822007-10-29 05:01:08 +00004266 return false;
4267}
4268
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004269/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004270/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004271CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004272 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4273 return CharUnits::Zero();
4274
Ken Dyck40775002010-01-11 17:06:35 +00004275 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004276
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004277 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004278 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004279 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004280 // Treat arrays as pointers, since that's how they're passed in.
4281 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004282 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004283 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004284}
4285
4286static inline
4287std::string charUnitsToString(const CharUnits &CU) {
4288 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004289}
4290
John McCall351762c2011-02-07 10:33:21 +00004291/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004292/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004293std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4294 std::string S;
4295
David Chisnall950a9512009-11-17 19:33:30 +00004296 const BlockDecl *Decl = Expr->getBlockDecl();
4297 QualType BlockTy =
4298 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4299 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00004300 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004301 // Compute size of all parameters.
4302 // Start with computing size of a pointer in number of bytes.
4303 // FIXME: There might(should) be a better way of doing this computation!
4304 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004305 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4306 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004307 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004308 E = Decl->param_end(); PI != E; ++PI) {
4309 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004310 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004311 if (sz.isZero())
4312 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004313 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004314 ParmOffset += sz;
4315 }
4316 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004317 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004318 // Block pointer and offset.
4319 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004320
4321 // Argument types.
4322 ParmOffset = PtrSize;
4323 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4324 Decl->param_end(); PI != E; ++PI) {
4325 ParmVarDecl *PVDecl = *PI;
4326 QualType PType = PVDecl->getOriginalType();
4327 if (const ArrayType *AT =
4328 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4329 // Use array's original type only if it has known number of
4330 // elements.
4331 if (!isa<ConstantArrayType>(AT))
4332 PType = PVDecl->getType();
4333 } else if (PType->isFunctionType())
4334 PType = PVDecl->getType();
4335 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004336 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004337 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004338 }
John McCall351762c2011-02-07 10:33:21 +00004339
4340 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004341}
4342
Douglas Gregora9d84932011-05-27 01:19:52 +00004343bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004344 std::string& S) {
4345 // Encode result type.
4346 getObjCEncodingForType(Decl->getResultType(), S);
4347 CharUnits ParmOffset;
4348 // Compute size of all parameters.
4349 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4350 E = Decl->param_end(); PI != E; ++PI) {
4351 QualType PType = (*PI)->getType();
4352 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004353 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004354 continue;
4355
David Chisnall50e4eba2010-12-30 14:05:53 +00004356 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004357 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004358 ParmOffset += sz;
4359 }
4360 S += charUnitsToString(ParmOffset);
4361 ParmOffset = CharUnits::Zero();
4362
4363 // Argument types.
4364 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4365 E = Decl->param_end(); PI != E; ++PI) {
4366 ParmVarDecl *PVDecl = *PI;
4367 QualType PType = PVDecl->getOriginalType();
4368 if (const ArrayType *AT =
4369 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4370 // Use array's original type only if it has known number of
4371 // elements.
4372 if (!isa<ConstantArrayType>(AT))
4373 PType = PVDecl->getType();
4374 } else if (PType->isFunctionType())
4375 PType = PVDecl->getType();
4376 getObjCEncodingForType(PType, S);
4377 S += charUnitsToString(ParmOffset);
4378 ParmOffset += getObjCEncodingTypeSize(PType);
4379 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004380
4381 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004382}
4383
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004384/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4385/// method parameter or return type. If Extended, include class names and
4386/// block object types.
4387void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4388 QualType T, std::string& S,
4389 bool Extended) const {
4390 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4391 getObjCEncodingForTypeQualifier(QT, S);
4392 // Encode parameter type.
4393 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4394 true /*OutermostType*/,
4395 false /*EncodingProperty*/,
4396 false /*StructField*/,
4397 Extended /*EncodeBlockParameters*/,
4398 Extended /*EncodeClassNames*/);
4399}
4400
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004401/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004402/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004403bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004404 std::string& S,
4405 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004406 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004407 // Encode return type.
4408 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4409 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004410 // Compute size of all parameters.
4411 // Start with computing size of a pointer in number of bytes.
4412 // FIXME: There might(should) be a better way of doing this computation!
4413 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004414 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004415 // The first two arguments (self and _cmd) are pointers; account for
4416 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004417 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004418 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004419 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004420 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004421 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004422 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004423 continue;
4424
Ken Dyck40775002010-01-11 17:06:35 +00004425 assert (sz.isPositive() &&
4426 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004427 ParmOffset += sz;
4428 }
Ken Dyck40775002010-01-11 17:06:35 +00004429 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004430 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004431 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004432
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004433 // Argument types.
4434 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004435 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004436 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004437 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004438 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004439 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004440 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4441 // Use array's original type only if it has known number of
4442 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004443 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004444 PType = PVDecl->getType();
4445 } else if (PType->isFunctionType())
4446 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004447 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4448 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004449 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004450 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004451 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004452
4453 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004454}
4455
Daniel Dunbar4932b362008-08-28 04:38:10 +00004456/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004457/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004458/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4459/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004460/// Property attributes are stored as a comma-delimited C string. The simple
4461/// attributes readonly and bycopy are encoded as single characters. The
4462/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4463/// encoded as single characters, followed by an identifier. Property types
4464/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004465/// these attributes are defined by the following enumeration:
4466/// @code
4467/// enum PropertyAttributes {
4468/// kPropertyReadOnly = 'R', // property is read-only.
4469/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4470/// kPropertyByref = '&', // property is a reference to the value last assigned
4471/// kPropertyDynamic = 'D', // property is dynamic
4472/// kPropertyGetter = 'G', // followed by getter selector name
4473/// kPropertySetter = 'S', // followed by setter selector name
4474/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004475/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004476/// kPropertyWeak = 'W' // 'weak' property
4477/// kPropertyStrong = 'P' // property GC'able
4478/// kPropertyNonAtomic = 'N' // property non-atomic
4479/// };
4480/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004481void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004482 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004483 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004484 // Collect information from the property implementation decl(s).
4485 bool Dynamic = false;
4486 ObjCPropertyImplDecl *SynthesizePID = 0;
4487
4488 // FIXME: Duplicated code due to poor abstraction.
4489 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004490 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004491 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4492 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004493 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004494 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004495 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004496 if (PID->getPropertyDecl() == PD) {
4497 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4498 Dynamic = true;
4499 } else {
4500 SynthesizePID = PID;
4501 }
4502 }
4503 }
4504 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004505 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004506 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004507 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004508 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004509 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004510 if (PID->getPropertyDecl() == PD) {
4511 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4512 Dynamic = true;
4513 } else {
4514 SynthesizePID = PID;
4515 }
4516 }
Mike Stump11289f42009-09-09 15:08:12 +00004517 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004518 }
4519 }
4520
4521 // FIXME: This is not very efficient.
4522 S = "T";
4523
4524 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004525 // GCC has some special rules regarding encoding of properties which
4526 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004527 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004528 true /* outermost type */,
4529 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004530
4531 if (PD->isReadOnly()) {
4532 S += ",R";
4533 } else {
4534 switch (PD->getSetterKind()) {
4535 case ObjCPropertyDecl::Assign: break;
4536 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004537 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004538 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004539 }
4540 }
4541
4542 // It really isn't clear at all what this means, since properties
4543 // are "dynamic by default".
4544 if (Dynamic)
4545 S += ",D";
4546
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004547 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4548 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004549
Daniel Dunbar4932b362008-08-28 04:38:10 +00004550 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4551 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004552 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004553 }
4554
4555 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4556 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004557 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004558 }
4559
4560 if (SynthesizePID) {
4561 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4562 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004563 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004564 }
4565
4566 // FIXME: OBJCGC: weak & strong
4567}
4568
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004569/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004570/// Another legacy compatibility encoding: 32-bit longs are encoded as
4571/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004572/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4573///
4574void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004575 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004576 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004577 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004578 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004579 else
Jay Foad39c79802011-01-12 09:06:06 +00004580 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004581 PointeeTy = IntTy;
4582 }
4583 }
4584}
4585
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004586void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004587 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004588 // We follow the behavior of gcc, expanding structures which are
4589 // directly pointed to, and expanding embedded structures. Note that
4590 // these rules are sufficient to prevent recursive encoding of the
4591 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004592 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004593 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004594}
4595
David Chisnallb190a2c2010-06-04 01:10:52 +00004596static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4597 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004598 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnallb190a2c2010-06-04 01:10:52 +00004599 case BuiltinType::Void: return 'v';
4600 case BuiltinType::Bool: return 'B';
4601 case BuiltinType::Char_U:
4602 case BuiltinType::UChar: return 'C';
4603 case BuiltinType::UShort: return 'S';
4604 case BuiltinType::UInt: return 'I';
4605 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004606 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004607 case BuiltinType::UInt128: return 'T';
4608 case BuiltinType::ULongLong: return 'Q';
4609 case BuiltinType::Char_S:
4610 case BuiltinType::SChar: return 'c';
4611 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004612 case BuiltinType::WChar_S:
4613 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004614 case BuiltinType::Int: return 'i';
4615 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004616 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004617 case BuiltinType::LongLong: return 'q';
4618 case BuiltinType::Int128: return 't';
4619 case BuiltinType::Float: return 'f';
4620 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004621 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004622 }
4623}
4624
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004625static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4626 EnumDecl *Enum = ET->getDecl();
4627
4628 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4629 if (!Enum->isFixed())
4630 return 'i';
4631
4632 // The encoding of a fixed enum type matches its fixed underlying type.
4633 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4634}
4635
Jay Foad39c79802011-01-12 09:06:06 +00004636static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004637 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00004638 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004639 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004640 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4641 // The GNU runtime requires more information; bitfields are encoded as b,
4642 // then the offset (in bits) of the first element, then the type of the
4643 // bitfield, then the size in bits. For example, in this structure:
4644 //
4645 // struct
4646 // {
4647 // int integer;
4648 // int flags:2;
4649 // };
4650 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4651 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4652 // information is not especially sensible, but we're stuck with it for
4653 // compatibility with GCC, although providing it breaks anything that
4654 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00004655 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004656 const RecordDecl *RD = FD->getParent();
4657 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004658 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004659 if (const EnumType *ET = T->getAs<EnumType>())
4660 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnall6f0a7d22010-12-26 20:12:30 +00004661 else
Jay Foad39c79802011-01-12 09:06:06 +00004662 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004663 }
Richard Smithcaf33902011-10-10 18:28:20 +00004664 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004665}
4666
Daniel Dunbar07d07852009-10-18 21:17:35 +00004667// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004668void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4669 bool ExpandPointedToStructures,
4670 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004671 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004672 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004673 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004674 bool StructField,
4675 bool EncodeBlockParameters,
4676 bool EncodeClassNames) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004677 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004678 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004679 return EncodeBitField(this, S, T, FD);
4680 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004681 return;
4682 }
Mike Stump11289f42009-09-09 15:08:12 +00004683
John McCall9dd450b2009-09-21 23:43:11 +00004684 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004685 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004686 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004687 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004688 return;
4689 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004690
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004691 // encoding for pointer or r3eference types.
4692 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004693 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004694 if (PT->isObjCSelType()) {
4695 S += ':';
4696 return;
4697 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004698 PointeeTy = PT->getPointeeType();
4699 }
4700 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4701 PointeeTy = RT->getPointeeType();
4702 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004703 bool isReadOnly = false;
4704 // For historical/compatibility reasons, the read-only qualifier of the
4705 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4706 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004707 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004708 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004709 if (OutermostType && T.isConstQualified()) {
4710 isReadOnly = true;
4711 S += 'r';
4712 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004713 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004714 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004715 while (P->getAs<PointerType>())
4716 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004717 if (P.isConstQualified()) {
4718 isReadOnly = true;
4719 S += 'r';
4720 }
4721 }
4722 if (isReadOnly) {
4723 // Another legacy compatibility encoding. Some ObjC qualifier and type
4724 // combinations need to be rearranged.
4725 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004726 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004727 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004728 }
Mike Stump11289f42009-09-09 15:08:12 +00004729
Anders Carlssond8499822007-10-29 05:01:08 +00004730 if (PointeeTy->isCharType()) {
4731 // char pointer types should be encoded as '*' unless it is a
4732 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004733 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004734 S += '*';
4735 return;
4736 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004737 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004738 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4739 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4740 S += '#';
4741 return;
4742 }
4743 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4744 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4745 S += '@';
4746 return;
4747 }
4748 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004749 }
Anders Carlssond8499822007-10-29 05:01:08 +00004750 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004751 getLegacyIntegralTypeEncoding(PointeeTy);
4752
Mike Stump11289f42009-09-09 15:08:12 +00004753 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004754 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004755 return;
4756 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004757
Chris Lattnere7cabb92009-07-13 00:10:46 +00004758 if (const ArrayType *AT =
4759 // Ignore type qualifiers etc.
4760 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004761 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004762 // Incomplete arrays are encoded as a pointer to the array element.
4763 S += '^';
4764
Mike Stump11289f42009-09-09 15:08:12 +00004765 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004766 false, ExpandStructures, FD);
4767 } else {
4768 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004769
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004770 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4771 if (getTypeSize(CAT->getElementType()) == 0)
4772 S += '0';
4773 else
4774 S += llvm::utostr(CAT->getSize().getZExtValue());
4775 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004776 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004777 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4778 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00004779 S += '0';
4780 }
Mike Stump11289f42009-09-09 15:08:12 +00004781
4782 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004783 false, ExpandStructures, FD);
4784 S += ']';
4785 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004786 return;
4787 }
Mike Stump11289f42009-09-09 15:08:12 +00004788
John McCall9dd450b2009-09-21 23:43:11 +00004789 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004790 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004791 return;
4792 }
Mike Stump11289f42009-09-09 15:08:12 +00004793
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004794 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004795 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004796 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004797 // Anonymous structures print as '?'
4798 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4799 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004800 if (ClassTemplateSpecializationDecl *Spec
4801 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4802 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4803 std::string TemplateArgsStr
4804 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004805 TemplateArgs.data(),
4806 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00004807 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004808
4809 S += TemplateArgsStr;
4810 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004811 } else {
4812 S += '?';
4813 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004814 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004815 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004816 if (!RDecl->isUnion()) {
4817 getObjCEncodingForStructureImpl(RDecl, S, FD);
4818 } else {
4819 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4820 FieldEnd = RDecl->field_end();
4821 Field != FieldEnd; ++Field) {
4822 if (FD) {
4823 S += '"';
4824 S += Field->getNameAsString();
4825 S += '"';
4826 }
Mike Stump11289f42009-09-09 15:08:12 +00004827
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004828 // Special case bit-fields.
4829 if (Field->isBitField()) {
4830 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00004831 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004832 } else {
4833 QualType qt = Field->getType();
4834 getLegacyIntegralTypeEncoding(qt);
4835 getObjCEncodingForTypeImpl(qt, S, false, true,
4836 FD, /*OutermostType*/false,
4837 /*EncodingProperty*/false,
4838 /*StructField*/true);
4839 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004840 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004841 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004842 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004843 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004844 return;
4845 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004846
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004847 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004848 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004849 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004850 else
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004851 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004852 return;
4853 }
Mike Stump11289f42009-09-09 15:08:12 +00004854
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004855 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004856 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004857 if (EncodeBlockParameters) {
4858 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4859
4860 S += '<';
4861 // Block return type
4862 getObjCEncodingForTypeImpl(FT->getResultType(), S,
4863 ExpandPointedToStructures, ExpandStructures,
4864 FD,
4865 false /* OutermostType */,
4866 EncodingProperty,
4867 false /* StructField */,
4868 EncodeBlockParameters,
4869 EncodeClassNames);
4870 // Block self
4871 S += "@?";
4872 // Block parameters
4873 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4874 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4875 E = FPT->arg_type_end(); I && (I != E); ++I) {
4876 getObjCEncodingForTypeImpl(*I, S,
4877 ExpandPointedToStructures,
4878 ExpandStructures,
4879 FD,
4880 false /* OutermostType */,
4881 EncodingProperty,
4882 false /* StructField */,
4883 EncodeBlockParameters,
4884 EncodeClassNames);
4885 }
4886 }
4887 S += '>';
4888 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004889 return;
4890 }
Mike Stump11289f42009-09-09 15:08:12 +00004891
John McCall8b07ec22010-05-15 11:32:37 +00004892 // Ignore protocol qualifiers when mangling at this level.
4893 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4894 T = OT->getBaseType();
4895
John McCall8ccfcb52009-09-24 19:53:00 +00004896 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004897 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004898 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004899 S += '{';
4900 const IdentifierInfo *II = OI->getIdentifier();
4901 S += II->getName();
4902 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00004903 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004904 DeepCollectObjCIvars(OI, true, Ivars);
4905 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004906 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004907 if (Field->isBitField())
4908 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004909 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004910 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004911 }
4912 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004913 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004914 }
Mike Stump11289f42009-09-09 15:08:12 +00004915
John McCall9dd450b2009-09-21 23:43:11 +00004916 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004917 if (OPT->isObjCIdType()) {
4918 S += '@';
4919 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004920 }
Mike Stump11289f42009-09-09 15:08:12 +00004921
Steve Narofff0c86112009-10-28 22:03:49 +00004922 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4923 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4924 // Since this is a binary compatibility issue, need to consult with runtime
4925 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004926 S += '#';
4927 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004928 }
Mike Stump11289f42009-09-09 15:08:12 +00004929
Chris Lattnere7cabb92009-07-13 00:10:46 +00004930 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004931 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004932 ExpandPointedToStructures,
4933 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004934 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004935 // Note that we do extended encoding of protocol qualifer list
4936 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004937 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004938 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4939 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004940 S += '<';
4941 S += (*I)->getNameAsString();
4942 S += '>';
4943 }
4944 S += '"';
4945 }
4946 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004947 }
Mike Stump11289f42009-09-09 15:08:12 +00004948
Chris Lattnere7cabb92009-07-13 00:10:46 +00004949 QualType PointeeTy = OPT->getPointeeType();
4950 if (!EncodingProperty &&
4951 isa<TypedefType>(PointeeTy.getTypePtr())) {
4952 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004953 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004954 // {...};
4955 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004956 getObjCEncodingForTypeImpl(PointeeTy, S,
4957 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004958 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004959 return;
4960 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004961
4962 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004963 if (OPT->getInterfaceDecl() &&
4964 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004965 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004966 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004967 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4968 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004969 S += '<';
4970 S += (*I)->getNameAsString();
4971 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004972 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004973 S += '"';
4974 }
4975 return;
4976 }
Mike Stump11289f42009-09-09 15:08:12 +00004977
John McCalla9e6e8d2010-05-17 23:56:34 +00004978 // gcc just blithely ignores member pointers.
4979 // TODO: maybe there should be a mangling for these
4980 if (T->getAs<MemberPointerType>())
4981 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004982
4983 if (T->isVectorType()) {
4984 // This matches gcc's encoding, even though technically it is
4985 // insufficient.
4986 // FIXME. We should do a better job than gcc.
4987 return;
4988 }
4989
David Blaikie83d382b2011-09-23 05:06:16 +00004990 llvm_unreachable("@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004991}
4992
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004993void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4994 std::string &S,
4995 const FieldDecl *FD,
4996 bool includeVBases) const {
4997 assert(RDecl && "Expected non-null RecordDecl");
4998 assert(!RDecl->isUnion() && "Should not be called for unions");
4999 if (!RDecl->getDefinition())
5000 return;
5001
5002 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5003 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5004 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5005
5006 if (CXXRec) {
5007 for (CXXRecordDecl::base_class_iterator
5008 BI = CXXRec->bases_begin(),
5009 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5010 if (!BI->isVirtual()) {
5011 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005012 if (base->isEmpty())
5013 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005014 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005015 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5016 std::make_pair(offs, base));
5017 }
5018 }
5019 }
5020
5021 unsigned i = 0;
5022 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5023 FieldEnd = RDecl->field_end();
5024 Field != FieldEnd; ++Field, ++i) {
5025 uint64_t offs = layout.getFieldOffset(i);
5026 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00005027 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005028 }
5029
5030 if (CXXRec && includeVBases) {
5031 for (CXXRecordDecl::base_class_iterator
5032 BI = CXXRec->vbases_begin(),
5033 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5034 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005035 if (base->isEmpty())
5036 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005037 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005038 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5039 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5040 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005041 }
5042 }
5043
5044 CharUnits size;
5045 if (CXXRec) {
5046 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5047 } else {
5048 size = layout.getSize();
5049 }
5050
5051 uint64_t CurOffs = 0;
5052 std::multimap<uint64_t, NamedDecl *>::iterator
5053 CurLayObj = FieldOrBaseOffsets.begin();
5054
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005055 if (CXXRec && CXXRec->isDynamicClass() &&
5056 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005057 if (FD) {
5058 S += "\"_vptr$";
5059 std::string recname = CXXRec->getNameAsString();
5060 if (recname.empty()) recname = "?";
5061 S += recname;
5062 S += '"';
5063 }
5064 S += "^^?";
5065 CurOffs += getTypeSize(VoidPtrTy);
5066 }
5067
5068 if (!RDecl->hasFlexibleArrayMember()) {
5069 // Mark the end of the structure.
5070 uint64_t offs = toBits(size);
5071 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5072 std::make_pair(offs, (NamedDecl*)0));
5073 }
5074
5075 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5076 assert(CurOffs <= CurLayObj->first);
5077
5078 if (CurOffs < CurLayObj->first) {
5079 uint64_t padding = CurLayObj->first - CurOffs;
5080 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5081 // packing/alignment of members is different that normal, in which case
5082 // the encoding will be out-of-sync with the real layout.
5083 // If the runtime switches to just consider the size of types without
5084 // taking into account alignment, we could make padding explicit in the
5085 // encoding (e.g. using arrays of chars). The encoding strings would be
5086 // longer then though.
5087 CurOffs += padding;
5088 }
5089
5090 NamedDecl *dcl = CurLayObj->second;
5091 if (dcl == 0)
5092 break; // reached end of structure.
5093
5094 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5095 // We expand the bases without their virtual bases since those are going
5096 // in the initial structure. Note that this differs from gcc which
5097 // expands virtual bases each time one is encountered in the hierarchy,
5098 // making the encoding type bigger than it really is.
5099 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005100 assert(!base->isEmpty());
5101 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005102 } else {
5103 FieldDecl *field = cast<FieldDecl>(dcl);
5104 if (FD) {
5105 S += '"';
5106 S += field->getNameAsString();
5107 S += '"';
5108 }
5109
5110 if (field->isBitField()) {
5111 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00005112 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005113 } else {
5114 QualType qt = field->getType();
5115 getLegacyIntegralTypeEncoding(qt);
5116 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5117 /*OutermostType*/false,
5118 /*EncodingProperty*/false,
5119 /*StructField*/true);
5120 CurOffs += getTypeSize(field->getType());
5121 }
5122 }
5123 }
5124}
5125
Mike Stump11289f42009-09-09 15:08:12 +00005126void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005127 std::string& S) const {
5128 if (QT & Decl::OBJC_TQ_In)
5129 S += 'n';
5130 if (QT & Decl::OBJC_TQ_Inout)
5131 S += 'N';
5132 if (QT & Decl::OBJC_TQ_Out)
5133 S += 'o';
5134 if (QT & Decl::OBJC_TQ_Bycopy)
5135 S += 'O';
5136 if (QT & Decl::OBJC_TQ_Byref)
5137 S += 'R';
5138 if (QT & Decl::OBJC_TQ_Oneway)
5139 S += 'V';
5140}
5141
Douglas Gregor3ea72692011-08-12 05:46:01 +00005142TypedefDecl *ASTContext::getObjCIdDecl() const {
5143 if (!ObjCIdDecl) {
5144 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5145 T = getObjCObjectPointerType(T);
5146 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5147 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5148 getTranslationUnitDecl(),
5149 SourceLocation(), SourceLocation(),
5150 &Idents.get("id"), IdInfo);
5151 }
5152
5153 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005154}
5155
Douglas Gregor52e02802011-08-12 06:17:30 +00005156TypedefDecl *ASTContext::getObjCSelDecl() const {
5157 if (!ObjCSelDecl) {
5158 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5159 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5160 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5161 getTranslationUnitDecl(),
5162 SourceLocation(), SourceLocation(),
5163 &Idents.get("SEL"), SelInfo);
5164 }
5165 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005166}
5167
Douglas Gregor0a586182011-08-12 05:59:41 +00005168TypedefDecl *ASTContext::getObjCClassDecl() const {
5169 if (!ObjCClassDecl) {
5170 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5171 T = getObjCObjectPointerType(T);
5172 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5173 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5174 getTranslationUnitDecl(),
5175 SourceLocation(), SourceLocation(),
5176 &Idents.get("Class"), ClassInfo);
5177 }
5178
5179 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005180}
5181
Douglas Gregord53ae832012-01-17 18:09:05 +00005182ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5183 if (!ObjCProtocolClassDecl) {
5184 ObjCProtocolClassDecl
5185 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5186 SourceLocation(),
5187 &Idents.get("Protocol"),
5188 /*PrevDecl=*/0,
5189 SourceLocation(), true);
5190 }
5191
5192 return ObjCProtocolClassDecl;
5193}
5194
Meador Inge5d3fb222012-06-16 03:34:49 +00005195//===----------------------------------------------------------------------===//
5196// __builtin_va_list Construction Functions
5197//===----------------------------------------------------------------------===//
5198
5199static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5200 // typedef char* __builtin_va_list;
5201 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5202 TypeSourceInfo *TInfo
5203 = Context->getTrivialTypeSourceInfo(CharPtrType);
5204
5205 TypedefDecl *VaListTypeDecl
5206 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5207 Context->getTranslationUnitDecl(),
5208 SourceLocation(), SourceLocation(),
5209 &Context->Idents.get("__builtin_va_list"),
5210 TInfo);
5211 return VaListTypeDecl;
5212}
5213
5214static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5215 // typedef void* __builtin_va_list;
5216 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5217 TypeSourceInfo *TInfo
5218 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5219
5220 TypedefDecl *VaListTypeDecl
5221 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5222 Context->getTranslationUnitDecl(),
5223 SourceLocation(), SourceLocation(),
5224 &Context->Idents.get("__builtin_va_list"),
5225 TInfo);
5226 return VaListTypeDecl;
5227}
5228
5229static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5230 // typedef struct __va_list_tag {
5231 RecordDecl *VaListTagDecl;
5232
5233 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5234 Context->getTranslationUnitDecl(),
5235 &Context->Idents.get("__va_list_tag"));
5236 VaListTagDecl->startDefinition();
5237
5238 const size_t NumFields = 5;
5239 QualType FieldTypes[NumFields];
5240 const char *FieldNames[NumFields];
5241
5242 // unsigned char gpr;
5243 FieldTypes[0] = Context->UnsignedCharTy;
5244 FieldNames[0] = "gpr";
5245
5246 // unsigned char fpr;
5247 FieldTypes[1] = Context->UnsignedCharTy;
5248 FieldNames[1] = "fpr";
5249
5250 // unsigned short reserved;
5251 FieldTypes[2] = Context->UnsignedShortTy;
5252 FieldNames[2] = "reserved";
5253
5254 // void* overflow_arg_area;
5255 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5256 FieldNames[3] = "overflow_arg_area";
5257
5258 // void* reg_save_area;
5259 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5260 FieldNames[4] = "reg_save_area";
5261
5262 // Create fields
5263 for (unsigned i = 0; i < NumFields; ++i) {
5264 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5265 SourceLocation(),
5266 SourceLocation(),
5267 &Context->Idents.get(FieldNames[i]),
5268 FieldTypes[i], /*TInfo=*/0,
5269 /*BitWidth=*/0,
5270 /*Mutable=*/false,
5271 ICIS_NoInit);
5272 Field->setAccess(AS_public);
5273 VaListTagDecl->addDecl(Field);
5274 }
5275 VaListTagDecl->completeDefinition();
5276 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005277 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005278
5279 // } __va_list_tag;
5280 TypedefDecl *VaListTagTypedefDecl
5281 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5282 Context->getTranslationUnitDecl(),
5283 SourceLocation(), SourceLocation(),
5284 &Context->Idents.get("__va_list_tag"),
5285 Context->getTrivialTypeSourceInfo(VaListTagType));
5286 QualType VaListTagTypedefType =
5287 Context->getTypedefType(VaListTagTypedefDecl);
5288
5289 // typedef __va_list_tag __builtin_va_list[1];
5290 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5291 QualType VaListTagArrayType
5292 = Context->getConstantArrayType(VaListTagTypedefType,
5293 Size, ArrayType::Normal, 0);
5294 TypeSourceInfo *TInfo
5295 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5296 TypedefDecl *VaListTypedefDecl
5297 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5298 Context->getTranslationUnitDecl(),
5299 SourceLocation(), SourceLocation(),
5300 &Context->Idents.get("__builtin_va_list"),
5301 TInfo);
5302
5303 return VaListTypedefDecl;
5304}
5305
5306static TypedefDecl *
5307CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5308 // typedef struct __va_list_tag {
5309 RecordDecl *VaListTagDecl;
5310 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5311 Context->getTranslationUnitDecl(),
5312 &Context->Idents.get("__va_list_tag"));
5313 VaListTagDecl->startDefinition();
5314
5315 const size_t NumFields = 4;
5316 QualType FieldTypes[NumFields];
5317 const char *FieldNames[NumFields];
5318
5319 // unsigned gp_offset;
5320 FieldTypes[0] = Context->UnsignedIntTy;
5321 FieldNames[0] = "gp_offset";
5322
5323 // unsigned fp_offset;
5324 FieldTypes[1] = Context->UnsignedIntTy;
5325 FieldNames[1] = "fp_offset";
5326
5327 // void* overflow_arg_area;
5328 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5329 FieldNames[2] = "overflow_arg_area";
5330
5331 // void* reg_save_area;
5332 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5333 FieldNames[3] = "reg_save_area";
5334
5335 // Create fields
5336 for (unsigned i = 0; i < NumFields; ++i) {
5337 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5338 VaListTagDecl,
5339 SourceLocation(),
5340 SourceLocation(),
5341 &Context->Idents.get(FieldNames[i]),
5342 FieldTypes[i], /*TInfo=*/0,
5343 /*BitWidth=*/0,
5344 /*Mutable=*/false,
5345 ICIS_NoInit);
5346 Field->setAccess(AS_public);
5347 VaListTagDecl->addDecl(Field);
5348 }
5349 VaListTagDecl->completeDefinition();
5350 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005351 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005352
5353 // } __va_list_tag;
5354 TypedefDecl *VaListTagTypedefDecl
5355 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5356 Context->getTranslationUnitDecl(),
5357 SourceLocation(), SourceLocation(),
5358 &Context->Idents.get("__va_list_tag"),
5359 Context->getTrivialTypeSourceInfo(VaListTagType));
5360 QualType VaListTagTypedefType =
5361 Context->getTypedefType(VaListTagTypedefDecl);
5362
5363 // typedef __va_list_tag __builtin_va_list[1];
5364 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5365 QualType VaListTagArrayType
5366 = Context->getConstantArrayType(VaListTagTypedefType,
5367 Size, ArrayType::Normal,0);
5368 TypeSourceInfo *TInfo
5369 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5370 TypedefDecl *VaListTypedefDecl
5371 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5372 Context->getTranslationUnitDecl(),
5373 SourceLocation(), SourceLocation(),
5374 &Context->Idents.get("__builtin_va_list"),
5375 TInfo);
5376
5377 return VaListTypedefDecl;
5378}
5379
5380static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5381 // typedef int __builtin_va_list[4];
5382 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5383 QualType IntArrayType
5384 = Context->getConstantArrayType(Context->IntTy,
5385 Size, ArrayType::Normal, 0);
5386 TypedefDecl *VaListTypedefDecl
5387 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5388 Context->getTranslationUnitDecl(),
5389 SourceLocation(), SourceLocation(),
5390 &Context->Idents.get("__builtin_va_list"),
5391 Context->getTrivialTypeSourceInfo(IntArrayType));
5392
5393 return VaListTypedefDecl;
5394}
5395
5396static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5397 TargetInfo::BuiltinVaListKind Kind) {
5398 switch (Kind) {
5399 case TargetInfo::CharPtrBuiltinVaList:
5400 return CreateCharPtrBuiltinVaListDecl(Context);
5401 case TargetInfo::VoidPtrBuiltinVaList:
5402 return CreateVoidPtrBuiltinVaListDecl(Context);
5403 case TargetInfo::PowerABIBuiltinVaList:
5404 return CreatePowerABIBuiltinVaListDecl(Context);
5405 case TargetInfo::X86_64ABIBuiltinVaList:
5406 return CreateX86_64ABIBuiltinVaListDecl(Context);
5407 case TargetInfo::PNaClABIBuiltinVaList:
5408 return CreatePNaClABIBuiltinVaListDecl(Context);
5409 }
5410
5411 llvm_unreachable("Unhandled __builtin_va_list type kind");
5412}
5413
5414TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5415 if (!BuiltinVaListDecl)
5416 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5417
5418 return BuiltinVaListDecl;
5419}
5420
Meador Ingecfb60902012-07-01 15:57:25 +00005421QualType ASTContext::getVaListTagType() const {
5422 // Force the creation of VaListTagTy by building the __builtin_va_list
5423 // declaration.
5424 if (VaListTagTy.isNull())
5425 (void) getBuiltinVaListDecl();
5426
5427 return VaListTagTy;
5428}
5429
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005430void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00005431 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00005432 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00005433
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005434 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00005435}
5436
John McCalld28ae272009-12-02 08:04:21 +00005437/// \brief Retrieve the template name that corresponds to a non-empty
5438/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00005439TemplateName
5440ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5441 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00005442 unsigned size = End - Begin;
5443 assert(size > 1 && "set is not overloaded!");
5444
5445 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5446 size * sizeof(FunctionTemplateDecl*));
5447 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5448
5449 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00005450 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00005451 NamedDecl *D = *I;
5452 assert(isa<FunctionTemplateDecl>(D) ||
5453 (isa<UsingShadowDecl>(D) &&
5454 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5455 *Storage++ = D;
5456 }
5457
5458 return TemplateName(OT);
5459}
5460
Douglas Gregordc572a32009-03-30 22:58:21 +00005461/// \brief Retrieve the template name that represents a qualified
5462/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00005463TemplateName
5464ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5465 bool TemplateKeyword,
5466 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00005467 assert(NNS && "Missing nested-name-specifier in qualified template name");
5468
Douglas Gregorc42075a2010-02-04 18:10:26 +00005469 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00005470 llvm::FoldingSetNodeID ID;
5471 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5472
5473 void *InsertPos = 0;
5474 QualifiedTemplateName *QTN =
5475 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5476 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00005477 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
5478 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00005479 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5480 }
5481
5482 return TemplateName(QTN);
5483}
5484
5485/// \brief Retrieve the template name that represents a dependent
5486/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00005487TemplateName
5488ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5489 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00005490 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00005491 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00005492
5493 llvm::FoldingSetNodeID ID;
5494 DependentTemplateName::Profile(ID, NNS, Name);
5495
5496 void *InsertPos = 0;
5497 DependentTemplateName *QTN =
5498 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5499
5500 if (QTN)
5501 return TemplateName(QTN);
5502
5503 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5504 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00005505 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5506 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00005507 } else {
5508 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00005509 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5510 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005511 DependentTemplateName *CheckQTN =
5512 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5513 assert(!CheckQTN && "Dependent type name canonicalization broken");
5514 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00005515 }
5516
5517 DependentTemplateNames.InsertNode(QTN, InsertPos);
5518 return TemplateName(QTN);
5519}
5520
Douglas Gregor71395fa2009-11-04 00:56:37 +00005521/// \brief Retrieve the template name that represents a dependent
5522/// template name such as \c MetaFun::template operator+.
5523TemplateName
5524ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00005525 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00005526 assert((!NNS || NNS->isDependent()) &&
5527 "Nested name specifier must be dependent");
5528
5529 llvm::FoldingSetNodeID ID;
5530 DependentTemplateName::Profile(ID, NNS, Operator);
5531
5532 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00005533 DependentTemplateName *QTN
5534 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005535
5536 if (QTN)
5537 return TemplateName(QTN);
5538
5539 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5540 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00005541 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5542 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005543 } else {
5544 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00005545 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5546 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005547
5548 DependentTemplateName *CheckQTN
5549 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5550 assert(!CheckQTN && "Dependent template name canonicalization broken");
5551 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00005552 }
5553
5554 DependentTemplateNames.InsertNode(QTN, InsertPos);
5555 return TemplateName(QTN);
5556}
5557
Douglas Gregor5590be02011-01-15 06:45:20 +00005558TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00005559ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5560 TemplateName replacement) const {
5561 llvm::FoldingSetNodeID ID;
5562 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5563
5564 void *insertPos = 0;
5565 SubstTemplateTemplateParmStorage *subst
5566 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5567
5568 if (!subst) {
5569 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5570 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5571 }
5572
5573 return TemplateName(subst);
5574}
5575
5576TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00005577ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5578 const TemplateArgument &ArgPack) const {
5579 ASTContext &Self = const_cast<ASTContext &>(*this);
5580 llvm::FoldingSetNodeID ID;
5581 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5582
5583 void *InsertPos = 0;
5584 SubstTemplateTemplateParmPackStorage *Subst
5585 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5586
5587 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00005588 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00005589 ArgPack.pack_size(),
5590 ArgPack.pack_begin());
5591 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5592 }
5593
5594 return TemplateName(Subst);
5595}
5596
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005597/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00005598/// TargetInfo, produce the corresponding type. The unsigned @p Type
5599/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00005600CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005601 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00005602 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005603 case TargetInfo::SignedShort: return ShortTy;
5604 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5605 case TargetInfo::SignedInt: return IntTy;
5606 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5607 case TargetInfo::SignedLong: return LongTy;
5608 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5609 case TargetInfo::SignedLongLong: return LongLongTy;
5610 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5611 }
5612
David Blaikie83d382b2011-09-23 05:06:16 +00005613 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005614}
Ted Kremenek77c51b22008-07-24 23:58:27 +00005615
5616//===----------------------------------------------------------------------===//
5617// Type Predicates.
5618//===----------------------------------------------------------------------===//
5619
Fariborz Jahanian96207692009-02-18 21:49:28 +00005620/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5621/// garbage collection attribute.
5622///
John McCall553d45a2011-01-12 00:34:59 +00005623Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005624 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00005625 return Qualifiers::GCNone;
5626
David Blaikiebbafb8a2012-03-11 07:00:24 +00005627 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00005628 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5629
5630 // Default behaviour under objective-C's gc is for ObjC pointers
5631 // (or pointers to them) be treated as though they were declared
5632 // as __strong.
5633 if (GCAttrs == Qualifiers::GCNone) {
5634 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5635 return Qualifiers::Strong;
5636 else if (Ty->isPointerType())
5637 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5638 } else {
5639 // It's not valid to set GC attributes on anything that isn't a
5640 // pointer.
5641#ifndef NDEBUG
5642 QualType CT = Ty->getCanonicalTypeInternal();
5643 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5644 CT = AT->getElementType();
5645 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5646#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00005647 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00005648 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00005649}
5650
Chris Lattner49af6a42008-04-07 06:51:04 +00005651//===----------------------------------------------------------------------===//
5652// Type Compatibility Testing
5653//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00005654
Mike Stump11289f42009-09-09 15:08:12 +00005655/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005656/// compatible.
5657static bool areCompatVectorTypes(const VectorType *LHS,
5658 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00005659 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00005660 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00005661 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00005662}
5663
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005664bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5665 QualType SecondVec) {
5666 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5667 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5668
5669 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5670 return true;
5671
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005672 // Treat Neon vector types and most AltiVec vector types as if they are the
5673 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005674 const VectorType *First = FirstVec->getAs<VectorType>();
5675 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005676 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005677 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005678 First->getVectorKind() != VectorType::AltiVecPixel &&
5679 First->getVectorKind() != VectorType::AltiVecBool &&
5680 Second->getVectorKind() != VectorType::AltiVecPixel &&
5681 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005682 return true;
5683
5684 return false;
5685}
5686
Steve Naroff8e6aee52009-07-23 01:01:38 +00005687//===----------------------------------------------------------------------===//
5688// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5689//===----------------------------------------------------------------------===//
5690
5691/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5692/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00005693bool
5694ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5695 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00005696 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005697 return true;
5698 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5699 E = rProto->protocol_end(); PI != E; ++PI)
5700 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5701 return true;
5702 return false;
5703}
5704
Steve Naroff8e6aee52009-07-23 01:01:38 +00005705/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5706/// return true if lhs's protocols conform to rhs's protocol; false
5707/// otherwise.
5708bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5709 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5710 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5711 return false;
5712}
5713
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005714/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5715/// Class<p1, ...>.
5716bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5717 QualType rhs) {
5718 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5719 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5720 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5721
5722 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5723 E = lhsQID->qual_end(); I != E; ++I) {
5724 bool match = false;
5725 ObjCProtocolDecl *lhsProto = *I;
5726 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5727 E = rhsOPT->qual_end(); J != E; ++J) {
5728 ObjCProtocolDecl *rhsProto = *J;
5729 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5730 match = true;
5731 break;
5732 }
5733 }
5734 if (!match)
5735 return false;
5736 }
5737 return true;
5738}
5739
Steve Naroff8e6aee52009-07-23 01:01:38 +00005740/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5741/// ObjCQualifiedIDType.
5742bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5743 bool compare) {
5744 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00005745 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005746 lhs->isObjCIdType() || lhs->isObjCClassType())
5747 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005748 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005749 rhs->isObjCIdType() || rhs->isObjCClassType())
5750 return true;
5751
5752 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00005753 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005754
Steve Naroff8e6aee52009-07-23 01:01:38 +00005755 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00005756
Steve Naroff8e6aee52009-07-23 01:01:38 +00005757 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005758 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005759 // make sure we check the class hierarchy.
5760 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5761 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5762 E = lhsQID->qual_end(); I != E; ++I) {
5763 // when comparing an id<P> on lhs with a static type on rhs,
5764 // see if static class implements all of id's protocols, directly or
5765 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005766 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005767 return false;
5768 }
5769 }
5770 // If there are no qualifiers and no interface, we have an 'id'.
5771 return true;
5772 }
Mike Stump11289f42009-09-09 15:08:12 +00005773 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005774 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5775 E = lhsQID->qual_end(); I != E; ++I) {
5776 ObjCProtocolDecl *lhsProto = *I;
5777 bool match = false;
5778
5779 // when comparing an id<P> on lhs with a static type on rhs,
5780 // see if static class implements all of id's protocols, directly or
5781 // through its super class and categories.
5782 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5783 E = rhsOPT->qual_end(); J != E; ++J) {
5784 ObjCProtocolDecl *rhsProto = *J;
5785 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5786 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5787 match = true;
5788 break;
5789 }
5790 }
Mike Stump11289f42009-09-09 15:08:12 +00005791 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005792 // make sure we check the class hierarchy.
5793 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5794 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5795 E = lhsQID->qual_end(); I != E; ++I) {
5796 // when comparing an id<P> on lhs with a static type on rhs,
5797 // see if static class implements all of id's protocols, directly or
5798 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005799 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005800 match = true;
5801 break;
5802 }
5803 }
5804 }
5805 if (!match)
5806 return false;
5807 }
Mike Stump11289f42009-09-09 15:08:12 +00005808
Steve Naroff8e6aee52009-07-23 01:01:38 +00005809 return true;
5810 }
Mike Stump11289f42009-09-09 15:08:12 +00005811
Steve Naroff8e6aee52009-07-23 01:01:38 +00005812 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5813 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5814
Mike Stump11289f42009-09-09 15:08:12 +00005815 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00005816 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005817 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005818 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5819 E = lhsOPT->qual_end(); I != E; ++I) {
5820 ObjCProtocolDecl *lhsProto = *I;
5821 bool match = false;
5822
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005823 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00005824 // see if static class implements all of id's protocols, directly or
5825 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005826 // First, lhs protocols in the qualifier list must be found, direct
5827 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005828 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5829 E = rhsQID->qual_end(); J != E; ++J) {
5830 ObjCProtocolDecl *rhsProto = *J;
5831 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5832 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5833 match = true;
5834 break;
5835 }
5836 }
5837 if (!match)
5838 return false;
5839 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005840
5841 // Static class's protocols, or its super class or category protocols
5842 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5843 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5844 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5845 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5846 // This is rather dubious but matches gcc's behavior. If lhs has
5847 // no type qualifier and its class has no static protocol(s)
5848 // assume that it is mismatch.
5849 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5850 return false;
5851 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5852 LHSInheritedProtocols.begin(),
5853 E = LHSInheritedProtocols.end(); I != E; ++I) {
5854 bool match = false;
5855 ObjCProtocolDecl *lhsProto = (*I);
5856 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5857 E = rhsQID->qual_end(); J != E; ++J) {
5858 ObjCProtocolDecl *rhsProto = *J;
5859 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5860 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5861 match = true;
5862 break;
5863 }
5864 }
5865 if (!match)
5866 return false;
5867 }
5868 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00005869 return true;
5870 }
5871 return false;
5872}
5873
Eli Friedman47f77112008-08-22 00:56:42 +00005874/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005875/// compatible for assignment from RHS to LHS. This handles validation of any
5876/// protocol qualifiers on the LHS or RHS.
5877///
Steve Naroff7cae42b2009-07-10 23:34:53 +00005878bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5879 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00005880 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5881 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5882
Steve Naroff1329fa02009-07-15 18:40:39 +00005883 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00005884 if (LHS->isObjCUnqualifiedIdOrClass() ||
5885 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00005886 return true;
5887
John McCall8b07ec22010-05-15 11:32:37 +00005888 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00005889 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5890 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00005891 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005892
5893 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5894 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5895 QualType(RHSOPT,0));
5896
John McCall8b07ec22010-05-15 11:32:37 +00005897 // If we have 2 user-defined types, fall into that path.
5898 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00005899 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005900
Steve Naroff8e6aee52009-07-23 01:01:38 +00005901 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005902}
5903
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005904/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00005905/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005906/// arguments in block literals. When passed as arguments, passing 'A*' where
5907/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5908/// not OK. For the return type, the opposite is not OK.
5909bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5910 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005911 const ObjCObjectPointerType *RHSOPT,
5912 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005913 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005914 return true;
5915
5916 if (LHSOPT->isObjCBuiltinType()) {
5917 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5918 }
5919
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005920 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005921 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5922 QualType(RHSOPT,0),
5923 false);
5924
5925 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5926 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5927 if (LHS && RHS) { // We have 2 user-defined types.
5928 if (LHS != RHS) {
5929 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005930 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005931 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005932 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005933 }
5934 else
5935 return true;
5936 }
5937 return false;
5938}
5939
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005940/// getIntersectionOfProtocols - This routine finds the intersection of set
5941/// of protocols inherited from two distinct objective-c pointer objects.
5942/// It is used to build composite qualifier list of the composite type of
5943/// the conditional expression involving two objective-c pointer objects.
5944static
5945void getIntersectionOfProtocols(ASTContext &Context,
5946 const ObjCObjectPointerType *LHSOPT,
5947 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005948 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005949
John McCall8b07ec22010-05-15 11:32:37 +00005950 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5951 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5952 assert(LHS->getInterface() && "LHS must have an interface base");
5953 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005954
5955 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5956 unsigned LHSNumProtocols = LHS->getNumProtocols();
5957 if (LHSNumProtocols > 0)
5958 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5959 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005960 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005961 Context.CollectInheritedProtocols(LHS->getInterface(),
5962 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005963 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5964 LHSInheritedProtocols.end());
5965 }
5966
5967 unsigned RHSNumProtocols = RHS->getNumProtocols();
5968 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00005969 ObjCProtocolDecl **RHSProtocols =
5970 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005971 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5972 if (InheritedProtocolSet.count(RHSProtocols[i]))
5973 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00005974 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005975 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005976 Context.CollectInheritedProtocols(RHS->getInterface(),
5977 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005978 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5979 RHSInheritedProtocols.begin(),
5980 E = RHSInheritedProtocols.end(); I != E; ++I)
5981 if (InheritedProtocolSet.count((*I)))
5982 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005983 }
5984}
5985
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005986/// areCommonBaseCompatible - Returns common base class of the two classes if
5987/// one found. Note that this is O'2 algorithm. But it will be called as the
5988/// last type comparison in a ?-exp of ObjC pointer types before a
5989/// warning is issued. So, its invokation is extremely rare.
5990QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00005991 const ObjCObjectPointerType *Lptr,
5992 const ObjCObjectPointerType *Rptr) {
5993 const ObjCObjectType *LHS = Lptr->getObjectType();
5994 const ObjCObjectType *RHS = Rptr->getObjectType();
5995 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5996 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00005997 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005998 return QualType();
5999
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006000 do {
John McCall8b07ec22010-05-15 11:32:37 +00006001 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006002 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006003 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006004 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6005
6006 QualType Result = QualType(LHS, 0);
6007 if (!Protocols.empty())
6008 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6009 Result = getObjCObjectPointerType(Result);
6010 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006011 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006012 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006013
6014 return QualType();
6015}
6016
John McCall8b07ec22010-05-15 11:32:37 +00006017bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6018 const ObjCObjectType *RHS) {
6019 assert(LHS->getInterface() && "LHS is not an interface type");
6020 assert(RHS->getInterface() && "RHS is not an interface type");
6021
Chris Lattner49af6a42008-04-07 06:51:04 +00006022 // Verify that the base decls are compatible: the RHS must be a subclass of
6023 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006024 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006025 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006026
Chris Lattner49af6a42008-04-07 06:51:04 +00006027 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6028 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006029 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006030 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006031
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006032 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6033 // more detailed analysis is required.
6034 if (RHS->getNumProtocols() == 0) {
6035 // OK, if LHS is a superclass of RHS *and*
6036 // this superclass is assignment compatible with LHS.
6037 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006038 bool IsSuperClass =
6039 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6040 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006041 // OK if conversion of LHS to SuperClass results in narrowing of types
6042 // ; i.e., SuperClass may implement at least one of the protocols
6043 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6044 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6045 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006046 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006047 // If super class has no protocols, it is not a match.
6048 if (SuperClassInheritedProtocols.empty())
6049 return false;
6050
6051 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6052 LHSPE = LHS->qual_end();
6053 LHSPI != LHSPE; LHSPI++) {
6054 bool SuperImplementsProtocol = false;
6055 ObjCProtocolDecl *LHSProto = (*LHSPI);
6056
6057 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6058 SuperClassInheritedProtocols.begin(),
6059 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6060 ObjCProtocolDecl *SuperClassProto = (*I);
6061 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6062 SuperImplementsProtocol = true;
6063 break;
6064 }
6065 }
6066 if (!SuperImplementsProtocol)
6067 return false;
6068 }
6069 return true;
6070 }
6071 return false;
6072 }
Mike Stump11289f42009-09-09 15:08:12 +00006073
John McCall8b07ec22010-05-15 11:32:37 +00006074 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6075 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00006076 LHSPI != LHSPE; LHSPI++) {
6077 bool RHSImplementsProtocol = false;
6078
6079 // If the RHS doesn't implement the protocol on the left, the types
6080 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00006081 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6082 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00006083 RHSPI != RHSPE; RHSPI++) {
6084 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006085 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00006086 break;
6087 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006088 }
6089 // FIXME: For better diagnostics, consider passing back the protocol name.
6090 if (!RHSImplementsProtocol)
6091 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006092 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006093 // The RHS implements all protocols listed on the LHS.
6094 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006095}
6096
Steve Naroffb7605152009-02-12 17:52:19 +00006097bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6098 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006099 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6100 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006101
Steve Naroff7cae42b2009-07-10 23:34:53 +00006102 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006103 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006104
6105 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6106 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006107}
6108
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006109bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6110 return canAssignObjCInterfaces(
6111 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6112 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6113}
6114
Mike Stump11289f42009-09-09 15:08:12 +00006115/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006116/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006117/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006118/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006119bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6120 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006121 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006122 return hasSameType(LHS, RHS);
6123
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006124 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006125}
6126
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006127bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006128 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006129}
6130
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006131bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6132 return !mergeTypes(LHS, RHS, true).isNull();
6133}
6134
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006135/// mergeTransparentUnionType - if T is a transparent union type and a member
6136/// of T is compatible with SubType, return the merged type, else return
6137/// QualType()
6138QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6139 bool OfBlockPointer,
6140 bool Unqualified) {
6141 if (const RecordType *UT = T->getAsUnionType()) {
6142 RecordDecl *UD = UT->getDecl();
6143 if (UD->hasAttr<TransparentUnionAttr>()) {
6144 for (RecordDecl::field_iterator it = UD->field_begin(),
6145 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00006146 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006147 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6148 if (!MT.isNull())
6149 return MT;
6150 }
6151 }
6152 }
6153
6154 return QualType();
6155}
6156
6157/// mergeFunctionArgumentTypes - merge two types which appear as function
6158/// argument types
6159QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6160 bool OfBlockPointer,
6161 bool Unqualified) {
6162 // GNU extension: two types are compatible if they appear as a function
6163 // argument, one of the types is a transparent union type and the other
6164 // type is compatible with a union member
6165 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6166 Unqualified);
6167 if (!lmerge.isNull())
6168 return lmerge;
6169
6170 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6171 Unqualified);
6172 if (!rmerge.isNull())
6173 return rmerge;
6174
6175 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6176}
6177
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006178QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006179 bool OfBlockPointer,
6180 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006181 const FunctionType *lbase = lhs->getAs<FunctionType>();
6182 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006183 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6184 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006185 bool allLTypes = true;
6186 bool allRTypes = true;
6187
6188 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006189 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006190 if (OfBlockPointer) {
6191 QualType RHS = rbase->getResultType();
6192 QualType LHS = lbase->getResultType();
6193 bool UnqualifiedResult = Unqualified;
6194 if (!UnqualifiedResult)
6195 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006196 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006197 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006198 else
John McCall8c6b56f2010-12-15 01:06:38 +00006199 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6200 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006201 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006202
6203 if (Unqualified)
6204 retType = retType.getUnqualifiedType();
6205
6206 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6207 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6208 if (Unqualified) {
6209 LRetType = LRetType.getUnqualifiedType();
6210 RRetType = RRetType.getUnqualifiedType();
6211 }
6212
6213 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006214 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006215 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006216 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006217
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006218 // FIXME: double check this
6219 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6220 // rbase->getRegParmAttr() != 0 &&
6221 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006222 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6223 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006224
Douglas Gregor8c940862010-01-18 17:14:39 +00006225 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00006226 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00006227 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006228
John McCall8c6b56f2010-12-15 01:06:38 +00006229 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006230 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6231 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006232 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6233 return QualType();
6234
John McCall31168b02011-06-15 23:02:42 +00006235 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6236 return QualType();
6237
Fariborz Jahanian48c69102011-10-05 00:05:34 +00006238 // functypes which return are preferred over those that do not.
6239 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
6240 allLTypes = false;
6241 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
6242 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006243 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6244 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006245
John McCall31168b02011-06-15 23:02:42 +00006246 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006247
Eli Friedman47f77112008-08-22 00:56:42 +00006248 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006249 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6250 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006251 unsigned lproto_nargs = lproto->getNumArgs();
6252 unsigned rproto_nargs = rproto->getNumArgs();
6253
6254 // Compatible functions must have the same number of arguments
6255 if (lproto_nargs != rproto_nargs)
6256 return QualType();
6257
6258 // Variadic and non-variadic functions aren't compatible
6259 if (lproto->isVariadic() != rproto->isVariadic())
6260 return QualType();
6261
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006262 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6263 return QualType();
6264
Fariborz Jahanian97676972011-09-28 21:52:05 +00006265 if (LangOpts.ObjCAutoRefCount &&
6266 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6267 return QualType();
6268
Eli Friedman47f77112008-08-22 00:56:42 +00006269 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006270 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00006271 for (unsigned i = 0; i < lproto_nargs; i++) {
6272 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6273 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006274 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6275 OfBlockPointer,
6276 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006277 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006278
6279 if (Unqualified)
6280 argtype = argtype.getUnqualifiedType();
6281
Eli Friedman47f77112008-08-22 00:56:42 +00006282 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006283 if (Unqualified) {
6284 largtype = largtype.getUnqualifiedType();
6285 rargtype = rargtype.getUnqualifiedType();
6286 }
6287
Chris Lattner465fa322008-10-05 17:34:18 +00006288 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6289 allLTypes = false;
6290 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6291 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006292 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006293
Eli Friedman47f77112008-08-22 00:56:42 +00006294 if (allLTypes) return lhs;
6295 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006296
6297 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6298 EPI.ExtInfo = einfo;
6299 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006300 }
6301
6302 if (lproto) allRTypes = false;
6303 if (rproto) allLTypes = false;
6304
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006305 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006306 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006307 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006308 if (proto->isVariadic()) return QualType();
6309 // Check that the types are compatible with the types that
6310 // would result from default argument promotions (C99 6.7.5.3p15).
6311 // The only types actually affected are promotable integer
6312 // types and floats, which would be passed as a different
6313 // type depending on whether the prototype is visible.
6314 unsigned proto_nargs = proto->getNumArgs();
6315 for (unsigned i = 0; i < proto_nargs; ++i) {
6316 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00006317
6318 // Look at the promotion type of enum types, since that is the type used
6319 // to pass enum values.
6320 if (const EnumType *Enum = argTy->getAs<EnumType>())
6321 argTy = Enum->getDecl()->getPromotionType();
6322
Eli Friedman47f77112008-08-22 00:56:42 +00006323 if (argTy->isPromotableIntegerType() ||
6324 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6325 return QualType();
6326 }
6327
6328 if (allLTypes) return lhs;
6329 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006330
6331 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6332 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00006333 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006334 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006335 }
6336
6337 if (allLTypes) return lhs;
6338 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00006339 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00006340}
6341
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006342QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006343 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006344 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00006345 // C++ [expr]: If an expression initially has the type "reference to T", the
6346 // type is adjusted to "T" prior to any further analysis, the expression
6347 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006348 // expression is an lvalue unless the reference is an rvalue reference and
6349 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00006350 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6351 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006352
6353 if (Unqualified) {
6354 LHS = LHS.getUnqualifiedType();
6355 RHS = RHS.getUnqualifiedType();
6356 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00006357
Eli Friedman47f77112008-08-22 00:56:42 +00006358 QualType LHSCan = getCanonicalType(LHS),
6359 RHSCan = getCanonicalType(RHS);
6360
6361 // If two types are identical, they are compatible.
6362 if (LHSCan == RHSCan)
6363 return LHS;
6364
John McCall8ccfcb52009-09-24 19:53:00 +00006365 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006366 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6367 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00006368 if (LQuals != RQuals) {
6369 // If any of these qualifiers are different, we have a type
6370 // mismatch.
6371 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00006372 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6373 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00006374 return QualType();
6375
6376 // Exactly one GC qualifier difference is allowed: __strong is
6377 // okay if the other type has no GC qualifier but is an Objective
6378 // C object pointer (i.e. implicitly strong by default). We fix
6379 // this by pretending that the unqualified type was actually
6380 // qualified __strong.
6381 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6382 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6383 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6384
6385 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6386 return QualType();
6387
6388 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6389 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6390 }
6391 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6392 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6393 }
Eli Friedman47f77112008-08-22 00:56:42 +00006394 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00006395 }
6396
6397 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00006398
Eli Friedmandcca6332009-06-01 01:22:52 +00006399 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6400 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00006401
Chris Lattnerfd652912008-01-14 05:45:46 +00006402 // We want to consider the two function types to be the same for these
6403 // comparisons, just force one to the other.
6404 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6405 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00006406
6407 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00006408 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6409 LHSClass = Type::ConstantArray;
6410 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6411 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00006412
John McCall8b07ec22010-05-15 11:32:37 +00006413 // ObjCInterfaces are just specialized ObjCObjects.
6414 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6415 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6416
Nate Begemance4d7fc2008-04-18 23:10:10 +00006417 // Canonicalize ExtVector -> Vector.
6418 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6419 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00006420
Chris Lattner95554662008-04-07 05:43:21 +00006421 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006422 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00006423 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00006424 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00006425 // Compatibility is based on the underlying type, not the promotion
6426 // type.
John McCall9dd450b2009-09-21 23:43:11 +00006427 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006428 QualType TINT = ETy->getDecl()->getIntegerType();
6429 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006430 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006431 }
John McCall9dd450b2009-09-21 23:43:11 +00006432 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006433 QualType TINT = ETy->getDecl()->getIntegerType();
6434 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006435 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006436 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006437 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00006438 if (OfBlockPointer && !BlockReturnType) {
6439 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6440 return LHS;
6441 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6442 return RHS;
6443 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006444
Eli Friedman47f77112008-08-22 00:56:42 +00006445 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00006446 }
Eli Friedman47f77112008-08-22 00:56:42 +00006447
Steve Naroffc6edcbd2008-01-09 22:43:08 +00006448 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006449 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006450#define TYPE(Class, Base)
6451#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00006452#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006453#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6454#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6455#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00006456 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006457
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006458 case Type::LValueReference:
6459 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006460 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00006461 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006462
John McCall8b07ec22010-05-15 11:32:37 +00006463 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006464 case Type::IncompleteArray:
6465 case Type::VariableArray:
6466 case Type::FunctionProto:
6467 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00006468 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006469
Chris Lattnerfd652912008-01-14 05:45:46 +00006470 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00006471 {
6472 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006473 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6474 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006475 if (Unqualified) {
6476 LHSPointee = LHSPointee.getUnqualifiedType();
6477 RHSPointee = RHSPointee.getUnqualifiedType();
6478 }
6479 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6480 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006481 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00006482 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006483 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00006484 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006485 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006486 return getPointerType(ResultType);
6487 }
Steve Naroff68e167d2008-12-10 17:49:55 +00006488 case Type::BlockPointer:
6489 {
6490 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006491 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6492 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006493 if (Unqualified) {
6494 LHSPointee = LHSPointee.getUnqualifiedType();
6495 RHSPointee = RHSPointee.getUnqualifiedType();
6496 }
6497 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6498 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00006499 if (ResultType.isNull()) return QualType();
6500 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6501 return LHS;
6502 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6503 return RHS;
6504 return getBlockPointerType(ResultType);
6505 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00006506 case Type::Atomic:
6507 {
6508 // Merge two pointer types, while trying to preserve typedef info
6509 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6510 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6511 if (Unqualified) {
6512 LHSValue = LHSValue.getUnqualifiedType();
6513 RHSValue = RHSValue.getUnqualifiedType();
6514 }
6515 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6516 Unqualified);
6517 if (ResultType.isNull()) return QualType();
6518 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6519 return LHS;
6520 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6521 return RHS;
6522 return getAtomicType(ResultType);
6523 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006524 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00006525 {
6526 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6527 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6528 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6529 return QualType();
6530
6531 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6532 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006533 if (Unqualified) {
6534 LHSElem = LHSElem.getUnqualifiedType();
6535 RHSElem = RHSElem.getUnqualifiedType();
6536 }
6537
6538 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006539 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00006540 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6541 return LHS;
6542 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6543 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00006544 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6545 ArrayType::ArraySizeModifier(), 0);
6546 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6547 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006548 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6549 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00006550 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6551 return LHS;
6552 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6553 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006554 if (LVAT) {
6555 // FIXME: This isn't correct! But tricky to implement because
6556 // the array's size has to be the size of LHS, but the type
6557 // has to be different.
6558 return LHS;
6559 }
6560 if (RVAT) {
6561 // FIXME: This isn't correct! But tricky to implement because
6562 // the array's size has to be the size of RHS, but the type
6563 // has to be different.
6564 return RHS;
6565 }
Eli Friedman3e62c212008-08-22 01:48:21 +00006566 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6567 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00006568 return getIncompleteArrayType(ResultType,
6569 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006570 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006571 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006572 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006573 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006574 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00006575 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00006576 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006577 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00006578 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00006579 case Type::Complex:
6580 // Distinct complex types are incompatible.
6581 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006582 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00006583 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00006584 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6585 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00006586 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00006587 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00006588 case Type::ObjCObject: {
6589 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00006590 // FIXME: This should be type compatibility, e.g. whether
6591 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00006592 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6593 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6594 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00006595 return LHS;
6596
Eli Friedman47f77112008-08-22 00:56:42 +00006597 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00006598 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006599 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006600 if (OfBlockPointer) {
6601 if (canAssignObjCInterfacesInBlockPointer(
6602 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006603 RHS->getAs<ObjCObjectPointerType>(),
6604 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00006605 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006606 return QualType();
6607 }
John McCall9dd450b2009-09-21 23:43:11 +00006608 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6609 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006610 return LHS;
6611
Steve Naroffc68cfcf2008-12-10 22:14:21 +00006612 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00006613 }
Steve Naroff32e44c02007-10-15 20:41:53 +00006614 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006615
David Blaikie8a40f702012-01-17 06:56:22 +00006616 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00006617}
Ted Kremenekfc581a92007-10-31 17:10:13 +00006618
Fariborz Jahanian97676972011-09-28 21:52:05 +00006619bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6620 const FunctionProtoType *FromFunctionType,
6621 const FunctionProtoType *ToFunctionType) {
6622 if (FromFunctionType->hasAnyConsumedArgs() !=
6623 ToFunctionType->hasAnyConsumedArgs())
6624 return false;
6625 FunctionProtoType::ExtProtoInfo FromEPI =
6626 FromFunctionType->getExtProtoInfo();
6627 FunctionProtoType::ExtProtoInfo ToEPI =
6628 ToFunctionType->getExtProtoInfo();
6629 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6630 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6631 ArgIdx != NumArgs; ++ArgIdx) {
6632 if (FromEPI.ConsumedArguments[ArgIdx] !=
6633 ToEPI.ConsumedArguments[ArgIdx])
6634 return false;
6635 }
6636 return true;
6637}
6638
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006639/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6640/// 'RHS' attributes and returns the merged version; including for function
6641/// return types.
6642QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6643 QualType LHSCan = getCanonicalType(LHS),
6644 RHSCan = getCanonicalType(RHS);
6645 // If two types are identical, they are compatible.
6646 if (LHSCan == RHSCan)
6647 return LHS;
6648 if (RHSCan->isFunctionType()) {
6649 if (!LHSCan->isFunctionType())
6650 return QualType();
6651 QualType OldReturnType =
6652 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6653 QualType NewReturnType =
6654 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6655 QualType ResReturnType =
6656 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6657 if (ResReturnType.isNull())
6658 return QualType();
6659 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6660 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6661 // In either case, use OldReturnType to build the new function type.
6662 const FunctionType *F = LHS->getAs<FunctionType>();
6663 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00006664 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6665 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006666 QualType ResultType
6667 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006668 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006669 return ResultType;
6670 }
6671 }
6672 return QualType();
6673 }
6674
6675 // If the qualifiers are different, the types can still be merged.
6676 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6677 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6678 if (LQuals != RQuals) {
6679 // If any of these qualifiers are different, we have a type mismatch.
6680 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6681 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6682 return QualType();
6683
6684 // Exactly one GC qualifier difference is allowed: __strong is
6685 // okay if the other type has no GC qualifier but is an Objective
6686 // C object pointer (i.e. implicitly strong by default). We fix
6687 // this by pretending that the unqualified type was actually
6688 // qualified __strong.
6689 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6690 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6691 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6692
6693 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6694 return QualType();
6695
6696 if (GC_L == Qualifiers::Strong)
6697 return LHS;
6698 if (GC_R == Qualifiers::Strong)
6699 return RHS;
6700 return QualType();
6701 }
6702
6703 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6704 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6705 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6706 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6707 if (ResQT == LHSBaseQT)
6708 return LHS;
6709 if (ResQT == RHSBaseQT)
6710 return RHS;
6711 }
6712 return QualType();
6713}
6714
Chris Lattner4ba0cef2008-04-07 07:01:58 +00006715//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006716// Integer Predicates
6717//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00006718
Jay Foad39c79802011-01-12 09:06:06 +00006719unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00006720 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00006721 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00006722 if (T->isBooleanType())
6723 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00006724 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006725 return (unsigned)getTypeSize(T);
6726}
6727
6728QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006729 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00006730
6731 // Turn <4 x signed int> -> <4 x unsigned int>
6732 if (const VectorType *VTy = T->getAs<VectorType>())
6733 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00006734 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00006735
6736 // For enums, we return the unsigned version of the base type.
6737 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006738 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00006739
6740 const BuiltinType *BTy = T->getAs<BuiltinType>();
6741 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006742 switch (BTy->getKind()) {
6743 case BuiltinType::Char_S:
6744 case BuiltinType::SChar:
6745 return UnsignedCharTy;
6746 case BuiltinType::Short:
6747 return UnsignedShortTy;
6748 case BuiltinType::Int:
6749 return UnsignedIntTy;
6750 case BuiltinType::Long:
6751 return UnsignedLongTy;
6752 case BuiltinType::LongLong:
6753 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00006754 case BuiltinType::Int128:
6755 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006756 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006757 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006758 }
6759}
6760
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00006761ASTMutationListener::~ASTMutationListener() { }
6762
Chris Lattnerecd79c62009-06-14 00:45:47 +00006763
6764//===----------------------------------------------------------------------===//
6765// Builtin Type Computation
6766//===----------------------------------------------------------------------===//
6767
6768/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00006769/// pointer over the consumed characters. This returns the resultant type. If
6770/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6771/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6772/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006773///
6774/// RequiresICE is filled in on return to indicate whether the value is required
6775/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00006776static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00006777 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006778 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00006779 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00006780 // Modifiers.
6781 int HowLong = 0;
6782 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006783 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00006784
Chris Lattnerdc226c22010-10-01 22:42:38 +00006785 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00006786 bool Done = false;
6787 while (!Done) {
6788 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00006789 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00006790 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006791 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00006792 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006793 case 'S':
6794 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6795 assert(!Signed && "Can't use 'S' modifier multiple times!");
6796 Signed = true;
6797 break;
6798 case 'U':
6799 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6800 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6801 Unsigned = true;
6802 break;
6803 case 'L':
6804 assert(HowLong <= 2 && "Can't have LLLL modifier");
6805 ++HowLong;
6806 break;
6807 }
6808 }
6809
6810 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00006811
Chris Lattnerecd79c62009-06-14 00:45:47 +00006812 // Read the base type.
6813 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00006814 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006815 case 'v':
6816 assert(HowLong == 0 && !Signed && !Unsigned &&
6817 "Bad modifiers used with 'v'!");
6818 Type = Context.VoidTy;
6819 break;
6820 case 'f':
6821 assert(HowLong == 0 && !Signed && !Unsigned &&
6822 "Bad modifiers used with 'f'!");
6823 Type = Context.FloatTy;
6824 break;
6825 case 'd':
6826 assert(HowLong < 2 && !Signed && !Unsigned &&
6827 "Bad modifiers used with 'd'!");
6828 if (HowLong)
6829 Type = Context.LongDoubleTy;
6830 else
6831 Type = Context.DoubleTy;
6832 break;
6833 case 's':
6834 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6835 if (Unsigned)
6836 Type = Context.UnsignedShortTy;
6837 else
6838 Type = Context.ShortTy;
6839 break;
6840 case 'i':
6841 if (HowLong == 3)
6842 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6843 else if (HowLong == 2)
6844 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6845 else if (HowLong == 1)
6846 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6847 else
6848 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6849 break;
6850 case 'c':
6851 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6852 if (Signed)
6853 Type = Context.SignedCharTy;
6854 else if (Unsigned)
6855 Type = Context.UnsignedCharTy;
6856 else
6857 Type = Context.CharTy;
6858 break;
6859 case 'b': // boolean
6860 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6861 Type = Context.BoolTy;
6862 break;
6863 case 'z': // size_t.
6864 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6865 Type = Context.getSizeType();
6866 break;
6867 case 'F':
6868 Type = Context.getCFConstantStringType();
6869 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00006870 case 'G':
6871 Type = Context.getObjCIdType();
6872 break;
6873 case 'H':
6874 Type = Context.getObjCSelType();
6875 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006876 case 'a':
6877 Type = Context.getBuiltinVaListType();
6878 assert(!Type.isNull() && "builtin va list type not initialized!");
6879 break;
6880 case 'A':
6881 // This is a "reference" to a va_list; however, what exactly
6882 // this means depends on how va_list is defined. There are two
6883 // different kinds of va_list: ones passed by value, and ones
6884 // passed by reference. An example of a by-value va_list is
6885 // x86, where va_list is a char*. An example of by-ref va_list
6886 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6887 // we want this argument to be a char*&; for x86-64, we want
6888 // it to be a __va_list_tag*.
6889 Type = Context.getBuiltinVaListType();
6890 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006891 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00006892 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006893 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00006894 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006895 break;
6896 case 'V': {
6897 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006898 unsigned NumElements = strtoul(Str, &End, 10);
6899 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006900 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00006901
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006902 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6903 RequiresICE, false);
6904 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00006905
6906 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00006907 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00006908 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006909 break;
6910 }
Douglas Gregorfed66992012-06-07 18:08:25 +00006911 case 'E': {
6912 char *End;
6913
6914 unsigned NumElements = strtoul(Str, &End, 10);
6915 assert(End != Str && "Missing vector size");
6916
6917 Str = End;
6918
6919 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6920 false);
6921 Type = Context.getExtVectorType(ElementType, NumElements);
6922 break;
6923 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006924 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006925 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6926 false);
6927 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006928 Type = Context.getComplexType(ElementType);
6929 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00006930 }
6931 case 'Y' : {
6932 Type = Context.getPointerDiffType();
6933 break;
6934 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00006935 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00006936 Type = Context.getFILEType();
6937 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006938 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006939 return QualType();
6940 }
Mike Stump2adb4da2009-07-28 23:47:15 +00006941 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00006942 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00006943 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00006944 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00006945 else
6946 Type = Context.getjmp_bufType();
6947
Mike Stump2adb4da2009-07-28 23:47:15 +00006948 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006949 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00006950 return QualType();
6951 }
6952 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00006953 case 'K':
6954 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
6955 Type = Context.getucontext_tType();
6956
6957 if (Type.isNull()) {
6958 Error = ASTContext::GE_Missing_ucontext;
6959 return QualType();
6960 }
6961 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00006962 }
Mike Stump11289f42009-09-09 15:08:12 +00006963
Chris Lattnerdc226c22010-10-01 22:42:38 +00006964 // If there are modifiers and if we're allowed to parse them, go for it.
6965 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006966 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00006967 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006968 default: Done = true; --Str; break;
6969 case '*':
6970 case '&': {
6971 // Both pointers and references can have their pointee types
6972 // qualified with an address space.
6973 char *End;
6974 unsigned AddrSpace = strtoul(Str, &End, 10);
6975 if (End != Str && AddrSpace != 0) {
6976 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6977 Str = End;
6978 }
6979 if (c == '*')
6980 Type = Context.getPointerType(Type);
6981 else
6982 Type = Context.getLValueReferenceType(Type);
6983 break;
6984 }
6985 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6986 case 'C':
6987 Type = Type.withConst();
6988 break;
6989 case 'D':
6990 Type = Context.getVolatileType(Type);
6991 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00006992 case 'R':
6993 Type = Type.withRestrict();
6994 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006995 }
6996 }
Chris Lattner84733392010-10-01 07:13:18 +00006997
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006998 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00006999 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007000
Chris Lattnerecd79c62009-06-14 00:45:47 +00007001 return Type;
7002}
7003
7004/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007005QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007006 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007007 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007008 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007009
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007010 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007011
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007012 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007013 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007014 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7015 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007016 if (Error != GE_None)
7017 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007018
7019 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7020
Chris Lattnerecd79c62009-06-14 00:45:47 +00007021 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007022 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007023 if (Error != GE_None)
7024 return QualType();
7025
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007026 // If this argument is required to be an IntegerConstantExpression and the
7027 // caller cares, fill in the bitmask we return.
7028 if (RequiresICE && IntegerConstantArgs)
7029 *IntegerConstantArgs |= 1 << ArgTypes.size();
7030
Chris Lattnerecd79c62009-06-14 00:45:47 +00007031 // Do array -> pointer decay. The builtin should use the decayed type.
7032 if (Ty->isArrayType())
7033 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007034
Chris Lattnerecd79c62009-06-14 00:45:47 +00007035 ArgTypes.push_back(Ty);
7036 }
7037
7038 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7039 "'.' should only occur at end of builtin type list!");
7040
John McCall991eb4b2010-12-21 00:44:39 +00007041 FunctionType::ExtInfo EI;
7042 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7043
7044 bool Variadic = (TypeStr[0] == '.');
7045
7046 // We really shouldn't be making a no-proto type here, especially in C++.
7047 if (ArgTypes.empty() && Variadic)
7048 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007049
John McCalldb40c7f2010-12-14 08:05:40 +00007050 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007051 EPI.ExtInfo = EI;
7052 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007053
7054 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007055}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007056
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007057GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
7058 GVALinkage External = GVA_StrongExternal;
7059
7060 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007061 switch (L) {
7062 case NoLinkage:
7063 case InternalLinkage:
7064 case UniqueExternalLinkage:
7065 return GVA_Internal;
7066
7067 case ExternalLinkage:
7068 switch (FD->getTemplateSpecializationKind()) {
7069 case TSK_Undeclared:
7070 case TSK_ExplicitSpecialization:
7071 External = GVA_StrongExternal;
7072 break;
7073
7074 case TSK_ExplicitInstantiationDefinition:
7075 return GVA_ExplicitTemplateInstantiation;
7076
7077 case TSK_ExplicitInstantiationDeclaration:
7078 case TSK_ImplicitInstantiation:
7079 External = GVA_TemplateInstantiation;
7080 break;
7081 }
7082 }
7083
7084 if (!FD->isInlined())
7085 return External;
7086
David Blaikiebbafb8a2012-03-11 07:00:24 +00007087 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007088 // GNU or C99 inline semantics. Determine whether this symbol should be
7089 // externally visible.
7090 if (FD->isInlineDefinitionExternallyVisible())
7091 return External;
7092
7093 // C99 inline semantics, where the symbol is not externally visible.
7094 return GVA_C99Inline;
7095 }
7096
7097 // C++0x [temp.explicit]p9:
7098 // [ Note: The intent is that an inline function that is the subject of
7099 // an explicit instantiation declaration will still be implicitly
7100 // instantiated when used so that the body can be considered for
7101 // inlining, but that no out-of-line copy of the inline function would be
7102 // generated in the translation unit. -- end note ]
7103 if (FD->getTemplateSpecializationKind()
7104 == TSK_ExplicitInstantiationDeclaration)
7105 return GVA_C99Inline;
7106
7107 return GVA_CXXInline;
7108}
7109
7110GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7111 // If this is a static data member, compute the kind of template
7112 // specialization. Otherwise, this variable is not part of a
7113 // template.
7114 TemplateSpecializationKind TSK = TSK_Undeclared;
7115 if (VD->isStaticDataMember())
7116 TSK = VD->getTemplateSpecializationKind();
7117
7118 Linkage L = VD->getLinkage();
David Blaikiebbafb8a2012-03-11 07:00:24 +00007119 if (L == ExternalLinkage && getLangOpts().CPlusPlus &&
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007120 VD->getType()->getLinkage() == UniqueExternalLinkage)
7121 L = UniqueExternalLinkage;
7122
7123 switch (L) {
7124 case NoLinkage:
7125 case InternalLinkage:
7126 case UniqueExternalLinkage:
7127 return GVA_Internal;
7128
7129 case ExternalLinkage:
7130 switch (TSK) {
7131 case TSK_Undeclared:
7132 case TSK_ExplicitSpecialization:
7133 return GVA_StrongExternal;
7134
7135 case TSK_ExplicitInstantiationDeclaration:
7136 llvm_unreachable("Variable should not be instantiated");
7137 // Fall through to treat this like any other instantiation.
7138
7139 case TSK_ExplicitInstantiationDefinition:
7140 return GVA_ExplicitTemplateInstantiation;
7141
7142 case TSK_ImplicitInstantiation:
7143 return GVA_TemplateInstantiation;
7144 }
7145 }
7146
David Blaikie8a40f702012-01-17 06:56:22 +00007147 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007148}
7149
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007150bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007151 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7152 if (!VD->isFileVarDecl())
7153 return false;
Argyrios Kyrtzidisa98e8612011-09-13 21:35:00 +00007154 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007155 return false;
7156
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007157 // Weak references don't produce any output by themselves.
7158 if (D->hasAttr<WeakRefAttr>())
7159 return false;
7160
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007161 // Aliases and used decls are required.
7162 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7163 return true;
7164
7165 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7166 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007167 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007168 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007169
7170 // Constructors and destructors are required.
7171 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7172 return true;
7173
7174 // The key function for a class is required.
7175 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7176 const CXXRecordDecl *RD = MD->getParent();
7177 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7178 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
7179 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7180 return true;
7181 }
7182 }
7183
7184 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7185
7186 // static, static inline, always_inline, and extern inline functions can
7187 // always be deferred. Normal inline functions can be deferred in C99/C++.
7188 // Implicit template instantiations can also be deferred in C++.
7189 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007190 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007191 return false;
7192 return true;
7193 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007194
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007195 const VarDecl *VD = cast<VarDecl>(D);
7196 assert(VD->isFileVarDecl() && "Expected file scoped var");
7197
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007198 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7199 return false;
7200
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007201 // Structs that have non-trivial constructors or destructors are required.
7202
7203 // FIXME: Handle references.
Alexis Huntf479f1b2011-05-09 18:22:59 +00007204 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007205 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
7206 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Alexis Huntf479f1b2011-05-09 18:22:59 +00007207 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
7208 RD->hasTrivialCopyConstructor() &&
7209 RD->hasTrivialMoveConstructor() &&
7210 RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007211 return true;
7212 }
7213 }
7214
7215 GVALinkage L = GetGVALinkageForVariable(VD);
7216 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
7217 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
7218 return false;
7219 }
7220
7221 return true;
7222}
Charles Davis53c59df2010-08-16 03:33:14 +00007223
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007224CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davis99202b32010-11-09 18:04:24 +00007225 // Pass through to the C++ ABI object
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007226 return ABI->getDefaultMethodCallConv(isVariadic);
7227}
7228
7229CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
7230 if (CC == CC_C && !LangOpts.MRTD && getTargetInfo().getCXXABI() != CXXABI_Microsoft)
7231 return CC_Default;
7232 return CC;
Charles Davis99202b32010-11-09 18:04:24 +00007233}
7234
Jay Foad39c79802011-01-12 09:06:06 +00007235bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007236 // Pass through to the C++ ABI object
7237 return ABI->isNearlyEmpty(RD);
7238}
7239
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007240MangleContext *ASTContext::createMangleContext() {
Douglas Gregore8bbc122011-09-02 00:18:52 +00007241 switch (Target->getCXXABI()) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007242 case CXXABI_ARM:
7243 case CXXABI_Itanium:
7244 return createItaniumMangleContext(*this, getDiagnostics());
7245 case CXXABI_Microsoft:
7246 return createMicrosoftMangleContext(*this, getDiagnostics());
7247 }
David Blaikie83d382b2011-09-23 05:06:16 +00007248 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007249}
7250
Charles Davis53c59df2010-08-16 03:33:14 +00007251CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007252
7253size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00007254 return ASTRecordLayouts.getMemorySize()
7255 + llvm::capacity_in_bytes(ObjCLayouts)
7256 + llvm::capacity_in_bytes(KeyFunctions)
7257 + llvm::capacity_in_bytes(ObjCImpls)
7258 + llvm::capacity_in_bytes(BlockVarCopyInits)
7259 + llvm::capacity_in_bytes(DeclAttrs)
7260 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7261 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7262 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7263 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7264 + llvm::capacity_in_bytes(OverriddenMethods)
7265 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007266 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00007267 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007268}
Ted Kremenek540017e2011-10-06 05:00:56 +00007269
Douglas Gregor63798542012-02-20 19:44:39 +00007270unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7271 CXXRecordDecl *Lambda = CallOperator->getParent();
7272 return LambdaMangleContexts[Lambda->getDeclContext()]
7273 .getManglingNumber(CallOperator);
7274}
7275
7276
Ted Kremenek540017e2011-10-06 05:00:56 +00007277void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7278 ParamIndices[D] = index;
7279}
7280
7281unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7282 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7283 assert(I != ParamIndices.end() &&
7284 "ParmIndices lacks entry set by ParmVarDecl");
7285 return I->second;
7286}