blob: 916e7d796fb02f4fad2ae3d40591a540e73e7599 [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"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000022#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +000023#include "clang/AST/ASTMutationListener.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000024#include "clang/AST/RecordLayout.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000025#include "clang/AST/Mangle.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000027#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000028#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000029#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000030#include "llvm/ADT/StringExtras.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000031#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000032#include "llvm/Support/raw_ostream.h"
Ted Kremenek7d39c9a2011-07-27 18:41:12 +000033#include "llvm/Support/Capacity.h"
Charles Davis53c59df2010-08-16 03:33:14 +000034#include "CXXABI.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000035#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000036
Chris Lattnerddc135e2006-11-10 06:34:16 +000037using namespace clang;
38
Douglas Gregor9672f922010-07-03 00:47:00 +000039unsigned ASTContext::NumImplicitDefaultConstructors;
40unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000041unsigned ASTContext::NumImplicitCopyConstructors;
42unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000043unsigned ASTContext::NumImplicitMoveConstructors;
44unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000045unsigned ASTContext::NumImplicitCopyAssignmentOperators;
46unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000047unsigned ASTContext::NumImplicitMoveAssignmentOperators;
48unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000049unsigned ASTContext::NumImplicitDestructors;
50unsigned ASTContext::NumImplicitDestructorsDeclared;
51
Steve Naroff0af91202007-04-27 21:51:21 +000052enum FloatingRank {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000053 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Steve Naroff0af91202007-04-27 21:51:21 +000054};
55
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000056const RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
57 if (!CommentsLoaded && ExternalSource) {
58 ExternalSource->ReadComments();
59 CommentsLoaded = true;
60 }
61
62 assert(D);
63
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000064 // User can not attach documentation to implicit declarations.
65 if (D->isImplicit())
66 return NULL;
67
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000068 // TODO: handle comments for function parameters properly.
69 if (isa<ParmVarDecl>(D))
70 return NULL;
71
72 ArrayRef<RawComment> RawComments = Comments.getComments();
73
74 // If there are no comments anywhere, we won't find anything.
75 if (RawComments.empty())
76 return NULL;
77
78 // If the declaration doesn't map directly to a location in a file, we
79 // can't find the comment.
80 SourceLocation DeclLoc = D->getLocation();
81 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
82 return NULL;
83
84 // Find the comment that occurs just after this declaration.
85 ArrayRef<RawComment>::iterator Comment
86 = std::lower_bound(RawComments.begin(),
87 RawComments.end(),
Dmitri Gribenkofecc2e02012-06-21 21:02:45 +000088 RawComment(SourceMgr, SourceRange(DeclLoc)),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000089 BeforeThanCompare<RawComment>(SourceMgr));
90
91 // Decompose the location for the declaration and find the beginning of the
92 // file buffer.
93 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
94
95 // First check whether we have a trailing comment.
96 if (Comment != RawComments.end() &&
Dmitri Gribenko5188c4b2012-06-26 20:39:18 +000097 Comment->isDocumentation() && Comment->isTrailingComment() &&
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000098 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D)) {
99 std::pair<FileID, unsigned> CommentBeginDecomp
100 = SourceMgr.getDecomposedLoc(Comment->getSourceRange().getBegin());
101 // Check that Doxygen trailing comment comes after the declaration, starts
102 // on the same line and in the same file as the declaration.
103 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
104 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
105 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
106 CommentBeginDecomp.second)) {
107 return &*Comment;
108 }
109 }
110
111 // The comment just after the declaration was not a trailing comment.
112 // Let's look at the previous comment.
113 if (Comment == RawComments.begin())
114 return NULL;
115 --Comment;
116
117 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko5188c4b2012-06-26 20:39:18 +0000118 if (!Comment->isDocumentation() || Comment->isTrailingComment())
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000119 return NULL;
120
121 // Decompose the end of the comment.
122 std::pair<FileID, unsigned> CommentEndDecomp
123 = SourceMgr.getDecomposedLoc(Comment->getSourceRange().getEnd());
124
125 // If the comment and the declaration aren't in the same file, then they
126 // aren't related.
127 if (DeclLocDecomp.first != CommentEndDecomp.first)
128 return NULL;
129
130 // Get the corresponding buffer.
131 bool Invalid = false;
132 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
133 &Invalid).data();
134 if (Invalid)
135 return NULL;
136
137 // Extract text between the comment and declaration.
138 StringRef Text(Buffer + CommentEndDecomp.second,
139 DeclLocDecomp.second - CommentEndDecomp.second);
140
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000141 // There should be no other declarations or preprocessor directives between
142 // comment and declaration.
143 if (Text.find_first_of(",;{}#") != StringRef::npos)
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000144 return NULL;
145
146 return &*Comment;
147}
148
149const RawComment *ASTContext::getRawCommentForDecl(const Decl *D) const {
150 // Check whether we have cached a comment string for this declaration
151 // already.
152 llvm::DenseMap<const Decl *, const RawComment *>::iterator Pos
153 = DeclComments.find(D);
154 if (Pos != DeclComments.end())
155 return Pos->second;
156
157 const RawComment *RC = getRawCommentForDeclNoCache(D);
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000158 // If we found a comment, it should be a documentation comment.
159 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000160 DeclComments[D] = RC;
161 return RC;
162}
163
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000164void
165ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
166 TemplateTemplateParmDecl *Parm) {
167 ID.AddInteger(Parm->getDepth());
168 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000169 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000170
171 TemplateParameterList *Params = Parm->getTemplateParameters();
172 ID.AddInteger(Params->size());
173 for (TemplateParameterList::const_iterator P = Params->begin(),
174 PEnd = Params->end();
175 P != PEnd; ++P) {
176 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
177 ID.AddInteger(0);
178 ID.AddBoolean(TTP->isParameterPack());
179 continue;
180 }
181
182 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
183 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000184 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000185 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000186 if (NTTP->isExpandedParameterPack()) {
187 ID.AddBoolean(true);
188 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000189 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
190 QualType T = NTTP->getExpansionType(I);
191 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
192 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000193 } else
194 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000195 continue;
196 }
197
198 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
199 ID.AddInteger(2);
200 Profile(ID, TTP);
201 }
202}
203
204TemplateTemplateParmDecl *
205ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000206 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000207 // Check if we already have a canonical template template parameter.
208 llvm::FoldingSetNodeID ID;
209 CanonicalTemplateTemplateParm::Profile(ID, TTP);
210 void *InsertPos = 0;
211 CanonicalTemplateTemplateParm *Canonical
212 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
213 if (Canonical)
214 return Canonical->getParam();
215
216 // Build a canonical template parameter list.
217 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000218 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000219 CanonParams.reserve(Params->size());
220 for (TemplateParameterList::const_iterator P = Params->begin(),
221 PEnd = Params->end();
222 P != PEnd; ++P) {
223 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
224 CanonParams.push_back(
225 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000226 SourceLocation(),
227 SourceLocation(),
228 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000229 TTP->getIndex(), 0, false,
230 TTP->isParameterPack()));
231 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000232 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
233 QualType T = getCanonicalType(NTTP->getType());
234 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
235 NonTypeTemplateParmDecl *Param;
236 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000237 SmallVector<QualType, 2> ExpandedTypes;
238 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000239 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
240 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
241 ExpandedTInfos.push_back(
242 getTrivialTypeSourceInfo(ExpandedTypes.back()));
243 }
244
245 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000246 SourceLocation(),
247 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000248 NTTP->getDepth(),
249 NTTP->getPosition(), 0,
250 T,
251 TInfo,
252 ExpandedTypes.data(),
253 ExpandedTypes.size(),
254 ExpandedTInfos.data());
255 } else {
256 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000257 SourceLocation(),
258 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000259 NTTP->getDepth(),
260 NTTP->getPosition(), 0,
261 T,
262 NTTP->isParameterPack(),
263 TInfo);
264 }
265 CanonParams.push_back(Param);
266
267 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000268 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
269 cast<TemplateTemplateParmDecl>(*P)));
270 }
271
272 TemplateTemplateParmDecl *CanonTTP
273 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
274 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000275 TTP->getPosition(),
276 TTP->isParameterPack(),
277 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000278 TemplateParameterList::Create(*this, SourceLocation(),
279 SourceLocation(),
280 CanonParams.data(),
281 CanonParams.size(),
282 SourceLocation()));
283
284 // Get the new insert position for the node we care about.
285 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
286 assert(Canonical == 0 && "Shouldn't be in the map!");
287 (void)Canonical;
288
289 // Create the canonical template template parameter entry.
290 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
291 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
292 return CanonTTP;
293}
294
Charles Davis53c59df2010-08-16 03:33:14 +0000295CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000296 if (!LangOpts.CPlusPlus) return 0;
297
Charles Davis6bcb07a2010-08-19 02:18:14 +0000298 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000299 case CXXABI_ARM:
300 return CreateARMCXXABI(*this);
301 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000302 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000303 case CXXABI_Microsoft:
304 return CreateMicrosoftCXXABI(*this);
305 }
David Blaikie8a40f702012-01-17 06:56:22 +0000306 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000307}
308
Douglas Gregore8bbc122011-09-02 00:18:52 +0000309static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000310 const LangOptions &LOpts) {
311 if (LOpts.FakeAddressSpaceMap) {
312 // The fake address space map must have a distinct entry for each
313 // language-specific address space.
314 static const unsigned FakeAddrSpaceMap[] = {
315 1, // opencl_global
316 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000317 3, // opencl_constant
318 4, // cuda_device
319 5, // cuda_constant
320 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000321 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000322 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000323 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000324 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000325 }
326}
327
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000328ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000329 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000330 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000331 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000332 unsigned size_reserve,
333 bool DelayInitialization)
334 : FunctionProtoTypes(this_()),
335 TemplateSpecializationTypes(this_()),
336 DependentTemplateSpecializationTypes(this_()),
337 SubstTemplateTemplateParmPacks(this_()),
338 GlobalNestedNameSpecifier(0),
339 Int128Decl(0), UInt128Decl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000340 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000341 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000342 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000343 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000344 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
345 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
346 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000347 NullTypeSourceInfo(QualType()),
348 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000349 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000350 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000351 Idents(idents), Selectors(sels),
352 BuiltinInfo(builtins),
353 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000354 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000355 Comments(SM), CommentsLoaded(false),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000356 LastSDM(0, 0),
357 UniqueBlockByRefTypeID(0)
358{
Mike Stump11289f42009-09-09 15:08:12 +0000359 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000360 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000361
362 if (!DelayInitialization) {
363 assert(t && "No target supplied for ASTContext initialization");
364 InitBuiltinTypes(*t);
365 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000366}
367
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000368ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000369 // Release the DenseMaps associated with DeclContext objects.
370 // FIXME: Is this the ideal solution?
371 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000372
Douglas Gregor5b11d492010-07-25 17:53:33 +0000373 // Call all of the deallocation functions.
374 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
375 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000376
Ted Kremenek076baeb2010-06-08 23:00:58 +0000377 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000378 // because they can contain DenseMaps.
379 for (llvm::DenseMap<const ObjCContainerDecl*,
380 const ASTRecordLayout*>::iterator
381 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
382 // Increment in loop to prevent using deallocated memory.
383 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
384 R->Destroy(*this);
385
Ted Kremenek076baeb2010-06-08 23:00:58 +0000386 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
387 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
388 // Increment in loop to prevent using deallocated memory.
389 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
390 R->Destroy(*this);
391 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000392
393 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
394 AEnd = DeclAttrs.end();
395 A != AEnd; ++A)
396 A->second->~AttrVec();
397}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000398
Douglas Gregor1a809332010-05-23 18:26:36 +0000399void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
400 Deallocations.push_back(std::make_pair(Callback, Data));
401}
402
Mike Stump11289f42009-09-09 15:08:12 +0000403void
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000404ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000405 ExternalSource.reset(Source.take());
406}
407
Chris Lattner4eb445d2007-01-26 01:27:23 +0000408void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000409 llvm::errs() << "\n*** AST Context Stats:\n";
410 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000411
Douglas Gregora30d0462009-05-26 14:40:08 +0000412 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000413#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000414#define ABSTRACT_TYPE(Name, Parent)
415#include "clang/AST/TypeNodes.def"
416 0 // Extra
417 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000418
Chris Lattner4eb445d2007-01-26 01:27:23 +0000419 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
420 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000421 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000422 }
423
Douglas Gregora30d0462009-05-26 14:40:08 +0000424 unsigned Idx = 0;
425 unsigned TotalBytes = 0;
426#define TYPE(Name, Parent) \
427 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000428 llvm::errs() << " " << counts[Idx] << " " << #Name \
429 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000430 TotalBytes += counts[Idx] * sizeof(Name##Type); \
431 ++Idx;
432#define ABSTRACT_TYPE(Name, Parent)
433#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000434
Chandler Carruth3c147a72011-07-04 05:32:14 +0000435 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
436
Douglas Gregor7454c562010-07-02 20:37:36 +0000437 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000438 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
439 << NumImplicitDefaultConstructors
440 << " implicit default constructors created\n";
441 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
442 << NumImplicitCopyConstructors
443 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000444 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000445 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
446 << NumImplicitMoveConstructors
447 << " implicit move constructors created\n";
448 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
449 << NumImplicitCopyAssignmentOperators
450 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000451 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000452 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
453 << NumImplicitMoveAssignmentOperators
454 << " implicit move assignment operators created\n";
455 llvm::errs() << NumImplicitDestructorsDeclared << "/"
456 << NumImplicitDestructors
457 << " implicit destructors created\n";
458
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000459 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000460 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000461 ExternalSource->PrintStats();
462 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000463
Douglas Gregor5b11d492010-07-25 17:53:33 +0000464 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000465}
466
Douglas Gregor801c99d2011-08-12 06:49:56 +0000467TypedefDecl *ASTContext::getInt128Decl() const {
468 if (!Int128Decl) {
469 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
470 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
471 getTranslationUnitDecl(),
472 SourceLocation(),
473 SourceLocation(),
474 &Idents.get("__int128_t"),
475 TInfo);
476 }
477
478 return Int128Decl;
479}
480
481TypedefDecl *ASTContext::getUInt128Decl() const {
482 if (!UInt128Decl) {
483 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
484 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
485 getTranslationUnitDecl(),
486 SourceLocation(),
487 SourceLocation(),
488 &Idents.get("__uint128_t"),
489 TInfo);
490 }
491
492 return UInt128Decl;
493}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000494
John McCall48f2d582009-10-23 23:03:21 +0000495void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000496 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000497 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000498 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000499}
500
Douglas Gregore8bbc122011-09-02 00:18:52 +0000501void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
502 assert((!this->Target || this->Target == &Target) &&
503 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000504 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000505
Douglas Gregore8bbc122011-09-02 00:18:52 +0000506 this->Target = &Target;
507
508 ABI.reset(createCXXABI(Target));
509 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
510
Chris Lattner970e54e2006-11-12 00:37:36 +0000511 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000512 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000513
Chris Lattner970e54e2006-11-12 00:37:36 +0000514 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000515 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000516 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000517 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000518 InitBuiltinType(CharTy, BuiltinType::Char_S);
519 else
520 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000521 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000522 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
523 InitBuiltinType(ShortTy, BuiltinType::Short);
524 InitBuiltinType(IntTy, BuiltinType::Int);
525 InitBuiltinType(LongTy, BuiltinType::Long);
526 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000527
Chris Lattner970e54e2006-11-12 00:37:36 +0000528 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000529 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
530 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
531 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
532 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
533 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000534
Chris Lattner970e54e2006-11-12 00:37:36 +0000535 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000536 InitBuiltinType(FloatTy, BuiltinType::Float);
537 InitBuiltinType(DoubleTy, BuiltinType::Double);
538 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000539
Chris Lattnerf122cef2009-04-30 02:43:43 +0000540 // GNU extension, 128-bit integers.
541 InitBuiltinType(Int128Ty, BuiltinType::Int128);
542 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
543
Chris Lattnerad3467e2010-12-25 23:25:43 +0000544 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedman786d0872011-04-30 19:24:24 +0000545 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000546 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
547 else // -fshort-wchar makes wchar_t be unsigned.
548 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
549 } else // C99
Chris Lattner007cb022009-02-26 23:43:47 +0000550 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000551
James Molloy36365542012-05-04 10:55:22 +0000552 WIntTy = getFromTargetType(Target.getWIntType());
553
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000554 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
555 InitBuiltinType(Char16Ty, BuiltinType::Char16);
556 else // C99
557 Char16Ty = getFromTargetType(Target.getChar16Type());
558
559 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
560 InitBuiltinType(Char32Ty, BuiltinType::Char32);
561 else // C99
562 Char32Ty = getFromTargetType(Target.getChar32Type());
563
Douglas Gregor4619e432008-12-05 23:32:09 +0000564 // Placeholder type for type-dependent expressions whose type is
565 // completely unknown. No code should ever check a type against
566 // DependentTy and users should never see it; however, it is here to
567 // help diagnose failures to properly check for type-dependent
568 // expressions.
569 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000570
John McCall36e7fe32010-10-12 00:20:44 +0000571 // Placeholder type for functions.
572 InitBuiltinType(OverloadTy, BuiltinType::Overload);
573
John McCall0009fcc2011-04-26 20:42:42 +0000574 // Placeholder type for bound members.
575 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
576
John McCall526ab472011-10-25 17:37:35 +0000577 // Placeholder type for pseudo-objects.
578 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
579
John McCall31996342011-04-07 08:22:57 +0000580 // "any" type; useful for debugger-like clients.
581 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
582
John McCall8a6b59a2011-10-17 18:09:15 +0000583 // Placeholder type for unbridged ARC casts.
584 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
585
Chris Lattner970e54e2006-11-12 00:37:36 +0000586 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000587 FloatComplexTy = getComplexType(FloatTy);
588 DoubleComplexTy = getComplexType(DoubleTy);
589 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000590
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000591 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000592 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
593 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000594 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000595
596 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +0000597 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
598 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000599
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000600 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000601
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000602 // void * type
603 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000604
605 // nullptr type (C++0x 2.14.7)
606 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000607
608 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
609 InitBuiltinType(HalfTy, BuiltinType::Half);
Chris Lattner970e54e2006-11-12 00:37:36 +0000610}
611
David Blaikie9c902b52011-09-25 23:23:43 +0000612DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000613 return SourceMgr.getDiagnostics();
614}
615
Douglas Gregor561eceb2010-08-30 16:49:28 +0000616AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
617 AttrVec *&Result = DeclAttrs[D];
618 if (!Result) {
619 void *Mem = Allocate(sizeof(AttrVec));
620 Result = new (Mem) AttrVec;
621 }
622
623 return *Result;
624}
625
626/// \brief Erase the attributes corresponding to the given declaration.
627void ASTContext::eraseDeclAttrs(const Decl *D) {
628 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
629 if (Pos != DeclAttrs.end()) {
630 Pos->second->~AttrVec();
631 DeclAttrs.erase(Pos);
632 }
633}
634
Douglas Gregor86d142a2009-10-08 07:24:58 +0000635MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000636ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000637 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000638 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000639 = InstantiatedFromStaticDataMember.find(Var);
640 if (Pos == InstantiatedFromStaticDataMember.end())
641 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000642
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000643 return Pos->second;
644}
645
Mike Stump11289f42009-09-09 15:08:12 +0000646void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000647ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000648 TemplateSpecializationKind TSK,
649 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000650 assert(Inst->isStaticDataMember() && "Not a static data member");
651 assert(Tmpl->isStaticDataMember() && "Not a static data member");
652 assert(!InstantiatedFromStaticDataMember[Inst] &&
653 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000654 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000655 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000656}
657
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000658FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
659 const FunctionDecl *FD){
660 assert(FD && "Specialization is 0");
661 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +0000662 = ClassScopeSpecializationPattern.find(FD);
663 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000664 return 0;
665
666 return Pos->second;
667}
668
669void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
670 FunctionDecl *Pattern) {
671 assert(FD && "Specialization is 0");
672 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +0000673 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000674}
675
John McCalle61f2ba2009-11-18 02:36:19 +0000676NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000677ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000678 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000679 = InstantiatedFromUsingDecl.find(UUD);
680 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000681 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000682
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000683 return Pos->second;
684}
685
686void
John McCallb96ec562009-12-04 22:46:56 +0000687ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
688 assert((isa<UsingDecl>(Pattern) ||
689 isa<UnresolvedUsingValueDecl>(Pattern) ||
690 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
691 "pattern decl is not a using decl");
692 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
693 InstantiatedFromUsingDecl[Inst] = Pattern;
694}
695
696UsingShadowDecl *
697ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
698 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
699 = InstantiatedFromUsingShadowDecl.find(Inst);
700 if (Pos == InstantiatedFromUsingShadowDecl.end())
701 return 0;
702
703 return Pos->second;
704}
705
706void
707ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
708 UsingShadowDecl *Pattern) {
709 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
710 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000711}
712
Anders Carlsson5da84842009-09-01 04:26:58 +0000713FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
714 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
715 = InstantiatedFromUnnamedFieldDecl.find(Field);
716 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
717 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000718
Anders Carlsson5da84842009-09-01 04:26:58 +0000719 return Pos->second;
720}
721
722void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
723 FieldDecl *Tmpl) {
724 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
725 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
726 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
727 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000728
Anders Carlsson5da84842009-09-01 04:26:58 +0000729 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
730}
731
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000732bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
733 const FieldDecl *LastFD) const {
734 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000735 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000736}
737
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000738bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
739 const FieldDecl *LastFD) const {
740 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000741 FD->getBitWidthValue(*this) == 0 &&
742 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000743}
744
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000745bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
746 const FieldDecl *LastFD) const {
747 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000748 FD->getBitWidthValue(*this) &&
749 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000750}
751
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000752bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000753 const FieldDecl *LastFD) const {
754 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000755 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000756}
757
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000758bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000759 const FieldDecl *LastFD) const {
760 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000761 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000762}
763
Douglas Gregor832940b2010-03-02 23:58:15 +0000764ASTContext::overridden_cxx_method_iterator
765ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
766 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
767 = OverriddenMethods.find(Method);
768 if (Pos == OverriddenMethods.end())
769 return 0;
770
771 return Pos->second.begin();
772}
773
774ASTContext::overridden_cxx_method_iterator
775ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
776 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
777 = OverriddenMethods.find(Method);
778 if (Pos == OverriddenMethods.end())
779 return 0;
780
781 return Pos->second.end();
782}
783
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000784unsigned
785ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
786 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
787 = OverriddenMethods.find(Method);
788 if (Pos == OverriddenMethods.end())
789 return 0;
790
791 return Pos->second.size();
792}
793
Douglas Gregor832940b2010-03-02 23:58:15 +0000794void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
795 const CXXMethodDecl *Overridden) {
796 OverriddenMethods[Method].push_back(Overridden);
797}
798
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000799void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
800 assert(!Import->NextLocalImport && "Import declaration already in the chain");
801 assert(!Import->isFromASTFile() && "Non-local import declaration");
802 if (!FirstLocalImport) {
803 FirstLocalImport = Import;
804 LastLocalImport = Import;
805 return;
806 }
807
808 LastLocalImport->NextLocalImport = Import;
809 LastLocalImport = Import;
810}
811
Chris Lattner53cfe802007-07-18 17:52:12 +0000812//===----------------------------------------------------------------------===//
813// Type Sizing and Analysis
814//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000815
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000816/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
817/// scalar floating point type.
818const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000819 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000820 assert(BT && "Not a floating point type!");
821 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +0000822 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000823 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +0000824 case BuiltinType::Float: return Target->getFloatFormat();
825 case BuiltinType::Double: return Target->getDoubleFormat();
826 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000827 }
828}
829
Ken Dyck160146e2010-01-27 17:10:57 +0000830/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000831/// specified decl. Note that bitfields do not have a valid alignment, so
832/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000833/// If @p RefAsPointee, references are treated like their underlying type
834/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000835CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000836 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +0000837
John McCall94268702010-10-08 18:24:19 +0000838 bool UseAlignAttrOnly = false;
839 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
840 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000841
John McCall94268702010-10-08 18:24:19 +0000842 // __attribute__((aligned)) can increase or decrease alignment
843 // *except* on a struct or struct member, where it only increases
844 // alignment unless 'packed' is also specified.
845 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +0000846 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +0000847 // ignore that possibility; Sema should diagnose it.
848 if (isa<FieldDecl>(D)) {
849 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
850 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
851 } else {
852 UseAlignAttrOnly = true;
853 }
854 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +0000855 else if (isa<FieldDecl>(D))
856 UseAlignAttrOnly =
857 D->hasAttr<PackedAttr>() ||
858 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +0000859
John McCall4e819612011-01-20 07:57:12 +0000860 // If we're using the align attribute only, just ignore everything
861 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +0000862 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +0000863 // do nothing
864
John McCall94268702010-10-08 18:24:19 +0000865 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000866 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000867 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000868 if (RefAsPointee)
869 T = RT->getPointeeType();
870 else
871 T = getPointerType(RT->getPointeeType());
872 }
873 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +0000874 // Adjust alignments of declarations with array type by the
875 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +0000876 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +0000877 const ArrayType *arrayType;
878 if (MinWidth && (arrayType = getAsArrayType(T))) {
879 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000880 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +0000881 else if (isa<ConstantArrayType>(arrayType) &&
882 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000883 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +0000884
John McCall33ddac02011-01-19 10:06:00 +0000885 // Walk through any array types while we're at it.
886 T = getBaseElementType(arrayType);
887 }
Chad Rosier99ee7822011-07-26 07:03:04 +0000888 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +0000889 }
John McCall4e819612011-01-20 07:57:12 +0000890
891 // Fields can be subject to extra alignment constraints, like if
892 // the field is packed, the struct is packed, or the struct has a
893 // a max-field-alignment constraint (#pragma pack). So calculate
894 // the actual alignment of the field within the struct, and then
895 // (as we're expected to) constrain that by the alignment of the type.
896 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
897 // So calculate the alignment of the field.
898 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
899
900 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +0000901 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +0000902
903 // Use the GCD of that and the offset within the record.
904 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
905 if (offset > 0) {
906 // Alignment is always a power of 2, so the GCD will be a power of 2,
907 // which means we get to do this crazy thing instead of Euclid's.
908 uint64_t lowBitOfOffset = offset & (~offset + 1);
909 if (lowBitOfOffset < fieldAlign)
910 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
911 }
912
913 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +0000914 }
Chris Lattner68061312009-01-24 21:53:27 +0000915 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000916
Ken Dyckcc56c542011-01-15 18:38:59 +0000917 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +0000918}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000919
John McCall87fe5d52010-05-20 01:18:31 +0000920std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000921ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000922 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +0000923 return std::make_pair(toCharUnitsFromBits(Info.first),
924 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +0000925}
926
927std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000928ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000929 return getTypeInfoInChars(T.getTypePtr());
930}
931
Daniel Dunbarc6475872012-03-09 04:12:54 +0000932std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
933 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
934 if (it != MemoizedTypeInfo.end())
935 return it->second;
936
937 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
938 MemoizedTypeInfo.insert(std::make_pair(T, Info));
939 return Info;
940}
941
942/// getTypeInfoImpl - Return the size of the specified type, in bits. This
943/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000944///
945/// FIXME: Pointers into different addr spaces could have different sizes and
946/// alignment requirements: getPointerInfo should take an AddrSpace, this
947/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000948std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +0000949ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000950 uint64_t Width=0;
951 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000952 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000953#define TYPE(Class, Base)
954#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000955#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000956#define DEPENDENT_TYPE(Class, Base) case Type::Class:
957#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +0000958 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000959
Chris Lattner355332d2007-07-13 22:27:08 +0000960 case Type::FunctionNoProto:
961 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000962 // GCC extension: alignof(function) = 32 bits
963 Width = 0;
964 Align = 32;
965 break;
966
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000967 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000968 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000969 Width = 0;
970 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
971 break;
972
Steve Naroff5c131802007-08-30 01:06:46 +0000973 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000974 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000975
Chris Lattner37e05872008-03-05 18:54:05 +0000976 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +0000977 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +0000978 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
979 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +0000980 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000981 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +0000982 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000983 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000984 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000985 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000986 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000987 const VectorType *VT = cast<VectorType>(T);
988 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
989 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000990 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000991 // If the alignment is not a power of 2, round up to the next power of 2.
992 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000993 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000994 Align = llvm::NextPowerOf2(Align);
995 Width = llvm::RoundUpToAlignment(Width, Align);
996 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000997 break;
998 }
Chris Lattner647fb222007-07-18 18:26:58 +0000999
Chris Lattner7570e9c2008-03-08 08:52:55 +00001000 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001001 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001002 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001003 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001004 // GCC extension: alignof(void) = 8 bits.
1005 Width = 0;
1006 Align = 8;
1007 break;
1008
Chris Lattner6a4f7452007-12-19 19:23:28 +00001009 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001010 Width = Target->getBoolWidth();
1011 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001012 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001013 case BuiltinType::Char_S:
1014 case BuiltinType::Char_U:
1015 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001016 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001017 Width = Target->getCharWidth();
1018 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001019 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001020 case BuiltinType::WChar_S:
1021 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001022 Width = Target->getWCharWidth();
1023 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001024 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001025 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001026 Width = Target->getChar16Width();
1027 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001028 break;
1029 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001030 Width = Target->getChar32Width();
1031 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001032 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001033 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001034 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001035 Width = Target->getShortWidth();
1036 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001037 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001038 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001039 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001040 Width = Target->getIntWidth();
1041 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001042 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001043 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001044 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001045 Width = Target->getLongWidth();
1046 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001047 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001048 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001049 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001050 Width = Target->getLongLongWidth();
1051 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001052 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001053 case BuiltinType::Int128:
1054 case BuiltinType::UInt128:
1055 Width = 128;
1056 Align = 128; // int128_t is 128-bit aligned on all targets.
1057 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001058 case BuiltinType::Half:
1059 Width = Target->getHalfWidth();
1060 Align = Target->getHalfAlign();
1061 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001062 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001063 Width = Target->getFloatWidth();
1064 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001065 break;
1066 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001067 Width = Target->getDoubleWidth();
1068 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001069 break;
1070 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001071 Width = Target->getLongDoubleWidth();
1072 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001073 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001074 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001075 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1076 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001077 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001078 case BuiltinType::ObjCId:
1079 case BuiltinType::ObjCClass:
1080 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001081 Width = Target->getPointerWidth(0);
1082 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001083 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001084 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001085 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001086 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001087 Width = Target->getPointerWidth(0);
1088 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001089 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001090 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001091 unsigned AS = getTargetAddressSpace(
1092 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001093 Width = Target->getPointerWidth(AS);
1094 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001095 break;
1096 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001097 case Type::LValueReference:
1098 case Type::RValueReference: {
1099 // alignof and sizeof should never enter this code path here, so we go
1100 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001101 unsigned AS = getTargetAddressSpace(
1102 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001103 Width = Target->getPointerWidth(AS);
1104 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001105 break;
1106 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001107 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001108 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001109 Width = Target->getPointerWidth(AS);
1110 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001111 break;
1112 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001113 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001114 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001115 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +00001116 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +00001117 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001118 Align = PtrDiffInfo.second;
1119 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001120 }
Chris Lattner647fb222007-07-18 18:26:58 +00001121 case Type::Complex: {
1122 // Complex types have the same alignment as their elements, but twice the
1123 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001124 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001125 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001126 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001127 Align = EltInfo.second;
1128 break;
1129 }
John McCall8b07ec22010-05-15 11:32:37 +00001130 case Type::ObjCObject:
1131 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001132 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001133 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001134 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001135 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001136 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001137 break;
1138 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001139 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001140 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001141 const TagType *TT = cast<TagType>(T);
1142
1143 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001144 Width = 8;
1145 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001146 break;
1147 }
Mike Stump11289f42009-09-09 15:08:12 +00001148
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001149 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001150 return getTypeInfo(ET->getDecl()->getIntegerType());
1151
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001152 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001153 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001154 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001155 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001156 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001157 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001158
Chris Lattner63d2b362009-10-22 05:17:15 +00001159 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001160 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1161 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001162
Richard Smith30482bc2011-02-20 03:19:35 +00001163 case Type::Auto: {
1164 const AutoType *A = cast<AutoType>(T);
1165 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001166 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001167 }
1168
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001169 case Type::Paren:
1170 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1171
Douglas Gregoref462e62009-04-30 17:32:17 +00001172 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001173 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001174 std::pair<uint64_t, unsigned> Info
1175 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001176 // If the typedef has an aligned attribute on it, it overrides any computed
1177 // alignment we have. This violates the GCC documentation (which says that
1178 // attribute(aligned) can only round up) but matches its implementation.
1179 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1180 Align = AttrAlign;
1181 else
1182 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001183 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001184 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001185 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001186
1187 case Type::TypeOfExpr:
1188 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1189 .getTypePtr());
1190
1191 case Type::TypeOf:
1192 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1193
Anders Carlsson81df7b82009-06-24 19:06:50 +00001194 case Type::Decltype:
1195 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1196 .getTypePtr());
1197
Alexis Hunte852b102011-05-24 22:41:36 +00001198 case Type::UnaryTransform:
1199 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1200
Abramo Bagnara6150c882010-05-11 21:36:43 +00001201 case Type::Elaborated:
1202 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001203
John McCall81904512011-01-06 01:58:22 +00001204 case Type::Attributed:
1205 return getTypeInfo(
1206 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1207
Richard Smith3f1b5d02011-05-05 21:57:07 +00001208 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001209 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001210 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001211 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1212 // A type alias template specialization may refer to a typedef with the
1213 // aligned attribute on it.
1214 if (TST->isTypeAlias())
1215 return getTypeInfo(TST->getAliasedType().getTypePtr());
1216 else
1217 return getTypeInfo(getCanonicalType(T));
1218 }
1219
Eli Friedman0dfb8892011-10-06 23:00:33 +00001220 case Type::Atomic: {
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001221 std::pair<uint64_t, unsigned> Info
1222 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1223 Width = Info.first;
1224 Align = Info.second;
1225 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1226 llvm::isPowerOf2_64(Width)) {
1227 // We can potentially perform lock-free atomic operations for this
1228 // type; promote the alignment appropriately.
1229 // FIXME: We could potentially promote the width here as well...
1230 // is that worthwhile? (Non-struct atomic types generally have
1231 // power-of-two size anyway, but structs might not. Requires a bit
1232 // of implementation work to make sure we zero out the extra bits.)
1233 Align = static_cast<unsigned>(Width);
1234 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001235 }
1236
Douglas Gregoref462e62009-04-30 17:32:17 +00001237 }
Mike Stump11289f42009-09-09 15:08:12 +00001238
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001239 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001240 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001241}
1242
Ken Dyckcc56c542011-01-15 18:38:59 +00001243/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1244CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1245 return CharUnits::fromQuantity(BitSize / getCharWidth());
1246}
1247
Ken Dyckb0fcc592011-02-11 01:54:29 +00001248/// toBits - Convert a size in characters to a size in characters.
1249int64_t ASTContext::toBits(CharUnits CharSize) const {
1250 return CharSize.getQuantity() * getCharWidth();
1251}
1252
Ken Dyck8c89d592009-12-22 14:23:30 +00001253/// getTypeSizeInChars - Return the size of the specified type, in characters.
1254/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001255CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001256 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001257}
Jay Foad39c79802011-01-12 09:06:06 +00001258CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001259 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001260}
1261
Ken Dycka6046ab2010-01-26 17:25:18 +00001262/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001263/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001264CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001265 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001266}
Jay Foad39c79802011-01-12 09:06:06 +00001267CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001268 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001269}
1270
Chris Lattnera3402cd2009-01-27 18:08:34 +00001271/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1272/// type for the current target in bits. This can be different than the ABI
1273/// alignment in cases where it is beneficial for performance to overalign
1274/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001275unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001276 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001277
1278 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001279 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001280 T = CT->getElementType().getTypePtr();
1281 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001282 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1283 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001284 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1285
Chris Lattnera3402cd2009-01-27 18:08:34 +00001286 return ABIAlign;
1287}
1288
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001289/// DeepCollectObjCIvars -
1290/// This routine first collects all declared, but not synthesized, ivars in
1291/// super class and then collects all ivars, including those synthesized for
1292/// current class. This routine is used for implementation of current class
1293/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001294///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001295void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1296 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001297 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001298 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1299 DeepCollectObjCIvars(SuperClass, false, Ivars);
1300 if (!leafClass) {
1301 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1302 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001303 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001304 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001305 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001306 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001307 Iv= Iv->getNextIvar())
1308 Ivars.push_back(Iv);
1309 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001310}
1311
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001312/// CollectInheritedProtocols - Collect all protocols in current class and
1313/// those inherited by it.
1314void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001315 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001316 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001317 // We can use protocol_iterator here instead of
1318 // all_referenced_protocol_iterator since we are walking all categories.
1319 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1320 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001321 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001322 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001323 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001324 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001325 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001326 CollectInheritedProtocols(*P, Protocols);
1327 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001328 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001329
1330 // Categories of this Interface.
1331 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1332 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1333 CollectInheritedProtocols(CDeclChain, Protocols);
1334 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1335 while (SD) {
1336 CollectInheritedProtocols(SD, Protocols);
1337 SD = SD->getSuperClass();
1338 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001339 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001340 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001341 PE = OC->protocol_end(); P != PE; ++P) {
1342 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001343 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001344 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1345 PE = Proto->protocol_end(); P != PE; ++P)
1346 CollectInheritedProtocols(*P, Protocols);
1347 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001348 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001349 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1350 PE = OP->protocol_end(); P != PE; ++P) {
1351 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001352 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001353 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1354 PE = Proto->protocol_end(); P != PE; ++P)
1355 CollectInheritedProtocols(*P, Protocols);
1356 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001357 }
1358}
1359
Jay Foad39c79802011-01-12 09:06:06 +00001360unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001361 unsigned count = 0;
1362 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001363 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1364 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001365 count += CDecl->ivar_size();
1366
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001367 // Count ivar defined in this class's implementation. This
1368 // includes synthesized ivars.
1369 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001370 count += ImplDecl->ivar_size();
1371
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001372 return count;
1373}
1374
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001375bool ASTContext::isSentinelNullExpr(const Expr *E) {
1376 if (!E)
1377 return false;
1378
1379 // nullptr_t is always treated as null.
1380 if (E->getType()->isNullPtrType()) return true;
1381
1382 if (E->getType()->isAnyPointerType() &&
1383 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1384 Expr::NPC_ValueDependentIsNull))
1385 return true;
1386
1387 // Unfortunately, __null has type 'int'.
1388 if (isa<GNUNullExpr>(E)) return true;
1389
1390 return false;
1391}
1392
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001393/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1394ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1395 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1396 I = ObjCImpls.find(D);
1397 if (I != ObjCImpls.end())
1398 return cast<ObjCImplementationDecl>(I->second);
1399 return 0;
1400}
1401/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1402ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1403 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1404 I = ObjCImpls.find(D);
1405 if (I != ObjCImpls.end())
1406 return cast<ObjCCategoryImplDecl>(I->second);
1407 return 0;
1408}
1409
1410/// \brief Set the implementation of ObjCInterfaceDecl.
1411void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1412 ObjCImplementationDecl *ImplD) {
1413 assert(IFaceD && ImplD && "Passed null params");
1414 ObjCImpls[IFaceD] = ImplD;
1415}
1416/// \brief Set the implementation of ObjCCategoryDecl.
1417void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1418 ObjCCategoryImplDecl *ImplD) {
1419 assert(CatD && ImplD && "Passed null params");
1420 ObjCImpls[CatD] = ImplD;
1421}
1422
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001423ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1424 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1425 return ID;
1426 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1427 return CD->getClassInterface();
1428 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1429 return IMD->getClassInterface();
1430
1431 return 0;
1432}
1433
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001434/// \brief Get the copy initialization expression of VarDecl,or NULL if
1435/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001436Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001437 assert(VD && "Passed null params");
1438 assert(VD->hasAttr<BlocksAttr>() &&
1439 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001440 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001441 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001442 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1443}
1444
1445/// \brief Set the copy inialization expression of a block var decl.
1446void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1447 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001448 assert(VD->hasAttr<BlocksAttr>() &&
1449 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001450 BlockVarCopyInits[VD] = Init;
1451}
1452
John McCallbcd03502009-12-07 02:54:59 +00001453TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001454 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001455 if (!DataSize)
1456 DataSize = TypeLoc::getFullDataSizeForType(T);
1457 else
1458 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001459 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001460
John McCallbcd03502009-12-07 02:54:59 +00001461 TypeSourceInfo *TInfo =
1462 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1463 new (TInfo) TypeSourceInfo(T);
1464 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001465}
1466
John McCallbcd03502009-12-07 02:54:59 +00001467TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001468 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001469 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001470 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001471 return DI;
1472}
1473
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001474const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001475ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001476 return getObjCLayout(D, 0);
1477}
1478
1479const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001480ASTContext::getASTObjCImplementationLayout(
1481 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001482 return getObjCLayout(D->getClassInterface(), D);
1483}
1484
Chris Lattner983a8bb2007-07-13 22:13:22 +00001485//===----------------------------------------------------------------------===//
1486// Type creation/memoization methods
1487//===----------------------------------------------------------------------===//
1488
Jay Foad39c79802011-01-12 09:06:06 +00001489QualType
John McCall33ddac02011-01-19 10:06:00 +00001490ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1491 unsigned fastQuals = quals.getFastQualifiers();
1492 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001493
1494 // Check if we've already instantiated this type.
1495 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001496 ExtQuals::Profile(ID, baseType, quals);
1497 void *insertPos = 0;
1498 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1499 assert(eq->getQualifiers() == quals);
1500 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001501 }
1502
John McCall33ddac02011-01-19 10:06:00 +00001503 // If the base type is not canonical, make the appropriate canonical type.
1504 QualType canon;
1505 if (!baseType->isCanonicalUnqualified()) {
1506 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00001507 canonSplit.Quals.addConsistentQualifiers(quals);
1508 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001509
1510 // Re-find the insert position.
1511 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1512 }
1513
1514 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1515 ExtQualNodes.InsertNode(eq, insertPos);
1516 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001517}
1518
Jay Foad39c79802011-01-12 09:06:06 +00001519QualType
1520ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001521 QualType CanT = getCanonicalType(T);
1522 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001523 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001524
John McCall8ccfcb52009-09-24 19:53:00 +00001525 // If we are composing extended qualifiers together, merge together
1526 // into one ExtQuals node.
1527 QualifierCollector Quals;
1528 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001529
John McCall8ccfcb52009-09-24 19:53:00 +00001530 // If this type already has an address space specified, it cannot get
1531 // another one.
1532 assert(!Quals.hasAddressSpace() &&
1533 "Type cannot be in multiple addr spaces!");
1534 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001535
John McCall8ccfcb52009-09-24 19:53:00 +00001536 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001537}
1538
Chris Lattnerd60183d2009-02-18 22:53:11 +00001539QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001540 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001541 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001542 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001543 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001544
John McCall53fa7142010-12-24 02:08:15 +00001545 if (const PointerType *ptr = T->getAs<PointerType>()) {
1546 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001547 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001548 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1549 return getPointerType(ResultType);
1550 }
1551 }
Mike Stump11289f42009-09-09 15:08:12 +00001552
John McCall8ccfcb52009-09-24 19:53:00 +00001553 // If we are composing extended qualifiers together, merge together
1554 // into one ExtQuals node.
1555 QualifierCollector Quals;
1556 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001557
John McCall8ccfcb52009-09-24 19:53:00 +00001558 // If this type already has an ObjCGC specified, it cannot get
1559 // another one.
1560 assert(!Quals.hasObjCGCAttr() &&
1561 "Type cannot have multiple ObjCGCs!");
1562 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001563
John McCall8ccfcb52009-09-24 19:53:00 +00001564 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001565}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001566
John McCall4f5019e2010-12-19 02:44:49 +00001567const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1568 FunctionType::ExtInfo Info) {
1569 if (T->getExtInfo() == Info)
1570 return T;
1571
1572 QualType Result;
1573 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1574 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1575 } else {
1576 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1577 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1578 EPI.ExtInfo = Info;
1579 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1580 FPT->getNumArgs(), EPI);
1581 }
1582
1583 return cast<FunctionType>(Result.getTypePtr());
1584}
1585
Chris Lattnerc6395932007-06-22 20:56:16 +00001586/// getComplexType - Return the uniqued reference to the type for a complex
1587/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001588QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001589 // Unique pointers, to guarantee there is only one pointer of a particular
1590 // structure.
1591 llvm::FoldingSetNodeID ID;
1592 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001593
Chris Lattnerc6395932007-06-22 20:56:16 +00001594 void *InsertPos = 0;
1595 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1596 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001597
Chris Lattnerc6395932007-06-22 20:56:16 +00001598 // If the pointee type isn't canonical, this won't be a canonical type either,
1599 // so fill in the canonical type field.
1600 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001601 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001602 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001603
Chris Lattnerc6395932007-06-22 20:56:16 +00001604 // Get the new insert position for the node we care about.
1605 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001606 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001607 }
John McCall90d1c2d2009-09-24 23:30:46 +00001608 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001609 Types.push_back(New);
1610 ComplexTypes.InsertNode(New, InsertPos);
1611 return QualType(New, 0);
1612}
1613
Chris Lattner970e54e2006-11-12 00:37:36 +00001614/// getPointerType - Return the uniqued reference to the type for a pointer to
1615/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001616QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001617 // Unique pointers, to guarantee there is only one pointer of a particular
1618 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001619 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001620 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001621
Chris Lattner67521df2007-01-27 01:29:36 +00001622 void *InsertPos = 0;
1623 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001624 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001625
Chris Lattner7ccecb92006-11-12 08:50:50 +00001626 // If the pointee type isn't canonical, this won't be a canonical type either,
1627 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001628 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001629 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001630 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001631
Chris Lattner67521df2007-01-27 01:29:36 +00001632 // Get the new insert position for the node we care about.
1633 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001634 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001635 }
John McCall90d1c2d2009-09-24 23:30:46 +00001636 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001637 Types.push_back(New);
1638 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001639 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001640}
1641
Mike Stump11289f42009-09-09 15:08:12 +00001642/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001643/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001644QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001645 assert(T->isFunctionType() && "block of function types only");
1646 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001647 // structure.
1648 llvm::FoldingSetNodeID ID;
1649 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001650
Steve Naroffec33ed92008-08-27 16:04:49 +00001651 void *InsertPos = 0;
1652 if (BlockPointerType *PT =
1653 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1654 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001655
1656 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001657 // type either so fill in the canonical type field.
1658 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001659 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001660 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001661
Steve Naroffec33ed92008-08-27 16:04:49 +00001662 // Get the new insert position for the node we care about.
1663 BlockPointerType *NewIP =
1664 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001665 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001666 }
John McCall90d1c2d2009-09-24 23:30:46 +00001667 BlockPointerType *New
1668 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001669 Types.push_back(New);
1670 BlockPointerTypes.InsertNode(New, InsertPos);
1671 return QualType(New, 0);
1672}
1673
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001674/// getLValueReferenceType - Return the uniqued reference to the type for an
1675/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001676QualType
1677ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00001678 assert(getCanonicalType(T) != OverloadTy &&
1679 "Unresolved overloaded function type");
1680
Bill Wendling3708c182007-05-27 10:15:43 +00001681 // Unique pointers, to guarantee there is only one pointer of a particular
1682 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001683 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001684 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001685
1686 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001687 if (LValueReferenceType *RT =
1688 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001689 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001690
John McCallfc93cf92009-10-22 22:37:11 +00001691 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1692
Bill Wendling3708c182007-05-27 10:15:43 +00001693 // If the referencee type isn't canonical, this won't be a canonical type
1694 // either, so fill in the canonical type field.
1695 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001696 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1697 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1698 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001699
Bill Wendling3708c182007-05-27 10:15:43 +00001700 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001701 LValueReferenceType *NewIP =
1702 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001703 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001704 }
1705
John McCall90d1c2d2009-09-24 23:30:46 +00001706 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001707 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1708 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001709 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001710 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001711
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001712 return QualType(New, 0);
1713}
1714
1715/// getRValueReferenceType - Return the uniqued reference to the type for an
1716/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001717QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001718 // Unique pointers, to guarantee there is only one pointer of a particular
1719 // structure.
1720 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001721 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001722
1723 void *InsertPos = 0;
1724 if (RValueReferenceType *RT =
1725 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1726 return QualType(RT, 0);
1727
John McCallfc93cf92009-10-22 22:37:11 +00001728 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1729
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001730 // If the referencee type isn't canonical, this won't be a canonical type
1731 // either, so fill in the canonical type field.
1732 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001733 if (InnerRef || !T.isCanonical()) {
1734 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1735 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001736
1737 // Get the new insert position for the node we care about.
1738 RValueReferenceType *NewIP =
1739 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001740 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001741 }
1742
John McCall90d1c2d2009-09-24 23:30:46 +00001743 RValueReferenceType *New
1744 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001745 Types.push_back(New);
1746 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001747 return QualType(New, 0);
1748}
1749
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001750/// getMemberPointerType - Return the uniqued reference to the type for a
1751/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001752QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001753 // Unique pointers, to guarantee there is only one pointer of a particular
1754 // structure.
1755 llvm::FoldingSetNodeID ID;
1756 MemberPointerType::Profile(ID, T, Cls);
1757
1758 void *InsertPos = 0;
1759 if (MemberPointerType *PT =
1760 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1761 return QualType(PT, 0);
1762
1763 // If the pointee or class type isn't canonical, this won't be a canonical
1764 // type either, so fill in the canonical type field.
1765 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001766 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001767 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1768
1769 // Get the new insert position for the node we care about.
1770 MemberPointerType *NewIP =
1771 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001772 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001773 }
John McCall90d1c2d2009-09-24 23:30:46 +00001774 MemberPointerType *New
1775 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001776 Types.push_back(New);
1777 MemberPointerTypes.InsertNode(New, InsertPos);
1778 return QualType(New, 0);
1779}
1780
Mike Stump11289f42009-09-09 15:08:12 +00001781/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001782/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001783QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001784 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001785 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001786 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001787 assert((EltTy->isDependentType() ||
1788 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001789 "Constant array of VLAs is illegal!");
1790
Chris Lattnere2df3f92009-05-13 04:12:56 +00001791 // Convert the array size into a canonical width matching the pointer size for
1792 // the target.
1793 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001794 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001795 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00001796
Chris Lattner23b7eb62007-06-15 23:05:46 +00001797 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001798 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001799
Chris Lattner36f8e652007-01-27 08:31:04 +00001800 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001801 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001802 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001803 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001804
John McCall33ddac02011-01-19 10:06:00 +00001805 // If the element type isn't canonical or has qualifiers, this won't
1806 // be a canonical type either, so fill in the canonical type field.
1807 QualType Canon;
1808 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1809 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00001810 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001811 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00001812 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001813
Chris Lattner36f8e652007-01-27 08:31:04 +00001814 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001815 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001816 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001817 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001818 }
Mike Stump11289f42009-09-09 15:08:12 +00001819
John McCall90d1c2d2009-09-24 23:30:46 +00001820 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001821 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001822 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001823 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001824 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001825}
1826
John McCall06549462011-01-18 08:40:38 +00001827/// getVariableArrayDecayedType - Turns the given type, which may be
1828/// variably-modified, into the corresponding type with all the known
1829/// sizes replaced with [*].
1830QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1831 // Vastly most common case.
1832 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001833
John McCall06549462011-01-18 08:40:38 +00001834 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001835
John McCall06549462011-01-18 08:40:38 +00001836 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00001837 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00001838 switch (ty->getTypeClass()) {
1839#define TYPE(Class, Base)
1840#define ABSTRACT_TYPE(Class, Base)
1841#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1842#include "clang/AST/TypeNodes.def"
1843 llvm_unreachable("didn't desugar past all non-canonical types?");
1844
1845 // These types should never be variably-modified.
1846 case Type::Builtin:
1847 case Type::Complex:
1848 case Type::Vector:
1849 case Type::ExtVector:
1850 case Type::DependentSizedExtVector:
1851 case Type::ObjCObject:
1852 case Type::ObjCInterface:
1853 case Type::ObjCObjectPointer:
1854 case Type::Record:
1855 case Type::Enum:
1856 case Type::UnresolvedUsing:
1857 case Type::TypeOfExpr:
1858 case Type::TypeOf:
1859 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00001860 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00001861 case Type::DependentName:
1862 case Type::InjectedClassName:
1863 case Type::TemplateSpecialization:
1864 case Type::DependentTemplateSpecialization:
1865 case Type::TemplateTypeParm:
1866 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00001867 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00001868 case Type::PackExpansion:
1869 llvm_unreachable("type should never be variably-modified");
1870
1871 // These types can be variably-modified but should never need to
1872 // further decay.
1873 case Type::FunctionNoProto:
1874 case Type::FunctionProto:
1875 case Type::BlockPointer:
1876 case Type::MemberPointer:
1877 return type;
1878
1879 // These types can be variably-modified. All these modifications
1880 // preserve structure except as noted by comments.
1881 // TODO: if we ever care about optimizing VLAs, there are no-op
1882 // optimizations available here.
1883 case Type::Pointer:
1884 result = getPointerType(getVariableArrayDecayedType(
1885 cast<PointerType>(ty)->getPointeeType()));
1886 break;
1887
1888 case Type::LValueReference: {
1889 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1890 result = getLValueReferenceType(
1891 getVariableArrayDecayedType(lv->getPointeeType()),
1892 lv->isSpelledAsLValue());
1893 break;
1894 }
1895
1896 case Type::RValueReference: {
1897 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1898 result = getRValueReferenceType(
1899 getVariableArrayDecayedType(lv->getPointeeType()));
1900 break;
1901 }
1902
Eli Friedman0dfb8892011-10-06 23:00:33 +00001903 case Type::Atomic: {
1904 const AtomicType *at = cast<AtomicType>(ty);
1905 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1906 break;
1907 }
1908
John McCall06549462011-01-18 08:40:38 +00001909 case Type::ConstantArray: {
1910 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1911 result = getConstantArrayType(
1912 getVariableArrayDecayedType(cat->getElementType()),
1913 cat->getSize(),
1914 cat->getSizeModifier(),
1915 cat->getIndexTypeCVRQualifiers());
1916 break;
1917 }
1918
1919 case Type::DependentSizedArray: {
1920 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1921 result = getDependentSizedArrayType(
1922 getVariableArrayDecayedType(dat->getElementType()),
1923 dat->getSizeExpr(),
1924 dat->getSizeModifier(),
1925 dat->getIndexTypeCVRQualifiers(),
1926 dat->getBracketsRange());
1927 break;
1928 }
1929
1930 // Turn incomplete types into [*] types.
1931 case Type::IncompleteArray: {
1932 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1933 result = getVariableArrayType(
1934 getVariableArrayDecayedType(iat->getElementType()),
1935 /*size*/ 0,
1936 ArrayType::Normal,
1937 iat->getIndexTypeCVRQualifiers(),
1938 SourceRange());
1939 break;
1940 }
1941
1942 // Turn VLA types into [*] types.
1943 case Type::VariableArray: {
1944 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1945 result = getVariableArrayType(
1946 getVariableArrayDecayedType(vat->getElementType()),
1947 /*size*/ 0,
1948 ArrayType::Star,
1949 vat->getIndexTypeCVRQualifiers(),
1950 vat->getBracketsRange());
1951 break;
1952 }
1953 }
1954
1955 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00001956 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00001957}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001958
Steve Naroffcadebd02007-08-30 18:14:25 +00001959/// getVariableArrayType - Returns a non-unique reference to the type for a
1960/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001961QualType ASTContext::getVariableArrayType(QualType EltTy,
1962 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001963 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001964 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001965 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001966 // Since we don't unique expressions, it isn't possible to unique VLA's
1967 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00001968 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001969
John McCall33ddac02011-01-19 10:06:00 +00001970 // Be sure to pull qualifiers off the element type.
1971 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1972 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00001973 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001974 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00001975 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001976 }
1977
John McCall90d1c2d2009-09-24 23:30:46 +00001978 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001979 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001980
1981 VariableArrayTypes.push_back(New);
1982 Types.push_back(New);
1983 return QualType(New, 0);
1984}
1985
Douglas Gregor4619e432008-12-05 23:32:09 +00001986/// getDependentSizedArrayType - Returns a non-unique reference to
1987/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001988/// type.
John McCall33ddac02011-01-19 10:06:00 +00001989QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1990 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00001991 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001992 unsigned elementTypeQuals,
1993 SourceRange brackets) const {
1994 assert((!numElements || numElements->isTypeDependent() ||
1995 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001996 "Size must be type- or value-dependent!");
1997
John McCall33ddac02011-01-19 10:06:00 +00001998 // Dependently-sized array types that do not have a specified number
1999 // of elements will have their sizes deduced from a dependent
2000 // initializer. We do no canonicalization here at all, which is okay
2001 // because they can't be used in most locations.
2002 if (!numElements) {
2003 DependentSizedArrayType *newType
2004 = new (*this, TypeAlignment)
2005 DependentSizedArrayType(*this, elementType, QualType(),
2006 numElements, ASM, elementTypeQuals,
2007 brackets);
2008 Types.push_back(newType);
2009 return QualType(newType, 0);
2010 }
2011
2012 // Otherwise, we actually build a new type every time, but we
2013 // also build a canonical type.
2014
2015 SplitQualType canonElementType = getCanonicalType(elementType).split();
2016
2017 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002018 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002019 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002020 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002021 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002022
John McCall33ddac02011-01-19 10:06:00 +00002023 // Look for an existing type with these properties.
2024 DependentSizedArrayType *canonTy =
2025 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002026
John McCall33ddac02011-01-19 10:06:00 +00002027 // If we don't have one, build one.
2028 if (!canonTy) {
2029 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002030 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002031 QualType(), numElements, ASM, elementTypeQuals,
2032 brackets);
2033 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2034 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002035 }
2036
John McCall33ddac02011-01-19 10:06:00 +00002037 // Apply qualifiers from the element type to the array.
2038 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002039 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002040
John McCall33ddac02011-01-19 10:06:00 +00002041 // If we didn't need extra canonicalization for the element type,
2042 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002043 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002044 return canon;
2045
2046 // Otherwise, we need to build a type which follows the spelling
2047 // of the element type.
2048 DependentSizedArrayType *sugaredType
2049 = new (*this, TypeAlignment)
2050 DependentSizedArrayType(*this, elementType, canon, numElements,
2051 ASM, elementTypeQuals, brackets);
2052 Types.push_back(sugaredType);
2053 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002054}
2055
John McCall33ddac02011-01-19 10:06:00 +00002056QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002057 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002058 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002059 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002060 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002061
John McCall33ddac02011-01-19 10:06:00 +00002062 void *insertPos = 0;
2063 if (IncompleteArrayType *iat =
2064 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2065 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002066
2067 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002068 // either, so fill in the canonical type field. We also have to pull
2069 // qualifiers off the element type.
2070 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002071
John McCall33ddac02011-01-19 10:06:00 +00002072 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2073 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002074 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002075 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002076 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002077
2078 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002079 IncompleteArrayType *existing =
2080 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2081 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002082 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002083
John McCall33ddac02011-01-19 10:06:00 +00002084 IncompleteArrayType *newType = new (*this, TypeAlignment)
2085 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002086
John McCall33ddac02011-01-19 10:06:00 +00002087 IncompleteArrayTypes.InsertNode(newType, insertPos);
2088 Types.push_back(newType);
2089 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002090}
2091
Steve Naroff91fcddb2007-07-18 18:00:27 +00002092/// getVectorType - Return the unique reference to a vector type of
2093/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002094QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002095 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002096 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002097
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002098 // Check if we've already instantiated a vector of this type.
2099 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002100 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002101
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002102 void *InsertPos = 0;
2103 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2104 return QualType(VTP, 0);
2105
2106 // If the element type isn't canonical, this won't be a canonical type either,
2107 // so fill in the canonical type field.
2108 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002109 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002110 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002111
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002112 // Get the new insert position for the node we care about.
2113 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002114 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002115 }
John McCall90d1c2d2009-09-24 23:30:46 +00002116 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002117 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002118 VectorTypes.InsertNode(New, InsertPos);
2119 Types.push_back(New);
2120 return QualType(New, 0);
2121}
2122
Nate Begemance4d7fc2008-04-18 23:10:10 +00002123/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002124/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002125QualType
2126ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002127 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002128
Steve Naroff91fcddb2007-07-18 18:00:27 +00002129 // Check if we've already instantiated a vector of this type.
2130 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002131 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002132 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002133 void *InsertPos = 0;
2134 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2135 return QualType(VTP, 0);
2136
2137 // If the element type isn't canonical, this won't be a canonical type either,
2138 // so fill in the canonical type field.
2139 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002140 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002141 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002142
Steve Naroff91fcddb2007-07-18 18:00:27 +00002143 // Get the new insert position for the node we care about.
2144 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002145 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002146 }
John McCall90d1c2d2009-09-24 23:30:46 +00002147 ExtVectorType *New = new (*this, TypeAlignment)
2148 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002149 VectorTypes.InsertNode(New, InsertPos);
2150 Types.push_back(New);
2151 return QualType(New, 0);
2152}
2153
Jay Foad39c79802011-01-12 09:06:06 +00002154QualType
2155ASTContext::getDependentSizedExtVectorType(QualType vecType,
2156 Expr *SizeExpr,
2157 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002158 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002159 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002160 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002161
Douglas Gregor352169a2009-07-31 03:54:25 +00002162 void *InsertPos = 0;
2163 DependentSizedExtVectorType *Canon
2164 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2165 DependentSizedExtVectorType *New;
2166 if (Canon) {
2167 // We already have a canonical version of this array type; use it as
2168 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002169 New = new (*this, TypeAlignment)
2170 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2171 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002172 } else {
2173 QualType CanonVecTy = getCanonicalType(vecType);
2174 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002175 New = new (*this, TypeAlignment)
2176 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2177 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002178
2179 DependentSizedExtVectorType *CanonCheck
2180 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2181 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2182 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002183 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2184 } else {
2185 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2186 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002187 New = new (*this, TypeAlignment)
2188 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002189 }
2190 }
Mike Stump11289f42009-09-09 15:08:12 +00002191
Douglas Gregor758a8692009-06-17 21:51:59 +00002192 Types.push_back(New);
2193 return QualType(New, 0);
2194}
2195
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002196/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002197///
Jay Foad39c79802011-01-12 09:06:06 +00002198QualType
2199ASTContext::getFunctionNoProtoType(QualType ResultTy,
2200 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002201 const CallingConv DefaultCC = Info.getCC();
2202 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2203 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002204 // Unique functions, to guarantee there is only one function of a particular
2205 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002206 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002207 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002208
Chris Lattner47955de2007-01-27 08:37:20 +00002209 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002210 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002211 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002212 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002213
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002214 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002215 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002216 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002217 Canonical =
2218 getFunctionNoProtoType(getCanonicalType(ResultTy),
2219 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002220
Chris Lattner47955de2007-01-27 08:37:20 +00002221 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002222 FunctionNoProtoType *NewIP =
2223 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002224 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002225 }
Mike Stump11289f42009-09-09 15:08:12 +00002226
Roman Divacky65b88cd2011-03-01 17:40:53 +00002227 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002228 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002229 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002230 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002231 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002232 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002233}
2234
2235/// getFunctionType - Return a normal function type with a typed argument
2236/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002237QualType
2238ASTContext::getFunctionType(QualType ResultTy,
2239 const QualType *ArgArray, unsigned NumArgs,
2240 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002241 // Unique functions, to guarantee there is only one function of a particular
2242 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002243 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002244 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002245
2246 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002247 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002248 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002249 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002250
2251 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002252 bool isCanonical =
2253 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2254 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002255 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002256 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002257 isCanonical = false;
2258
Roman Divacky65b88cd2011-03-01 17:40:53 +00002259 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2260 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2261 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002262
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002263 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002264 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002265 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002266 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002267 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002268 CanonicalArgs.reserve(NumArgs);
2269 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002270 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002271
John McCalldb40c7f2010-12-14 08:05:40 +00002272 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002273 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002274 CanonicalEPI.ExceptionSpecType = EST_None;
2275 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002276 CanonicalEPI.ExtInfo
2277 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2278
Chris Lattner76a00cf2008-04-06 22:59:24 +00002279 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002280 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002281 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002282
Chris Lattnerfd4de792007-01-27 01:15:32 +00002283 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002284 FunctionProtoType *NewIP =
2285 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002286 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002287 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002288
John McCall31168b02011-06-15 23:02:42 +00002289 // FunctionProtoType objects are allocated with extra bytes after
2290 // them for three variable size arrays at the end:
2291 // - parameter types
2292 // - exception types
2293 // - consumed-arguments flags
2294 // Instead of the exception types, there could be a noexcept
2295 // expression.
John McCalldb40c7f2010-12-14 08:05:40 +00002296 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002297 NumArgs * sizeof(QualType);
2298 if (EPI.ExceptionSpecType == EST_Dynamic)
2299 Size += EPI.NumExceptions * sizeof(QualType);
2300 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002301 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002302 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002303 Size += 2 * sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002304 }
John McCall31168b02011-06-15 23:02:42 +00002305 if (EPI.ConsumedArguments)
2306 Size += NumArgs * sizeof(bool);
2307
John McCalldb40c7f2010-12-14 08:05:40 +00002308 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002309 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2310 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002311 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002312 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002313 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002314 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002315}
Chris Lattneref51c202006-11-10 07:17:23 +00002316
John McCalle78aac42010-03-10 03:28:59 +00002317#ifndef NDEBUG
2318static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2319 if (!isa<CXXRecordDecl>(D)) return false;
2320 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2321 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2322 return true;
2323 if (RD->getDescribedClassTemplate() &&
2324 !isa<ClassTemplateSpecializationDecl>(RD))
2325 return true;
2326 return false;
2327}
2328#endif
2329
2330/// getInjectedClassNameType - Return the unique reference to the
2331/// injected class name type for the specified templated declaration.
2332QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002333 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002334 assert(NeedsInjectedClassNameType(Decl));
2335 if (Decl->TypeForDecl) {
2336 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002337 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002338 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2339 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2340 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2341 } else {
John McCall424cec92011-01-19 06:33:43 +00002342 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002343 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002344 Decl->TypeForDecl = newType;
2345 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002346 }
2347 return QualType(Decl->TypeForDecl, 0);
2348}
2349
Douglas Gregor83a586e2008-04-13 21:07:44 +00002350/// getTypeDeclType - Return the unique reference to the type for the
2351/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002352QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002353 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002354 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002355
Richard Smithdda56e42011-04-15 14:24:37 +00002356 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002357 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002358
John McCall96f0b5f2010-03-10 06:48:02 +00002359 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2360 "Template type parameter types are always available.");
2361
John McCall81e38502010-02-16 03:57:14 +00002362 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002363 assert(!Record->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002364 "struct/union has previous declaration");
2365 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002366 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002367 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002368 assert(!Enum->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002369 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002370 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002371 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002372 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002373 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2374 Decl->TypeForDecl = newType;
2375 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002376 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002377 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002378
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002379 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002380}
2381
Chris Lattner32d920b2007-01-26 02:01:53 +00002382/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002383/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002384QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002385ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2386 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002387 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002388
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002389 if (Canonical.isNull())
2390 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002391 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002392 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002393 Decl->TypeForDecl = newType;
2394 Types.push_back(newType);
2395 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002396}
2397
Jay Foad39c79802011-01-12 09:06:06 +00002398QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002399 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2400
Douglas Gregorec9fd132012-01-14 16:38:05 +00002401 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002402 if (PrevDecl->TypeForDecl)
2403 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2404
John McCall424cec92011-01-19 06:33:43 +00002405 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2406 Decl->TypeForDecl = newType;
2407 Types.push_back(newType);
2408 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002409}
2410
Jay Foad39c79802011-01-12 09:06:06 +00002411QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002412 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2413
Douglas Gregorec9fd132012-01-14 16:38:05 +00002414 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002415 if (PrevDecl->TypeForDecl)
2416 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2417
John McCall424cec92011-01-19 06:33:43 +00002418 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2419 Decl->TypeForDecl = newType;
2420 Types.push_back(newType);
2421 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002422}
2423
John McCall81904512011-01-06 01:58:22 +00002424QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2425 QualType modifiedType,
2426 QualType equivalentType) {
2427 llvm::FoldingSetNodeID id;
2428 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2429
2430 void *insertPos = 0;
2431 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2432 if (type) return QualType(type, 0);
2433
2434 QualType canon = getCanonicalType(equivalentType);
2435 type = new (*this, TypeAlignment)
2436 AttributedType(canon, attrKind, modifiedType, equivalentType);
2437
2438 Types.push_back(type);
2439 AttributedTypes.InsertNode(type, insertPos);
2440
2441 return QualType(type, 0);
2442}
2443
2444
John McCallcebee162009-10-18 09:09:24 +00002445/// \brief Retrieve a substitution-result type.
2446QualType
2447ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002448 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002449 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002450 && "replacement types must always be canonical");
2451
2452 llvm::FoldingSetNodeID ID;
2453 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2454 void *InsertPos = 0;
2455 SubstTemplateTypeParmType *SubstParm
2456 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2457
2458 if (!SubstParm) {
2459 SubstParm = new (*this, TypeAlignment)
2460 SubstTemplateTypeParmType(Parm, Replacement);
2461 Types.push_back(SubstParm);
2462 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2463 }
2464
2465 return QualType(SubstParm, 0);
2466}
2467
Douglas Gregorada4b792011-01-14 02:55:32 +00002468/// \brief Retrieve a
2469QualType ASTContext::getSubstTemplateTypeParmPackType(
2470 const TemplateTypeParmType *Parm,
2471 const TemplateArgument &ArgPack) {
2472#ifndef NDEBUG
2473 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2474 PEnd = ArgPack.pack_end();
2475 P != PEnd; ++P) {
2476 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2477 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2478 }
2479#endif
2480
2481 llvm::FoldingSetNodeID ID;
2482 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2483 void *InsertPos = 0;
2484 if (SubstTemplateTypeParmPackType *SubstParm
2485 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2486 return QualType(SubstParm, 0);
2487
2488 QualType Canon;
2489 if (!Parm->isCanonicalUnqualified()) {
2490 Canon = getCanonicalType(QualType(Parm, 0));
2491 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2492 ArgPack);
2493 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2494 }
2495
2496 SubstTemplateTypeParmPackType *SubstParm
2497 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2498 ArgPack);
2499 Types.push_back(SubstParm);
2500 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2501 return QualType(SubstParm, 0);
2502}
2503
Douglas Gregoreff93e02009-02-05 23:33:38 +00002504/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002505/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002506/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002507QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002508 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002509 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002510 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002511 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002512 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002513 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002514 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2515
2516 if (TypeParm)
2517 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002518
Chandler Carruth08836322011-05-01 00:51:33 +00002519 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002520 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002521 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002522
2523 TemplateTypeParmType *TypeCheck
2524 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2525 assert(!TypeCheck && "Template type parameter canonical type broken");
2526 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002527 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002528 TypeParm = new (*this, TypeAlignment)
2529 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002530
2531 Types.push_back(TypeParm);
2532 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2533
2534 return QualType(TypeParm, 0);
2535}
2536
John McCalle78aac42010-03-10 03:28:59 +00002537TypeSourceInfo *
2538ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2539 SourceLocation NameLoc,
2540 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002541 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002542 assert(!Name.getAsDependentTemplateName() &&
2543 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002544 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002545
2546 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2547 TemplateSpecializationTypeLoc TL
2548 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002549 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00002550 TL.setTemplateNameLoc(NameLoc);
2551 TL.setLAngleLoc(Args.getLAngleLoc());
2552 TL.setRAngleLoc(Args.getRAngleLoc());
2553 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2554 TL.setArgLocInfo(i, Args[i].getLocInfo());
2555 return DI;
2556}
2557
Mike Stump11289f42009-09-09 15:08:12 +00002558QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002559ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002560 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002561 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002562 assert(!Template.getAsDependentTemplateName() &&
2563 "No dependent template names here!");
2564
John McCall6b51f282009-11-23 01:53:49 +00002565 unsigned NumArgs = Args.size();
2566
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002567 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002568 ArgVec.reserve(NumArgs);
2569 for (unsigned i = 0; i != NumArgs; ++i)
2570 ArgVec.push_back(Args[i].getArgument());
2571
John McCall2408e322010-04-27 00:57:59 +00002572 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002573 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002574}
2575
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002576#ifndef NDEBUG
2577static bool hasAnyPackExpansions(const TemplateArgument *Args,
2578 unsigned NumArgs) {
2579 for (unsigned I = 0; I != NumArgs; ++I)
2580 if (Args[I].isPackExpansion())
2581 return true;
2582
2583 return true;
2584}
2585#endif
2586
John McCall0ad16662009-10-29 08:12:44 +00002587QualType
2588ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002589 const TemplateArgument *Args,
2590 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002591 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002592 assert(!Template.getAsDependentTemplateName() &&
2593 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002594 // Look through qualified template names.
2595 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2596 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002597
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002598 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00002599 Template.getAsTemplateDecl() &&
2600 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00002601 QualType CanonType;
2602 if (!Underlying.isNull())
2603 CanonType = getCanonicalType(Underlying);
2604 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002605 // We can get here with an alias template when the specialization contains
2606 // a pack expansion that does not match up with a parameter pack.
2607 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2608 "Caller must compute aliased type");
2609 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00002610 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2611 NumArgs);
2612 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002613
Douglas Gregora8e02e72009-07-28 23:00:59 +00002614 // Allocate the (non-canonical) template specialization type, but don't
2615 // try to unique it: these types typically have location information that
2616 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002617 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2618 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002619 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002620 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002621 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002622 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2623 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002624
Douglas Gregor8bf42052009-02-09 18:46:07 +00002625 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002626 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002627}
2628
Mike Stump11289f42009-09-09 15:08:12 +00002629QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002630ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2631 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002632 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002633 assert(!Template.getAsDependentTemplateName() &&
2634 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002635
Douglas Gregore29139c2011-03-03 17:04:51 +00002636 // Look through qualified template names.
2637 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2638 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002639
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002640 // Build the canonical template specialization type.
2641 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002642 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002643 CanonArgs.reserve(NumArgs);
2644 for (unsigned I = 0; I != NumArgs; ++I)
2645 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2646
2647 // Determine whether this canonical template specialization type already
2648 // exists.
2649 llvm::FoldingSetNodeID ID;
2650 TemplateSpecializationType::Profile(ID, CanonTemplate,
2651 CanonArgs.data(), NumArgs, *this);
2652
2653 void *InsertPos = 0;
2654 TemplateSpecializationType *Spec
2655 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2656
2657 if (!Spec) {
2658 // Allocate a new canonical template specialization type.
2659 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2660 sizeof(TemplateArgument) * NumArgs),
2661 TypeAlignment);
2662 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2663 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002664 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002665 Types.push_back(Spec);
2666 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2667 }
2668
2669 assert(Spec->isDependentType() &&
2670 "Non-dependent template-id type must have a canonical type");
2671 return QualType(Spec, 0);
2672}
2673
2674QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002675ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2676 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002677 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002678 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002679 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002680
2681 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002682 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002683 if (T)
2684 return QualType(T, 0);
2685
Douglas Gregorc42075a2010-02-04 18:10:26 +00002686 QualType Canon = NamedType;
2687 if (!Canon.isCanonical()) {
2688 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002689 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2690 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002691 (void)CheckT;
2692 }
2693
Abramo Bagnara6150c882010-05-11 21:36:43 +00002694 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002695 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002696 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002697 return QualType(T, 0);
2698}
2699
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002700QualType
Jay Foad39c79802011-01-12 09:06:06 +00002701ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002702 llvm::FoldingSetNodeID ID;
2703 ParenType::Profile(ID, InnerType);
2704
2705 void *InsertPos = 0;
2706 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2707 if (T)
2708 return QualType(T, 0);
2709
2710 QualType Canon = InnerType;
2711 if (!Canon.isCanonical()) {
2712 Canon = getCanonicalType(InnerType);
2713 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2714 assert(!CheckT && "Paren canonical type broken");
2715 (void)CheckT;
2716 }
2717
2718 T = new (*this) ParenType(InnerType, Canon);
2719 Types.push_back(T);
2720 ParenTypes.InsertNode(T, InsertPos);
2721 return QualType(T, 0);
2722}
2723
Douglas Gregor02085352010-03-31 20:19:30 +00002724QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2725 NestedNameSpecifier *NNS,
2726 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002727 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002728 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2729
2730 if (Canon.isNull()) {
2731 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002732 ElaboratedTypeKeyword CanonKeyword = Keyword;
2733 if (Keyword == ETK_None)
2734 CanonKeyword = ETK_Typename;
2735
2736 if (CanonNNS != NNS || CanonKeyword != Keyword)
2737 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002738 }
2739
2740 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002741 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002742
2743 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002744 DependentNameType *T
2745 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002746 if (T)
2747 return QualType(T, 0);
2748
Douglas Gregor02085352010-03-31 20:19:30 +00002749 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002750 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002751 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002752 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002753}
2754
Mike Stump11289f42009-09-09 15:08:12 +00002755QualType
John McCallc392f372010-06-11 00:33:02 +00002756ASTContext::getDependentTemplateSpecializationType(
2757 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002758 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002759 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002760 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002761 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002762 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00002763 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2764 ArgCopy.push_back(Args[I].getArgument());
2765 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2766 ArgCopy.size(),
2767 ArgCopy.data());
2768}
2769
2770QualType
2771ASTContext::getDependentTemplateSpecializationType(
2772 ElaboratedTypeKeyword Keyword,
2773 NestedNameSpecifier *NNS,
2774 const IdentifierInfo *Name,
2775 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002776 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00002777 assert((!NNS || NNS->isDependent()) &&
2778 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00002779
Douglas Gregorc42075a2010-02-04 18:10:26 +00002780 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002781 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2782 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002783
2784 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002785 DependentTemplateSpecializationType *T
2786 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002787 if (T)
2788 return QualType(T, 0);
2789
John McCallc392f372010-06-11 00:33:02 +00002790 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002791
John McCallc392f372010-06-11 00:33:02 +00002792 ElaboratedTypeKeyword CanonKeyword = Keyword;
2793 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2794
2795 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002796 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00002797 for (unsigned I = 0; I != NumArgs; ++I) {
2798 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2799 if (!CanonArgs[I].structurallyEquals(Args[I]))
2800 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002801 }
2802
John McCallc392f372010-06-11 00:33:02 +00002803 QualType Canon;
2804 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2805 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2806 Name, NumArgs,
2807 CanonArgs.data());
2808
2809 // Find the insert position again.
2810 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2811 }
2812
2813 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2814 sizeof(TemplateArgument) * NumArgs),
2815 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002816 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002817 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002818 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002819 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002820 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002821}
2822
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002823QualType ASTContext::getPackExpansionType(QualType Pattern,
2824 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002825 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002826 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002827
2828 assert(Pattern->containsUnexpandedParameterPack() &&
2829 "Pack expansions must expand one or more parameter packs");
2830 void *InsertPos = 0;
2831 PackExpansionType *T
2832 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2833 if (T)
2834 return QualType(T, 0);
2835
2836 QualType Canon;
2837 if (!Pattern.isCanonical()) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002838 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002839
2840 // Find the insert position again.
2841 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2842 }
2843
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002844 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002845 Types.push_back(T);
2846 PackExpansionTypes.InsertNode(T, InsertPos);
2847 return QualType(T, 0);
2848}
2849
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002850/// CmpProtocolNames - Comparison predicate for sorting protocols
2851/// alphabetically.
2852static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2853 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002854 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002855}
2856
John McCall8b07ec22010-05-15 11:32:37 +00002857static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002858 unsigned NumProtocols) {
2859 if (NumProtocols == 0) return true;
2860
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002861 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
2862 return false;
2863
John McCallfc93cf92009-10-22 22:37:11 +00002864 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002865 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
2866 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00002867 return false;
2868 return true;
2869}
2870
2871static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002872 unsigned &NumProtocols) {
2873 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002874
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002875 // Sort protocols, keyed by name.
2876 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2877
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002878 // Canonicalize.
2879 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
2880 Protocols[I] = Protocols[I]->getCanonicalDecl();
2881
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002882 // Remove duplicates.
2883 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2884 NumProtocols = ProtocolsEnd-Protocols;
2885}
2886
John McCall8b07ec22010-05-15 11:32:37 +00002887QualType ASTContext::getObjCObjectType(QualType BaseType,
2888 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002889 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002890 // If the base type is an interface and there aren't any protocols
2891 // to add, then the interface type will do just fine.
2892 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2893 return BaseType;
2894
2895 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002896 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002897 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002898 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002899 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2900 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002901
John McCall8b07ec22010-05-15 11:32:37 +00002902 // Build the canonical type, which has the canonical base type and
2903 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002904 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002905 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2906 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2907 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002908 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002909 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002910 unsigned UniqueCount = NumProtocols;
2911
John McCallfc93cf92009-10-22 22:37:11 +00002912 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002913 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2914 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002915 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002916 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2917 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002918 }
2919
2920 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002921 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2922 }
2923
2924 unsigned Size = sizeof(ObjCObjectTypeImpl);
2925 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2926 void *Mem = Allocate(Size, TypeAlignment);
2927 ObjCObjectTypeImpl *T =
2928 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2929
2930 Types.push_back(T);
2931 ObjCObjectTypes.InsertNode(T, InsertPos);
2932 return QualType(T, 0);
2933}
2934
2935/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2936/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00002937QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00002938 llvm::FoldingSetNodeID ID;
2939 ObjCObjectPointerType::Profile(ID, ObjectT);
2940
2941 void *InsertPos = 0;
2942 if (ObjCObjectPointerType *QT =
2943 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2944 return QualType(QT, 0);
2945
2946 // Find the canonical object type.
2947 QualType Canonical;
2948 if (!ObjectT.isCanonical()) {
2949 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2950
2951 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002952 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2953 }
2954
Douglas Gregorf85bee62010-02-08 22:59:26 +00002955 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002956 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2957 ObjCObjectPointerType *QType =
2958 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002959
Steve Narofffb4330f2009-06-17 22:40:22 +00002960 Types.push_back(QType);
2961 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002962 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002963}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002964
Douglas Gregor1c283312010-08-11 12:19:30 +00002965/// getObjCInterfaceType - Return the unique reference to the type for the
2966/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00002967QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
2968 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00002969 if (Decl->TypeForDecl)
2970 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002971
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00002972 if (PrevDecl) {
2973 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
2974 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2975 return QualType(PrevDecl->TypeForDecl, 0);
2976 }
2977
Douglas Gregor7671e532011-12-16 16:34:57 +00002978 // Prefer the definition, if there is one.
2979 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
2980 Decl = Def;
2981
Douglas Gregor1c283312010-08-11 12:19:30 +00002982 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2983 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2984 Decl->TypeForDecl = T;
2985 Types.push_back(T);
2986 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002987}
2988
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002989/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2990/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002991/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002992/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002993/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002994QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002995 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002996 if (tofExpr->isTypeDependent()) {
2997 llvm::FoldingSetNodeID ID;
2998 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002999
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003000 void *InsertPos = 0;
3001 DependentTypeOfExprType *Canon
3002 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3003 if (Canon) {
3004 // We already have a "canonical" version of an identical, dependent
3005 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003006 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003007 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003008 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003009 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003010 Canon
3011 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003012 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3013 toe = Canon;
3014 }
3015 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003016 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003017 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003018 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003019 Types.push_back(toe);
3020 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003021}
3022
Steve Naroffa773cd52007-08-01 18:02:17 +00003023/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3024/// TypeOfType AST's. The only motivation to unique these nodes would be
3025/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003026/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003027/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003028QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003029 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003030 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003031 Types.push_back(tot);
3032 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003033}
3034
Anders Carlssonad6bd352009-06-24 21:24:56 +00003035
Anders Carlsson81df7b82009-06-24 19:06:50 +00003036/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3037/// DecltypeType AST's. The only motivation to unique these nodes would be
3038/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003039/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003040/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003041QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003042 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003043
3044 // C++0x [temp.type]p2:
3045 // If an expression e involves a template parameter, decltype(e) denotes a
3046 // unique dependent type. Two such decltype-specifiers refer to the same
3047 // type only if their expressions are equivalent (14.5.6.1).
3048 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003049 llvm::FoldingSetNodeID ID;
3050 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003051
Douglas Gregora21f6c32009-07-30 23:36:40 +00003052 void *InsertPos = 0;
3053 DependentDecltypeType *Canon
3054 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3055 if (Canon) {
3056 // We already have a "canonical" version of an equivalent, dependent
3057 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003058 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003059 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003060 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003061 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003062 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003063 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3064 dt = Canon;
3065 }
3066 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003067 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3068 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003069 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003070 Types.push_back(dt);
3071 return QualType(dt, 0);
3072}
3073
Alexis Hunte852b102011-05-24 22:41:36 +00003074/// getUnaryTransformationType - We don't unique these, since the memory
3075/// savings are minimal and these are rare.
3076QualType ASTContext::getUnaryTransformType(QualType BaseType,
3077 QualType UnderlyingType,
3078 UnaryTransformType::UTTKind Kind)
3079 const {
3080 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003081 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3082 Kind,
3083 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003084 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003085 Types.push_back(Ty);
3086 return QualType(Ty, 0);
3087}
3088
Richard Smithb2bc2e62011-02-21 20:05:19 +00003089/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003090QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00003091 void *InsertPos = 0;
3092 if (!DeducedType.isNull()) {
3093 // Look in the folding set for an existing type.
3094 llvm::FoldingSetNodeID ID;
3095 AutoType::Profile(ID, DeducedType);
3096 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3097 return QualType(AT, 0);
3098 }
3099
3100 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3101 Types.push_back(AT);
3102 if (InsertPos)
3103 AutoTypes.InsertNode(AT, InsertPos);
3104 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003105}
3106
Eli Friedman0dfb8892011-10-06 23:00:33 +00003107/// getAtomicType - Return the uniqued reference to the atomic type for
3108/// the given value type.
3109QualType ASTContext::getAtomicType(QualType T) const {
3110 // Unique pointers, to guarantee there is only one pointer of a particular
3111 // structure.
3112 llvm::FoldingSetNodeID ID;
3113 AtomicType::Profile(ID, T);
3114
3115 void *InsertPos = 0;
3116 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3117 return QualType(AT, 0);
3118
3119 // If the atomic value type isn't canonical, this won't be a canonical type
3120 // either, so fill in the canonical type field.
3121 QualType Canonical;
3122 if (!T.isCanonical()) {
3123 Canonical = getAtomicType(getCanonicalType(T));
3124
3125 // Get the new insert position for the node we care about.
3126 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3127 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3128 }
3129 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3130 Types.push_back(New);
3131 AtomicTypes.InsertNode(New, InsertPos);
3132 return QualType(New, 0);
3133}
3134
Richard Smith02e85f32011-04-14 22:09:26 +00003135/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3136QualType ASTContext::getAutoDeductType() const {
3137 if (AutoDeductTy.isNull())
3138 AutoDeductTy = getAutoType(QualType());
3139 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3140 return AutoDeductTy;
3141}
3142
3143/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3144QualType ASTContext::getAutoRRefDeductType() const {
3145 if (AutoRRefDeductTy.isNull())
3146 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3147 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3148 return AutoRRefDeductTy;
3149}
3150
Chris Lattnerfb072462007-01-23 05:45:31 +00003151/// getTagDeclType - Return the unique reference to the type for the
3152/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003153QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003154 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003155 // FIXME: What is the design on getTagDeclType when it requires casting
3156 // away const? mutable?
3157 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003158}
3159
Mike Stump11289f42009-09-09 15:08:12 +00003160/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3161/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3162/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003163CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003164 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003165}
Chris Lattnerfb072462007-01-23 05:45:31 +00003166
Hans Wennborg27541db2011-10-27 08:29:09 +00003167/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3168CanQualType ASTContext::getIntMaxType() const {
3169 return getFromTargetType(Target->getIntMaxType());
3170}
3171
3172/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3173CanQualType ASTContext::getUIntMaxType() const {
3174 return getFromTargetType(Target->getUIntMaxType());
3175}
3176
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003177/// getSignedWCharType - Return the type of "signed wchar_t".
3178/// Used when in C++, as a GCC extension.
3179QualType ASTContext::getSignedWCharType() const {
3180 // FIXME: derive from "Target" ?
3181 return WCharTy;
3182}
3183
3184/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3185/// Used when in C++, as a GCC extension.
3186QualType ASTContext::getUnsignedWCharType() const {
3187 // FIXME: derive from "Target" ?
3188 return UnsignedIntTy;
3189}
3190
Hans Wennborg27541db2011-10-27 08:29:09 +00003191/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003192/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3193QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003194 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003195}
3196
Chris Lattnera21ad802008-04-02 05:18:44 +00003197//===----------------------------------------------------------------------===//
3198// Type Operators
3199//===----------------------------------------------------------------------===//
3200
Jay Foad39c79802011-01-12 09:06:06 +00003201CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003202 // Push qualifiers into arrays, and then discard any remaining
3203 // qualifiers.
3204 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003205 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003206 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003207 QualType Result;
3208 if (isa<ArrayType>(Ty)) {
3209 Result = getArrayDecayedType(QualType(Ty,0));
3210 } else if (isa<FunctionType>(Ty)) {
3211 Result = getPointerType(QualType(Ty, 0));
3212 } else {
3213 Result = QualType(Ty, 0);
3214 }
3215
3216 return CanQualType::CreateUnsafe(Result);
3217}
3218
John McCall6c9dd522011-01-18 07:41:22 +00003219QualType ASTContext::getUnqualifiedArrayType(QualType type,
3220 Qualifiers &quals) {
3221 SplitQualType splitType = type.getSplitUnqualifiedType();
3222
3223 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3224 // the unqualified desugared type and then drops it on the floor.
3225 // We then have to strip that sugar back off with
3226 // getUnqualifiedDesugaredType(), which is silly.
3227 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003228 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003229
3230 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003231 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003232 quals = splitType.Quals;
3233 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003234 }
3235
John McCall6c9dd522011-01-18 07:41:22 +00003236 // Otherwise, recurse on the array's element type.
3237 QualType elementType = AT->getElementType();
3238 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3239
3240 // If that didn't change the element type, AT has no qualifiers, so we
3241 // can just use the results in splitType.
3242 if (elementType == unqualElementType) {
3243 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003244 quals = splitType.Quals;
3245 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003246 }
3247
3248 // Otherwise, add in the qualifiers from the outermost type, then
3249 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003250 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003251
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003252 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003253 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003254 CAT->getSizeModifier(), 0);
3255 }
3256
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003257 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003258 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003259 }
3260
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003261 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003262 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003263 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003264 VAT->getSizeModifier(),
3265 VAT->getIndexTypeCVRQualifiers(),
3266 VAT->getBracketsRange());
3267 }
3268
3269 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003270 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003271 DSAT->getSizeModifier(), 0,
3272 SourceRange());
3273}
3274
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003275/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3276/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3277/// they point to and return true. If T1 and T2 aren't pointer types
3278/// or pointer-to-member types, or if they are not similar at this
3279/// level, returns false and leaves T1 and T2 unchanged. Top-level
3280/// qualifiers on T1 and T2 are ignored. This function will typically
3281/// be called in a loop that successively "unwraps" pointer and
3282/// pointer-to-member types to compare them at each level.
3283bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3284 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3285 *T2PtrType = T2->getAs<PointerType>();
3286 if (T1PtrType && T2PtrType) {
3287 T1 = T1PtrType->getPointeeType();
3288 T2 = T2PtrType->getPointeeType();
3289 return true;
3290 }
3291
3292 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3293 *T2MPType = T2->getAs<MemberPointerType>();
3294 if (T1MPType && T2MPType &&
3295 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3296 QualType(T2MPType->getClass(), 0))) {
3297 T1 = T1MPType->getPointeeType();
3298 T2 = T2MPType->getPointeeType();
3299 return true;
3300 }
3301
David Blaikiebbafb8a2012-03-11 07:00:24 +00003302 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003303 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3304 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3305 if (T1OPType && T2OPType) {
3306 T1 = T1OPType->getPointeeType();
3307 T2 = T2OPType->getPointeeType();
3308 return true;
3309 }
3310 }
3311
3312 // FIXME: Block pointers, too?
3313
3314 return false;
3315}
3316
Jay Foad39c79802011-01-12 09:06:06 +00003317DeclarationNameInfo
3318ASTContext::getNameForTemplate(TemplateName Name,
3319 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003320 switch (Name.getKind()) {
3321 case TemplateName::QualifiedTemplate:
3322 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003323 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003324 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3325 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003326
John McCalld9dfe3a2011-06-30 08:33:18 +00003327 case TemplateName::OverloadedTemplate: {
3328 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3329 // DNInfo work in progress: CHECKME: what about DNLoc?
3330 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3331 }
3332
3333 case TemplateName::DependentTemplate: {
3334 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003335 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003336 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003337 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3338 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003339 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003340 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3341 // DNInfo work in progress: FIXME: source locations?
3342 DeclarationNameLoc DNLoc;
3343 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3344 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3345 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003346 }
3347 }
3348
John McCalld9dfe3a2011-06-30 08:33:18 +00003349 case TemplateName::SubstTemplateTemplateParm: {
3350 SubstTemplateTemplateParmStorage *subst
3351 = Name.getAsSubstTemplateTemplateParm();
3352 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3353 NameLoc);
3354 }
3355
3356 case TemplateName::SubstTemplateTemplateParmPack: {
3357 SubstTemplateTemplateParmPackStorage *subst
3358 = Name.getAsSubstTemplateTemplateParmPack();
3359 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3360 NameLoc);
3361 }
3362 }
3363
3364 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003365}
3366
Jay Foad39c79802011-01-12 09:06:06 +00003367TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003368 switch (Name.getKind()) {
3369 case TemplateName::QualifiedTemplate:
3370 case TemplateName::Template: {
3371 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003372 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003373 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003374 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3375
3376 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003377 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003378 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003379
John McCalld9dfe3a2011-06-30 08:33:18 +00003380 case TemplateName::OverloadedTemplate:
3381 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003382
John McCalld9dfe3a2011-06-30 08:33:18 +00003383 case TemplateName::DependentTemplate: {
3384 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3385 assert(DTN && "Non-dependent template names must refer to template decls.");
3386 return DTN->CanonicalTemplateName;
3387 }
3388
3389 case TemplateName::SubstTemplateTemplateParm: {
3390 SubstTemplateTemplateParmStorage *subst
3391 = Name.getAsSubstTemplateTemplateParm();
3392 return getCanonicalTemplateName(subst->getReplacement());
3393 }
3394
3395 case TemplateName::SubstTemplateTemplateParmPack: {
3396 SubstTemplateTemplateParmPackStorage *subst
3397 = Name.getAsSubstTemplateTemplateParmPack();
3398 TemplateTemplateParmDecl *canonParameter
3399 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3400 TemplateArgument canonArgPack
3401 = getCanonicalTemplateArgument(subst->getArgumentPack());
3402 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3403 }
3404 }
3405
3406 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003407}
3408
Douglas Gregoradee3e32009-11-11 23:06:43 +00003409bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3410 X = getCanonicalTemplateName(X);
3411 Y = getCanonicalTemplateName(Y);
3412 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3413}
3414
Mike Stump11289f42009-09-09 15:08:12 +00003415TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003416ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003417 switch (Arg.getKind()) {
3418 case TemplateArgument::Null:
3419 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003420
Douglas Gregora8e02e72009-07-28 23:00:59 +00003421 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003422 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003423
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003424 case TemplateArgument::Declaration: {
3425 if (Decl *D = Arg.getAsDecl())
3426 return TemplateArgument(D->getCanonicalDecl());
3427 return TemplateArgument((Decl*)0);
3428 }
Mike Stump11289f42009-09-09 15:08:12 +00003429
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003430 case TemplateArgument::Template:
3431 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003432
3433 case TemplateArgument::TemplateExpansion:
3434 return TemplateArgument(getCanonicalTemplateName(
3435 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003436 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003437
Douglas Gregora8e02e72009-07-28 23:00:59 +00003438 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00003439 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003440
Douglas Gregora8e02e72009-07-28 23:00:59 +00003441 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003442 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003443
Douglas Gregora8e02e72009-07-28 23:00:59 +00003444 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003445 if (Arg.pack_size() == 0)
3446 return Arg;
3447
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003448 TemplateArgument *CanonArgs
3449 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003450 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003451 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003452 AEnd = Arg.pack_end();
3453 A != AEnd; (void)++A, ++Idx)
3454 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003455
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003456 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003457 }
3458 }
3459
3460 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003461 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003462}
3463
Douglas Gregor333489b2009-03-27 23:10:48 +00003464NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003465ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003466 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003467 return 0;
3468
3469 switch (NNS->getKind()) {
3470 case NestedNameSpecifier::Identifier:
3471 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003472 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003473 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3474 NNS->getAsIdentifier());
3475
3476 case NestedNameSpecifier::Namespace:
3477 // A namespace is canonical; build a nested-name-specifier with
3478 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003479 return NestedNameSpecifier::Create(*this, 0,
3480 NNS->getAsNamespace()->getOriginalNamespace());
3481
3482 case NestedNameSpecifier::NamespaceAlias:
3483 // A namespace is canonical; build a nested-name-specifier with
3484 // this namespace and no prefix.
3485 return NestedNameSpecifier::Create(*this, 0,
3486 NNS->getAsNamespaceAlias()->getNamespace()
3487 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003488
3489 case NestedNameSpecifier::TypeSpec:
3490 case NestedNameSpecifier::TypeSpecWithTemplate: {
3491 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003492
3493 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3494 // break it apart into its prefix and identifier, then reconsititute those
3495 // as the canonical nested-name-specifier. This is required to canonicalize
3496 // a dependent nested-name-specifier involving typedefs of dependent-name
3497 // types, e.g.,
3498 // typedef typename T::type T1;
3499 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00003500 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3501 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00003502 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003503
Eli Friedman5358a0a2012-03-03 04:09:56 +00003504 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3505 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3506 // first place?
John McCall33ddac02011-01-19 10:06:00 +00003507 return NestedNameSpecifier::Create(*this, 0, false,
3508 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003509 }
3510
3511 case NestedNameSpecifier::Global:
3512 // The global specifier is canonical and unique.
3513 return NNS;
3514 }
3515
David Blaikie8a40f702012-01-17 06:56:22 +00003516 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00003517}
3518
Chris Lattner7adf0762008-08-04 07:31:14 +00003519
Jay Foad39c79802011-01-12 09:06:06 +00003520const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003521 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003522 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003523 // Handle the common positive case fast.
3524 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3525 return AT;
3526 }
Mike Stump11289f42009-09-09 15:08:12 +00003527
John McCall8ccfcb52009-09-24 19:53:00 +00003528 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003529 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003530 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003531
John McCall8ccfcb52009-09-24 19:53:00 +00003532 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003533 // implements C99 6.7.3p8: "If the specification of an array type includes
3534 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003535
Chris Lattner7adf0762008-08-04 07:31:14 +00003536 // If we get here, we either have type qualifiers on the type, or we have
3537 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003538 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003539
John McCall33ddac02011-01-19 10:06:00 +00003540 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003541 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00003542
Chris Lattner7adf0762008-08-04 07:31:14 +00003543 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00003544 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00003545 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003546 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003547
Chris Lattner7adf0762008-08-04 07:31:14 +00003548 // Otherwise, we have an array and we have qualifiers on it. Push the
3549 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003550 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003551
Chris Lattner7adf0762008-08-04 07:31:14 +00003552 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3553 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3554 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003555 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003556 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3557 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3558 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003559 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003560
Mike Stump11289f42009-09-09 15:08:12 +00003561 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003562 = dyn_cast<DependentSizedArrayType>(ATy))
3563 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003564 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003565 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003566 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003567 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003568 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003569
Chris Lattner7adf0762008-08-04 07:31:14 +00003570 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003571 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003572 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003573 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003574 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003575 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003576}
3577
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003578QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003579 // C99 6.7.5.3p7:
3580 // A declaration of a parameter as "array of type" shall be
3581 // adjusted to "qualified pointer to type", where the type
3582 // qualifiers (if any) are those specified within the [ and ] of
3583 // the array type derivation.
3584 if (T->isArrayType())
3585 return getArrayDecayedType(T);
3586
3587 // C99 6.7.5.3p8:
3588 // A declaration of a parameter as "function returning type"
3589 // shall be adjusted to "pointer to function returning type", as
3590 // in 6.3.2.1.
3591 if (T->isFunctionType())
3592 return getPointerType(T);
3593
3594 return T;
3595}
3596
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003597QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003598 T = getVariableArrayDecayedType(T);
3599 T = getAdjustedParameterType(T);
3600 return T.getUnqualifiedType();
3601}
3602
Chris Lattnera21ad802008-04-02 05:18:44 +00003603/// getArrayDecayedType - Return the properly qualified result of decaying the
3604/// specified array type to a pointer. This operation is non-trivial when
3605/// handling typedefs etc. The canonical type of "T" must be an array type,
3606/// this returns a pointer to a properly qualified element of the array.
3607///
3608/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003609QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003610 // Get the element type with 'getAsArrayType' so that we don't lose any
3611 // typedefs in the element type of the array. This also handles propagation
3612 // of type qualifiers from the array type into the element type if present
3613 // (C99 6.7.3p8).
3614 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3615 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003616
Chris Lattner7adf0762008-08-04 07:31:14 +00003617 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003618
3619 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003620 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003621}
3622
John McCall33ddac02011-01-19 10:06:00 +00003623QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3624 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003625}
3626
John McCall33ddac02011-01-19 10:06:00 +00003627QualType ASTContext::getBaseElementType(QualType type) const {
3628 Qualifiers qs;
3629 while (true) {
3630 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003631 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00003632 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003633
John McCall33ddac02011-01-19 10:06:00 +00003634 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00003635 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003636 }
Mike Stump11289f42009-09-09 15:08:12 +00003637
John McCall33ddac02011-01-19 10:06:00 +00003638 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003639}
3640
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003641/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003642uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003643ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3644 uint64_t ElementCount = 1;
3645 do {
3646 ElementCount *= CA->getSize().getZExtValue();
3647 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3648 } while (CA);
3649 return ElementCount;
3650}
3651
Steve Naroff0af91202007-04-27 21:51:21 +00003652/// getFloatingRank - Return a relative rank for floating point types.
3653/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003654static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003655 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003656 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003657
John McCall9dd450b2009-09-21 23:43:11 +00003658 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3659 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003660 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003661 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00003662 case BuiltinType::Float: return FloatRank;
3663 case BuiltinType::Double: return DoubleRank;
3664 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003665 }
3666}
3667
Mike Stump11289f42009-09-09 15:08:12 +00003668/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3669/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003670/// 'typeDomain' is a real floating point or complex type.
3671/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003672QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3673 QualType Domain) const {
3674 FloatingRank EltRank = getFloatingRank(Size);
3675 if (Domain->isComplexType()) {
3676 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003677 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00003678 case FloatRank: return FloatComplexTy;
3679 case DoubleRank: return DoubleComplexTy;
3680 case LongDoubleRank: return LongDoubleComplexTy;
3681 }
Steve Naroff0af91202007-04-27 21:51:21 +00003682 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003683
3684 assert(Domain->isRealFloatingType() && "Unknown domain!");
3685 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003686 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003687 case FloatRank: return FloatTy;
3688 case DoubleRank: return DoubleTy;
3689 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003690 }
David Blaikief47fa302012-01-17 02:30:50 +00003691 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00003692}
3693
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003694/// getFloatingTypeOrder - Compare the rank of the two specified floating
3695/// point types, ignoring the domain of the type (i.e. 'double' ==
3696/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003697/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003698int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003699 FloatingRank LHSR = getFloatingRank(LHS);
3700 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003701
Chris Lattnerb90739d2008-04-06 23:38:49 +00003702 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003703 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003704 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003705 return 1;
3706 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003707}
3708
Chris Lattner76a00cf2008-04-06 22:59:24 +00003709/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3710/// routine will assert if passed a built-in type that isn't an integer or enum,
3711/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003712unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003713 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003714
Chris Lattner76a00cf2008-04-06 22:59:24 +00003715 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003716 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003717 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003718 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003719 case BuiltinType::Char_S:
3720 case BuiltinType::Char_U:
3721 case BuiltinType::SChar:
3722 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003723 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003724 case BuiltinType::Short:
3725 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003726 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003727 case BuiltinType::Int:
3728 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003729 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003730 case BuiltinType::Long:
3731 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003732 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003733 case BuiltinType::LongLong:
3734 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003735 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003736 case BuiltinType::Int128:
3737 case BuiltinType::UInt128:
3738 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003739 }
3740}
3741
Eli Friedman629ffb92009-08-20 04:21:42 +00003742/// \brief Whether this is a promotable bitfield reference according
3743/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3744///
3745/// \returns the type this bit-field will promote to, or NULL if no
3746/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003747QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003748 if (E->isTypeDependent() || E->isValueDependent())
3749 return QualType();
3750
Eli Friedman629ffb92009-08-20 04:21:42 +00003751 FieldDecl *Field = E->getBitField();
3752 if (!Field)
3753 return QualType();
3754
3755 QualType FT = Field->getType();
3756
Richard Smithcaf33902011-10-10 18:28:20 +00003757 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00003758 uint64_t IntSize = getTypeSize(IntTy);
3759 // GCC extension compatibility: if the bit-field size is less than or equal
3760 // to the size of int, it gets promoted no matter what its type is.
3761 // For instance, unsigned long bf : 4 gets promoted to signed int.
3762 if (BitWidth < IntSize)
3763 return IntTy;
3764
3765 if (BitWidth == IntSize)
3766 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3767
3768 // Types bigger than int are not subject to promotions, and therefore act
3769 // like the base type.
3770 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3771 // is ridiculous.
3772 return QualType();
3773}
3774
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003775/// getPromotedIntegerType - Returns the type that Promotable will
3776/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3777/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003778QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003779 assert(!Promotable.isNull());
3780 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003781 if (const EnumType *ET = Promotable->getAs<EnumType>())
3782 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00003783
3784 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3785 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3786 // (3.9.1) can be converted to a prvalue of the first of the following
3787 // types that can represent all the values of its underlying type:
3788 // int, unsigned int, long int, unsigned long int, long long int, or
3789 // unsigned long long int [...]
3790 // FIXME: Is there some better way to compute this?
3791 if (BT->getKind() == BuiltinType::WChar_S ||
3792 BT->getKind() == BuiltinType::WChar_U ||
3793 BT->getKind() == BuiltinType::Char16 ||
3794 BT->getKind() == BuiltinType::Char32) {
3795 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3796 uint64_t FromSize = getTypeSize(BT);
3797 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3798 LongLongTy, UnsignedLongLongTy };
3799 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3800 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3801 if (FromSize < ToSize ||
3802 (FromSize == ToSize &&
3803 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3804 return PromoteTypes[Idx];
3805 }
3806 llvm_unreachable("char type should fit into long long");
3807 }
3808 }
3809
3810 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003811 if (Promotable->isSignedIntegerType())
3812 return IntTy;
3813 uint64_t PromotableSize = getTypeSize(Promotable);
3814 uint64_t IntSize = getTypeSize(IntTy);
3815 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3816 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3817}
3818
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003819/// \brief Recurses in pointer/array types until it finds an objc retainable
3820/// type and returns its ownership.
3821Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3822 while (!T.isNull()) {
3823 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3824 return T.getObjCLifetime();
3825 if (T->isArrayType())
3826 T = getBaseElementType(T);
3827 else if (const PointerType *PT = T->getAs<PointerType>())
3828 T = PT->getPointeeType();
3829 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00003830 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003831 else
3832 break;
3833 }
3834
3835 return Qualifiers::OCL_None;
3836}
3837
Mike Stump11289f42009-09-09 15:08:12 +00003838/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003839/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003840/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003841int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00003842 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3843 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003844 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003845
Chris Lattner76a00cf2008-04-06 22:59:24 +00003846 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3847 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003848
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003849 unsigned LHSRank = getIntegerRank(LHSC);
3850 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003851
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003852 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3853 if (LHSRank == RHSRank) return 0;
3854 return LHSRank > RHSRank ? 1 : -1;
3855 }
Mike Stump11289f42009-09-09 15:08:12 +00003856
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003857 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3858 if (LHSUnsigned) {
3859 // If the unsigned [LHS] type is larger, return it.
3860 if (LHSRank >= RHSRank)
3861 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003862
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003863 // If the signed type can represent all values of the unsigned type, it
3864 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003865 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003866 return -1;
3867 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003868
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003869 // If the unsigned [RHS] type is larger, return it.
3870 if (RHSRank >= LHSRank)
3871 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003872
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003873 // If the signed type can represent all values of the unsigned type, it
3874 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003875 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003876 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003877}
Anders Carlsson98f07902007-08-17 05:31:46 +00003878
Anders Carlsson6d417272009-11-14 21:45:58 +00003879static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003880CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3881 DeclContext *DC, IdentifierInfo *Id) {
3882 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003883 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003884 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003885 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003886 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003887}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003888
Mike Stump11289f42009-09-09 15:08:12 +00003889// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003890QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003891 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003892 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003893 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003894 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003895 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003896
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003897 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003898
Anders Carlsson98f07902007-08-17 05:31:46 +00003899 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003900 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003901 // int flags;
3902 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003903 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003904 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003905 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003906 FieldTypes[3] = LongTy;
3907
Anders Carlsson98f07902007-08-17 05:31:46 +00003908 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003909 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003910 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003911 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00003912 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003913 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003914 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003915 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003916 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00003917 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003918 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003919 }
3920
Douglas Gregord5058122010-02-11 01:19:42 +00003921 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003922 }
Mike Stump11289f42009-09-09 15:08:12 +00003923
Anders Carlsson98f07902007-08-17 05:31:46 +00003924 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003925}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003926
Douglas Gregor512b0772009-04-23 22:29:11 +00003927void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003928 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003929 assert(Rec && "Invalid CFConstantStringType");
3930 CFConstantStringTypeDecl = Rec->getDecl();
3931}
3932
Jay Foad39c79802011-01-12 09:06:06 +00003933QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003934 if (BlockDescriptorType)
3935 return getTagDeclType(BlockDescriptorType);
3936
3937 RecordDecl *T;
3938 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003939 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003940 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003941 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003942
3943 QualType FieldTypes[] = {
3944 UnsignedLongTy,
3945 UnsignedLongTy,
3946 };
3947
3948 const char *FieldNames[] = {
3949 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003950 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003951 };
3952
3953 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003954 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003955 SourceLocation(),
3956 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003957 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003958 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003959 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003960 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00003961 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003962 T->addDecl(Field);
3963 }
3964
Douglas Gregord5058122010-02-11 01:19:42 +00003965 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003966
3967 BlockDescriptorType = T;
3968
3969 return getTagDeclType(BlockDescriptorType);
3970}
3971
Jay Foad39c79802011-01-12 09:06:06 +00003972QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003973 if (BlockDescriptorExtendedType)
3974 return getTagDeclType(BlockDescriptorExtendedType);
3975
3976 RecordDecl *T;
3977 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003978 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003979 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003980 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003981
3982 QualType FieldTypes[] = {
3983 UnsignedLongTy,
3984 UnsignedLongTy,
3985 getPointerType(VoidPtrTy),
3986 getPointerType(VoidPtrTy)
3987 };
3988
3989 const char *FieldNames[] = {
3990 "reserved",
3991 "Size",
3992 "CopyFuncPtr",
3993 "DestroyFuncPtr"
3994 };
3995
3996 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003997 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003998 SourceLocation(),
3999 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004000 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004001 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004002 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004003 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004004 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004005 T->addDecl(Field);
4006 }
4007
Douglas Gregord5058122010-02-11 01:19:42 +00004008 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004009
4010 BlockDescriptorExtendedType = T;
4011
4012 return getTagDeclType(BlockDescriptorExtendedType);
4013}
4014
Jay Foad39c79802011-01-12 09:06:06 +00004015bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCall31168b02011-06-15 23:02:42 +00004016 if (Ty->isObjCRetainableType())
Mike Stump94967902009-10-21 18:16:27 +00004017 return true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004018 if (getLangOpts().CPlusPlus) {
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004019 if (const RecordType *RT = Ty->getAs<RecordType>()) {
4020 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntfcaeae42011-05-25 20:50:04 +00004021 return RD->hasConstCopyConstructor();
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004022
4023 }
4024 }
Mike Stump94967902009-10-21 18:16:27 +00004025 return false;
4026}
4027
Jay Foad39c79802011-01-12 09:06:06 +00004028QualType
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004029ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00004030 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00004031 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00004032 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00004033 // unsigned int __flags;
4034 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00004035 // void *__copy_helper; // as needed
4036 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00004037 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00004038 // } *
4039
Mike Stump94967902009-10-21 18:16:27 +00004040 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
4041
4042 // FIXME: Move up
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004043 SmallString<36> Name;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00004044 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
4045 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00004046 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004047 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00004048 T->startDefinition();
4049 QualType Int32Ty = IntTy;
4050 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
4051 QualType FieldTypes[] = {
4052 getPointerType(VoidPtrTy),
4053 getPointerType(getTagDeclType(T)),
4054 Int32Ty,
4055 Int32Ty,
4056 getPointerType(VoidPtrTy),
4057 getPointerType(VoidPtrTy),
4058 Ty
4059 };
4060
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004061 StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00004062 "__isa",
4063 "__forwarding",
4064 "__flags",
4065 "__size",
4066 "__copy_helper",
4067 "__destroy_helper",
4068 DeclName,
4069 };
4070
4071 for (size_t i = 0; i < 7; ++i) {
4072 if (!HasCopyAndDispose && i >=4 && i <= 5)
4073 continue;
4074 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00004075 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00004076 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004077 FieldTypes[i], /*TInfo=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004078 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004079 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004080 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00004081 T->addDecl(Field);
4082 }
4083
Douglas Gregord5058122010-02-11 01:19:42 +00004084 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00004085
4086 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00004087}
4088
Douglas Gregorbab8a962011-09-08 01:46:34 +00004089TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4090 if (!ObjCInstanceTypeDecl)
4091 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4092 getTranslationUnitDecl(),
4093 SourceLocation(),
4094 SourceLocation(),
4095 &Idents.get("instancetype"),
4096 getTrivialTypeSourceInfo(getObjCIdType()));
4097 return ObjCInstanceTypeDecl;
4098}
4099
Anders Carlsson18acd442007-10-29 06:33:42 +00004100// This returns true if a type has been typedefed to BOOL:
4101// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004102static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004103 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004104 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4105 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004106
Anders Carlssond8499822007-10-29 05:01:08 +00004107 return false;
4108}
4109
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004110/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004111/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004112CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004113 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4114 return CharUnits::Zero();
4115
Ken Dyck40775002010-01-11 17:06:35 +00004116 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004117
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004118 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004119 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004120 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004121 // Treat arrays as pointers, since that's how they're passed in.
4122 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004123 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004124 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004125}
4126
4127static inline
4128std::string charUnitsToString(const CharUnits &CU) {
4129 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004130}
4131
John McCall351762c2011-02-07 10:33:21 +00004132/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004133/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004134std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4135 std::string S;
4136
David Chisnall950a9512009-11-17 19:33:30 +00004137 const BlockDecl *Decl = Expr->getBlockDecl();
4138 QualType BlockTy =
4139 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4140 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00004141 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004142 // Compute size of all parameters.
4143 // Start with computing size of a pointer in number of bytes.
4144 // FIXME: There might(should) be a better way of doing this computation!
4145 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004146 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4147 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004148 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004149 E = Decl->param_end(); PI != E; ++PI) {
4150 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004151 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00004152 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004153 ParmOffset += sz;
4154 }
4155 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004156 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004157 // Block pointer and offset.
4158 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004159
4160 // Argument types.
4161 ParmOffset = PtrSize;
4162 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4163 Decl->param_end(); PI != E; ++PI) {
4164 ParmVarDecl *PVDecl = *PI;
4165 QualType PType = PVDecl->getOriginalType();
4166 if (const ArrayType *AT =
4167 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4168 // Use array's original type only if it has known number of
4169 // elements.
4170 if (!isa<ConstantArrayType>(AT))
4171 PType = PVDecl->getType();
4172 } else if (PType->isFunctionType())
4173 PType = PVDecl->getType();
4174 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004175 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004176 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004177 }
John McCall351762c2011-02-07 10:33:21 +00004178
4179 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004180}
4181
Douglas Gregora9d84932011-05-27 01:19:52 +00004182bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004183 std::string& S) {
4184 // Encode result type.
4185 getObjCEncodingForType(Decl->getResultType(), S);
4186 CharUnits ParmOffset;
4187 // Compute size of all parameters.
4188 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4189 E = Decl->param_end(); PI != E; ++PI) {
4190 QualType PType = (*PI)->getType();
4191 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004192 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004193 continue;
4194
David Chisnall50e4eba2010-12-30 14:05:53 +00004195 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004196 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004197 ParmOffset += sz;
4198 }
4199 S += charUnitsToString(ParmOffset);
4200 ParmOffset = CharUnits::Zero();
4201
4202 // Argument types.
4203 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4204 E = Decl->param_end(); PI != E; ++PI) {
4205 ParmVarDecl *PVDecl = *PI;
4206 QualType PType = PVDecl->getOriginalType();
4207 if (const ArrayType *AT =
4208 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4209 // Use array's original type only if it has known number of
4210 // elements.
4211 if (!isa<ConstantArrayType>(AT))
4212 PType = PVDecl->getType();
4213 } else if (PType->isFunctionType())
4214 PType = PVDecl->getType();
4215 getObjCEncodingForType(PType, S);
4216 S += charUnitsToString(ParmOffset);
4217 ParmOffset += getObjCEncodingTypeSize(PType);
4218 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004219
4220 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004221}
4222
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004223/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4224/// method parameter or return type. If Extended, include class names and
4225/// block object types.
4226void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4227 QualType T, std::string& S,
4228 bool Extended) const {
4229 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4230 getObjCEncodingForTypeQualifier(QT, S);
4231 // Encode parameter type.
4232 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4233 true /*OutermostType*/,
4234 false /*EncodingProperty*/,
4235 false /*StructField*/,
4236 Extended /*EncodeBlockParameters*/,
4237 Extended /*EncodeClassNames*/);
4238}
4239
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004240/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004241/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004242bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004243 std::string& S,
4244 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004245 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004246 // Encode return type.
4247 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4248 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004249 // Compute size of all parameters.
4250 // Start with computing size of a pointer in number of bytes.
4251 // FIXME: There might(should) be a better way of doing this computation!
4252 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004253 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004254 // The first two arguments (self and _cmd) are pointers; account for
4255 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004256 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004257 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004258 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004259 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004260 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004261 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004262 continue;
4263
Ken Dyck40775002010-01-11 17:06:35 +00004264 assert (sz.isPositive() &&
4265 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004266 ParmOffset += sz;
4267 }
Ken Dyck40775002010-01-11 17:06:35 +00004268 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004269 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004270 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004271
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004272 // Argument types.
4273 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004274 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004275 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004276 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004277 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004278 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004279 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4280 // Use array's original type only if it has known number of
4281 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004282 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004283 PType = PVDecl->getType();
4284 } else if (PType->isFunctionType())
4285 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004286 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4287 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004288 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004289 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004290 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004291
4292 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004293}
4294
Daniel Dunbar4932b362008-08-28 04:38:10 +00004295/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004296/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004297/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4298/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004299/// Property attributes are stored as a comma-delimited C string. The simple
4300/// attributes readonly and bycopy are encoded as single characters. The
4301/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4302/// encoded as single characters, followed by an identifier. Property types
4303/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004304/// these attributes are defined by the following enumeration:
4305/// @code
4306/// enum PropertyAttributes {
4307/// kPropertyReadOnly = 'R', // property is read-only.
4308/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4309/// kPropertyByref = '&', // property is a reference to the value last assigned
4310/// kPropertyDynamic = 'D', // property is dynamic
4311/// kPropertyGetter = 'G', // followed by getter selector name
4312/// kPropertySetter = 'S', // followed by setter selector name
4313/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004314/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004315/// kPropertyWeak = 'W' // 'weak' property
4316/// kPropertyStrong = 'P' // property GC'able
4317/// kPropertyNonAtomic = 'N' // property non-atomic
4318/// };
4319/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004320void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004321 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004322 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004323 // Collect information from the property implementation decl(s).
4324 bool Dynamic = false;
4325 ObjCPropertyImplDecl *SynthesizePID = 0;
4326
4327 // FIXME: Duplicated code due to poor abstraction.
4328 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004329 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004330 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4331 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004332 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004333 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004334 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004335 if (PID->getPropertyDecl() == PD) {
4336 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4337 Dynamic = true;
4338 } else {
4339 SynthesizePID = PID;
4340 }
4341 }
4342 }
4343 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004344 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004345 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004346 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004347 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004348 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004349 if (PID->getPropertyDecl() == PD) {
4350 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4351 Dynamic = true;
4352 } else {
4353 SynthesizePID = PID;
4354 }
4355 }
Mike Stump11289f42009-09-09 15:08:12 +00004356 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004357 }
4358 }
4359
4360 // FIXME: This is not very efficient.
4361 S = "T";
4362
4363 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004364 // GCC has some special rules regarding encoding of properties which
4365 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004366 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004367 true /* outermost type */,
4368 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004369
4370 if (PD->isReadOnly()) {
4371 S += ",R";
4372 } else {
4373 switch (PD->getSetterKind()) {
4374 case ObjCPropertyDecl::Assign: break;
4375 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004376 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004377 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004378 }
4379 }
4380
4381 // It really isn't clear at all what this means, since properties
4382 // are "dynamic by default".
4383 if (Dynamic)
4384 S += ",D";
4385
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004386 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4387 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004388
Daniel Dunbar4932b362008-08-28 04:38:10 +00004389 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4390 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004391 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004392 }
4393
4394 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4395 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004396 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004397 }
4398
4399 if (SynthesizePID) {
4400 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4401 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004402 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004403 }
4404
4405 // FIXME: OBJCGC: weak & strong
4406}
4407
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004408/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004409/// Another legacy compatibility encoding: 32-bit longs are encoded as
4410/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004411/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4412///
4413void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004414 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004415 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004416 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004417 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004418 else
Jay Foad39c79802011-01-12 09:06:06 +00004419 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004420 PointeeTy = IntTy;
4421 }
4422 }
4423}
4424
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004425void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004426 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004427 // We follow the behavior of gcc, expanding structures which are
4428 // directly pointed to, and expanding embedded structures. Note that
4429 // these rules are sufficient to prevent recursive encoding of the
4430 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004431 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004432 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004433}
4434
David Chisnallb190a2c2010-06-04 01:10:52 +00004435static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4436 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004437 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnallb190a2c2010-06-04 01:10:52 +00004438 case BuiltinType::Void: return 'v';
4439 case BuiltinType::Bool: return 'B';
4440 case BuiltinType::Char_U:
4441 case BuiltinType::UChar: return 'C';
4442 case BuiltinType::UShort: return 'S';
4443 case BuiltinType::UInt: return 'I';
4444 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004445 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004446 case BuiltinType::UInt128: return 'T';
4447 case BuiltinType::ULongLong: return 'Q';
4448 case BuiltinType::Char_S:
4449 case BuiltinType::SChar: return 'c';
4450 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004451 case BuiltinType::WChar_S:
4452 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004453 case BuiltinType::Int: return 'i';
4454 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004455 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004456 case BuiltinType::LongLong: return 'q';
4457 case BuiltinType::Int128: return 't';
4458 case BuiltinType::Float: return 'f';
4459 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004460 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004461 }
4462}
4463
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004464static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4465 EnumDecl *Enum = ET->getDecl();
4466
4467 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4468 if (!Enum->isFixed())
4469 return 'i';
4470
4471 // The encoding of a fixed enum type matches its fixed underlying type.
4472 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4473}
4474
Jay Foad39c79802011-01-12 09:06:06 +00004475static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004476 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00004477 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004478 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004479 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4480 // The GNU runtime requires more information; bitfields are encoded as b,
4481 // then the offset (in bits) of the first element, then the type of the
4482 // bitfield, then the size in bits. For example, in this structure:
4483 //
4484 // struct
4485 // {
4486 // int integer;
4487 // int flags:2;
4488 // };
4489 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4490 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4491 // information is not especially sensible, but we're stuck with it for
4492 // compatibility with GCC, although providing it breaks anything that
4493 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00004494 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004495 const RecordDecl *RD = FD->getParent();
4496 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004497 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004498 if (const EnumType *ET = T->getAs<EnumType>())
4499 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnall6f0a7d22010-12-26 20:12:30 +00004500 else
Jay Foad39c79802011-01-12 09:06:06 +00004501 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004502 }
Richard Smithcaf33902011-10-10 18:28:20 +00004503 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004504}
4505
Daniel Dunbar07d07852009-10-18 21:17:35 +00004506// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004507void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4508 bool ExpandPointedToStructures,
4509 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004510 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004511 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004512 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004513 bool StructField,
4514 bool EncodeBlockParameters,
4515 bool EncodeClassNames) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004516 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004517 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004518 return EncodeBitField(this, S, T, FD);
4519 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004520 return;
4521 }
Mike Stump11289f42009-09-09 15:08:12 +00004522
John McCall9dd450b2009-09-21 23:43:11 +00004523 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004524 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004525 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004526 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004527 return;
4528 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004529
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004530 // encoding for pointer or r3eference types.
4531 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004532 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004533 if (PT->isObjCSelType()) {
4534 S += ':';
4535 return;
4536 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004537 PointeeTy = PT->getPointeeType();
4538 }
4539 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4540 PointeeTy = RT->getPointeeType();
4541 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004542 bool isReadOnly = false;
4543 // For historical/compatibility reasons, the read-only qualifier of the
4544 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4545 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004546 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004547 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004548 if (OutermostType && T.isConstQualified()) {
4549 isReadOnly = true;
4550 S += 'r';
4551 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004552 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004553 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004554 while (P->getAs<PointerType>())
4555 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004556 if (P.isConstQualified()) {
4557 isReadOnly = true;
4558 S += 'r';
4559 }
4560 }
4561 if (isReadOnly) {
4562 // Another legacy compatibility encoding. Some ObjC qualifier and type
4563 // combinations need to be rearranged.
4564 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004565 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004566 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004567 }
Mike Stump11289f42009-09-09 15:08:12 +00004568
Anders Carlssond8499822007-10-29 05:01:08 +00004569 if (PointeeTy->isCharType()) {
4570 // char pointer types should be encoded as '*' unless it is a
4571 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004572 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004573 S += '*';
4574 return;
4575 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004576 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004577 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4578 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4579 S += '#';
4580 return;
4581 }
4582 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4583 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4584 S += '@';
4585 return;
4586 }
4587 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004588 }
Anders Carlssond8499822007-10-29 05:01:08 +00004589 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004590 getLegacyIntegralTypeEncoding(PointeeTy);
4591
Mike Stump11289f42009-09-09 15:08:12 +00004592 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004593 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004594 return;
4595 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004596
Chris Lattnere7cabb92009-07-13 00:10:46 +00004597 if (const ArrayType *AT =
4598 // Ignore type qualifiers etc.
4599 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004600 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004601 // Incomplete arrays are encoded as a pointer to the array element.
4602 S += '^';
4603
Mike Stump11289f42009-09-09 15:08:12 +00004604 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004605 false, ExpandStructures, FD);
4606 } else {
4607 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004608
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004609 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4610 if (getTypeSize(CAT->getElementType()) == 0)
4611 S += '0';
4612 else
4613 S += llvm::utostr(CAT->getSize().getZExtValue());
4614 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004615 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004616 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4617 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00004618 S += '0';
4619 }
Mike Stump11289f42009-09-09 15:08:12 +00004620
4621 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004622 false, ExpandStructures, FD);
4623 S += ']';
4624 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004625 return;
4626 }
Mike Stump11289f42009-09-09 15:08:12 +00004627
John McCall9dd450b2009-09-21 23:43:11 +00004628 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004629 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004630 return;
4631 }
Mike Stump11289f42009-09-09 15:08:12 +00004632
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004633 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004634 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004635 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004636 // Anonymous structures print as '?'
4637 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4638 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004639 if (ClassTemplateSpecializationDecl *Spec
4640 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4641 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4642 std::string TemplateArgsStr
4643 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004644 TemplateArgs.data(),
4645 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00004646 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004647
4648 S += TemplateArgsStr;
4649 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004650 } else {
4651 S += '?';
4652 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004653 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004654 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004655 if (!RDecl->isUnion()) {
4656 getObjCEncodingForStructureImpl(RDecl, S, FD);
4657 } else {
4658 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4659 FieldEnd = RDecl->field_end();
4660 Field != FieldEnd; ++Field) {
4661 if (FD) {
4662 S += '"';
4663 S += Field->getNameAsString();
4664 S += '"';
4665 }
Mike Stump11289f42009-09-09 15:08:12 +00004666
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004667 // Special case bit-fields.
4668 if (Field->isBitField()) {
4669 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00004670 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004671 } else {
4672 QualType qt = Field->getType();
4673 getLegacyIntegralTypeEncoding(qt);
4674 getObjCEncodingForTypeImpl(qt, S, false, true,
4675 FD, /*OutermostType*/false,
4676 /*EncodingProperty*/false,
4677 /*StructField*/true);
4678 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004679 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004680 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004681 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004682 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004683 return;
4684 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004685
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004686 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004687 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004688 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004689 else
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004690 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004691 return;
4692 }
Mike Stump11289f42009-09-09 15:08:12 +00004693
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004694 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004695 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004696 if (EncodeBlockParameters) {
4697 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4698
4699 S += '<';
4700 // Block return type
4701 getObjCEncodingForTypeImpl(FT->getResultType(), S,
4702 ExpandPointedToStructures, ExpandStructures,
4703 FD,
4704 false /* OutermostType */,
4705 EncodingProperty,
4706 false /* StructField */,
4707 EncodeBlockParameters,
4708 EncodeClassNames);
4709 // Block self
4710 S += "@?";
4711 // Block parameters
4712 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4713 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4714 E = FPT->arg_type_end(); I && (I != E); ++I) {
4715 getObjCEncodingForTypeImpl(*I, S,
4716 ExpandPointedToStructures,
4717 ExpandStructures,
4718 FD,
4719 false /* OutermostType */,
4720 EncodingProperty,
4721 false /* StructField */,
4722 EncodeBlockParameters,
4723 EncodeClassNames);
4724 }
4725 }
4726 S += '>';
4727 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004728 return;
4729 }
Mike Stump11289f42009-09-09 15:08:12 +00004730
John McCall8b07ec22010-05-15 11:32:37 +00004731 // Ignore protocol qualifiers when mangling at this level.
4732 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4733 T = OT->getBaseType();
4734
John McCall8ccfcb52009-09-24 19:53:00 +00004735 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004736 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004737 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004738 S += '{';
4739 const IdentifierInfo *II = OI->getIdentifier();
4740 S += II->getName();
4741 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00004742 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004743 DeepCollectObjCIvars(OI, true, Ivars);
4744 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004745 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004746 if (Field->isBitField())
4747 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004748 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004749 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004750 }
4751 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004752 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004753 }
Mike Stump11289f42009-09-09 15:08:12 +00004754
John McCall9dd450b2009-09-21 23:43:11 +00004755 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004756 if (OPT->isObjCIdType()) {
4757 S += '@';
4758 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004759 }
Mike Stump11289f42009-09-09 15:08:12 +00004760
Steve Narofff0c86112009-10-28 22:03:49 +00004761 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4762 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4763 // Since this is a binary compatibility issue, need to consult with runtime
4764 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004765 S += '#';
4766 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004767 }
Mike Stump11289f42009-09-09 15:08:12 +00004768
Chris Lattnere7cabb92009-07-13 00:10:46 +00004769 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004770 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004771 ExpandPointedToStructures,
4772 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004773 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004774 // Note that we do extended encoding of protocol qualifer list
4775 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004776 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004777 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4778 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004779 S += '<';
4780 S += (*I)->getNameAsString();
4781 S += '>';
4782 }
4783 S += '"';
4784 }
4785 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004786 }
Mike Stump11289f42009-09-09 15:08:12 +00004787
Chris Lattnere7cabb92009-07-13 00:10:46 +00004788 QualType PointeeTy = OPT->getPointeeType();
4789 if (!EncodingProperty &&
4790 isa<TypedefType>(PointeeTy.getTypePtr())) {
4791 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004792 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004793 // {...};
4794 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004795 getObjCEncodingForTypeImpl(PointeeTy, S,
4796 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004797 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004798 return;
4799 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004800
4801 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004802 if (OPT->getInterfaceDecl() &&
4803 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004804 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004805 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004806 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4807 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004808 S += '<';
4809 S += (*I)->getNameAsString();
4810 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004811 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004812 S += '"';
4813 }
4814 return;
4815 }
Mike Stump11289f42009-09-09 15:08:12 +00004816
John McCalla9e6e8d2010-05-17 23:56:34 +00004817 // gcc just blithely ignores member pointers.
4818 // TODO: maybe there should be a mangling for these
4819 if (T->getAs<MemberPointerType>())
4820 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004821
4822 if (T->isVectorType()) {
4823 // This matches gcc's encoding, even though technically it is
4824 // insufficient.
4825 // FIXME. We should do a better job than gcc.
4826 return;
4827 }
4828
David Blaikie83d382b2011-09-23 05:06:16 +00004829 llvm_unreachable("@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004830}
4831
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004832void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4833 std::string &S,
4834 const FieldDecl *FD,
4835 bool includeVBases) const {
4836 assert(RDecl && "Expected non-null RecordDecl");
4837 assert(!RDecl->isUnion() && "Should not be called for unions");
4838 if (!RDecl->getDefinition())
4839 return;
4840
4841 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4842 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4843 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4844
4845 if (CXXRec) {
4846 for (CXXRecordDecl::base_class_iterator
4847 BI = CXXRec->bases_begin(),
4848 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4849 if (!BI->isVirtual()) {
4850 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004851 if (base->isEmpty())
4852 continue;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004853 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4854 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4855 std::make_pair(offs, base));
4856 }
4857 }
4858 }
4859
4860 unsigned i = 0;
4861 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4862 FieldEnd = RDecl->field_end();
4863 Field != FieldEnd; ++Field, ++i) {
4864 uint64_t offs = layout.getFieldOffset(i);
4865 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00004866 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004867 }
4868
4869 if (CXXRec && includeVBases) {
4870 for (CXXRecordDecl::base_class_iterator
4871 BI = CXXRec->vbases_begin(),
4872 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4873 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004874 if (base->isEmpty())
4875 continue;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004876 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00004877 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4878 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4879 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004880 }
4881 }
4882
4883 CharUnits size;
4884 if (CXXRec) {
4885 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4886 } else {
4887 size = layout.getSize();
4888 }
4889
4890 uint64_t CurOffs = 0;
4891 std::multimap<uint64_t, NamedDecl *>::iterator
4892 CurLayObj = FieldOrBaseOffsets.begin();
4893
Douglas Gregorf5d6c742012-04-27 22:30:01 +00004894 if (CXXRec && CXXRec->isDynamicClass() &&
4895 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004896 if (FD) {
4897 S += "\"_vptr$";
4898 std::string recname = CXXRec->getNameAsString();
4899 if (recname.empty()) recname = "?";
4900 S += recname;
4901 S += '"';
4902 }
4903 S += "^^?";
4904 CurOffs += getTypeSize(VoidPtrTy);
4905 }
4906
4907 if (!RDecl->hasFlexibleArrayMember()) {
4908 // Mark the end of the structure.
4909 uint64_t offs = toBits(size);
4910 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4911 std::make_pair(offs, (NamedDecl*)0));
4912 }
4913
4914 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4915 assert(CurOffs <= CurLayObj->first);
4916
4917 if (CurOffs < CurLayObj->first) {
4918 uint64_t padding = CurLayObj->first - CurOffs;
4919 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4920 // packing/alignment of members is different that normal, in which case
4921 // the encoding will be out-of-sync with the real layout.
4922 // If the runtime switches to just consider the size of types without
4923 // taking into account alignment, we could make padding explicit in the
4924 // encoding (e.g. using arrays of chars). The encoding strings would be
4925 // longer then though.
4926 CurOffs += padding;
4927 }
4928
4929 NamedDecl *dcl = CurLayObj->second;
4930 if (dcl == 0)
4931 break; // reached end of structure.
4932
4933 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4934 // We expand the bases without their virtual bases since those are going
4935 // in the initial structure. Note that this differs from gcc which
4936 // expands virtual bases each time one is encountered in the hierarchy,
4937 // making the encoding type bigger than it really is.
4938 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004939 assert(!base->isEmpty());
4940 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004941 } else {
4942 FieldDecl *field = cast<FieldDecl>(dcl);
4943 if (FD) {
4944 S += '"';
4945 S += field->getNameAsString();
4946 S += '"';
4947 }
4948
4949 if (field->isBitField()) {
4950 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00004951 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004952 } else {
4953 QualType qt = field->getType();
4954 getLegacyIntegralTypeEncoding(qt);
4955 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4956 /*OutermostType*/false,
4957 /*EncodingProperty*/false,
4958 /*StructField*/true);
4959 CurOffs += getTypeSize(field->getType());
4960 }
4961 }
4962 }
4963}
4964
Mike Stump11289f42009-09-09 15:08:12 +00004965void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004966 std::string& S) const {
4967 if (QT & Decl::OBJC_TQ_In)
4968 S += 'n';
4969 if (QT & Decl::OBJC_TQ_Inout)
4970 S += 'N';
4971 if (QT & Decl::OBJC_TQ_Out)
4972 S += 'o';
4973 if (QT & Decl::OBJC_TQ_Bycopy)
4974 S += 'O';
4975 if (QT & Decl::OBJC_TQ_Byref)
4976 S += 'R';
4977 if (QT & Decl::OBJC_TQ_Oneway)
4978 S += 'V';
4979}
4980
Douglas Gregor3ea72692011-08-12 05:46:01 +00004981TypedefDecl *ASTContext::getObjCIdDecl() const {
4982 if (!ObjCIdDecl) {
4983 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
4984 T = getObjCObjectPointerType(T);
4985 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
4986 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4987 getTranslationUnitDecl(),
4988 SourceLocation(), SourceLocation(),
4989 &Idents.get("id"), IdInfo);
4990 }
4991
4992 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00004993}
4994
Douglas Gregor52e02802011-08-12 06:17:30 +00004995TypedefDecl *ASTContext::getObjCSelDecl() const {
4996 if (!ObjCSelDecl) {
4997 QualType SelT = getPointerType(ObjCBuiltinSelTy);
4998 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
4999 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5000 getTranslationUnitDecl(),
5001 SourceLocation(), SourceLocation(),
5002 &Idents.get("SEL"), SelInfo);
5003 }
5004 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005005}
5006
Douglas Gregor0a586182011-08-12 05:59:41 +00005007TypedefDecl *ASTContext::getObjCClassDecl() const {
5008 if (!ObjCClassDecl) {
5009 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5010 T = getObjCObjectPointerType(T);
5011 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5012 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5013 getTranslationUnitDecl(),
5014 SourceLocation(), SourceLocation(),
5015 &Idents.get("Class"), ClassInfo);
5016 }
5017
5018 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005019}
5020
Douglas Gregord53ae832012-01-17 18:09:05 +00005021ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5022 if (!ObjCProtocolClassDecl) {
5023 ObjCProtocolClassDecl
5024 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5025 SourceLocation(),
5026 &Idents.get("Protocol"),
5027 /*PrevDecl=*/0,
5028 SourceLocation(), true);
5029 }
5030
5031 return ObjCProtocolClassDecl;
5032}
5033
Meador Inge5d3fb222012-06-16 03:34:49 +00005034//===----------------------------------------------------------------------===//
5035// __builtin_va_list Construction Functions
5036//===----------------------------------------------------------------------===//
5037
5038static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5039 // typedef char* __builtin_va_list;
5040 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5041 TypeSourceInfo *TInfo
5042 = Context->getTrivialTypeSourceInfo(CharPtrType);
5043
5044 TypedefDecl *VaListTypeDecl
5045 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5046 Context->getTranslationUnitDecl(),
5047 SourceLocation(), SourceLocation(),
5048 &Context->Idents.get("__builtin_va_list"),
5049 TInfo);
5050 return VaListTypeDecl;
5051}
5052
5053static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5054 // typedef void* __builtin_va_list;
5055 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5056 TypeSourceInfo *TInfo
5057 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5058
5059 TypedefDecl *VaListTypeDecl
5060 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5061 Context->getTranslationUnitDecl(),
5062 SourceLocation(), SourceLocation(),
5063 &Context->Idents.get("__builtin_va_list"),
5064 TInfo);
5065 return VaListTypeDecl;
5066}
5067
5068static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5069 // typedef struct __va_list_tag {
5070 RecordDecl *VaListTagDecl;
5071
5072 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5073 Context->getTranslationUnitDecl(),
5074 &Context->Idents.get("__va_list_tag"));
5075 VaListTagDecl->startDefinition();
5076
5077 const size_t NumFields = 5;
5078 QualType FieldTypes[NumFields];
5079 const char *FieldNames[NumFields];
5080
5081 // unsigned char gpr;
5082 FieldTypes[0] = Context->UnsignedCharTy;
5083 FieldNames[0] = "gpr";
5084
5085 // unsigned char fpr;
5086 FieldTypes[1] = Context->UnsignedCharTy;
5087 FieldNames[1] = "fpr";
5088
5089 // unsigned short reserved;
5090 FieldTypes[2] = Context->UnsignedShortTy;
5091 FieldNames[2] = "reserved";
5092
5093 // void* overflow_arg_area;
5094 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5095 FieldNames[3] = "overflow_arg_area";
5096
5097 // void* reg_save_area;
5098 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5099 FieldNames[4] = "reg_save_area";
5100
5101 // Create fields
5102 for (unsigned i = 0; i < NumFields; ++i) {
5103 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5104 SourceLocation(),
5105 SourceLocation(),
5106 &Context->Idents.get(FieldNames[i]),
5107 FieldTypes[i], /*TInfo=*/0,
5108 /*BitWidth=*/0,
5109 /*Mutable=*/false,
5110 ICIS_NoInit);
5111 Field->setAccess(AS_public);
5112 VaListTagDecl->addDecl(Field);
5113 }
5114 VaListTagDecl->completeDefinition();
5115 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5116
5117 // } __va_list_tag;
5118 TypedefDecl *VaListTagTypedefDecl
5119 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5120 Context->getTranslationUnitDecl(),
5121 SourceLocation(), SourceLocation(),
5122 &Context->Idents.get("__va_list_tag"),
5123 Context->getTrivialTypeSourceInfo(VaListTagType));
5124 QualType VaListTagTypedefType =
5125 Context->getTypedefType(VaListTagTypedefDecl);
5126
5127 // typedef __va_list_tag __builtin_va_list[1];
5128 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5129 QualType VaListTagArrayType
5130 = Context->getConstantArrayType(VaListTagTypedefType,
5131 Size, ArrayType::Normal, 0);
5132 TypeSourceInfo *TInfo
5133 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5134 TypedefDecl *VaListTypedefDecl
5135 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5136 Context->getTranslationUnitDecl(),
5137 SourceLocation(), SourceLocation(),
5138 &Context->Idents.get("__builtin_va_list"),
5139 TInfo);
5140
5141 return VaListTypedefDecl;
5142}
5143
5144static TypedefDecl *
5145CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5146 // typedef struct __va_list_tag {
5147 RecordDecl *VaListTagDecl;
5148 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5149 Context->getTranslationUnitDecl(),
5150 &Context->Idents.get("__va_list_tag"));
5151 VaListTagDecl->startDefinition();
5152
5153 const size_t NumFields = 4;
5154 QualType FieldTypes[NumFields];
5155 const char *FieldNames[NumFields];
5156
5157 // unsigned gp_offset;
5158 FieldTypes[0] = Context->UnsignedIntTy;
5159 FieldNames[0] = "gp_offset";
5160
5161 // unsigned fp_offset;
5162 FieldTypes[1] = Context->UnsignedIntTy;
5163 FieldNames[1] = "fp_offset";
5164
5165 // void* overflow_arg_area;
5166 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5167 FieldNames[2] = "overflow_arg_area";
5168
5169 // void* reg_save_area;
5170 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5171 FieldNames[3] = "reg_save_area";
5172
5173 // Create fields
5174 for (unsigned i = 0; i < NumFields; ++i) {
5175 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5176 VaListTagDecl,
5177 SourceLocation(),
5178 SourceLocation(),
5179 &Context->Idents.get(FieldNames[i]),
5180 FieldTypes[i], /*TInfo=*/0,
5181 /*BitWidth=*/0,
5182 /*Mutable=*/false,
5183 ICIS_NoInit);
5184 Field->setAccess(AS_public);
5185 VaListTagDecl->addDecl(Field);
5186 }
5187 VaListTagDecl->completeDefinition();
5188 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5189
5190 // } __va_list_tag;
5191 TypedefDecl *VaListTagTypedefDecl
5192 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5193 Context->getTranslationUnitDecl(),
5194 SourceLocation(), SourceLocation(),
5195 &Context->Idents.get("__va_list_tag"),
5196 Context->getTrivialTypeSourceInfo(VaListTagType));
5197 QualType VaListTagTypedefType =
5198 Context->getTypedefType(VaListTagTypedefDecl);
5199
5200 // typedef __va_list_tag __builtin_va_list[1];
5201 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5202 QualType VaListTagArrayType
5203 = Context->getConstantArrayType(VaListTagTypedefType,
5204 Size, ArrayType::Normal,0);
5205 TypeSourceInfo *TInfo
5206 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5207 TypedefDecl *VaListTypedefDecl
5208 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5209 Context->getTranslationUnitDecl(),
5210 SourceLocation(), SourceLocation(),
5211 &Context->Idents.get("__builtin_va_list"),
5212 TInfo);
5213
5214 return VaListTypedefDecl;
5215}
5216
5217static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5218 // typedef int __builtin_va_list[4];
5219 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5220 QualType IntArrayType
5221 = Context->getConstantArrayType(Context->IntTy,
5222 Size, ArrayType::Normal, 0);
5223 TypedefDecl *VaListTypedefDecl
5224 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5225 Context->getTranslationUnitDecl(),
5226 SourceLocation(), SourceLocation(),
5227 &Context->Idents.get("__builtin_va_list"),
5228 Context->getTrivialTypeSourceInfo(IntArrayType));
5229
5230 return VaListTypedefDecl;
5231}
5232
5233static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5234 TargetInfo::BuiltinVaListKind Kind) {
5235 switch (Kind) {
5236 case TargetInfo::CharPtrBuiltinVaList:
5237 return CreateCharPtrBuiltinVaListDecl(Context);
5238 case TargetInfo::VoidPtrBuiltinVaList:
5239 return CreateVoidPtrBuiltinVaListDecl(Context);
5240 case TargetInfo::PowerABIBuiltinVaList:
5241 return CreatePowerABIBuiltinVaListDecl(Context);
5242 case TargetInfo::X86_64ABIBuiltinVaList:
5243 return CreateX86_64ABIBuiltinVaListDecl(Context);
5244 case TargetInfo::PNaClABIBuiltinVaList:
5245 return CreatePNaClABIBuiltinVaListDecl(Context);
5246 }
5247
5248 llvm_unreachable("Unhandled __builtin_va_list type kind");
5249}
5250
5251TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5252 if (!BuiltinVaListDecl)
5253 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5254
5255 return BuiltinVaListDecl;
5256}
5257
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005258void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00005259 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00005260 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00005261
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005262 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00005263}
5264
John McCalld28ae272009-12-02 08:04:21 +00005265/// \brief Retrieve the template name that corresponds to a non-empty
5266/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00005267TemplateName
5268ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5269 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00005270 unsigned size = End - Begin;
5271 assert(size > 1 && "set is not overloaded!");
5272
5273 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5274 size * sizeof(FunctionTemplateDecl*));
5275 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5276
5277 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00005278 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00005279 NamedDecl *D = *I;
5280 assert(isa<FunctionTemplateDecl>(D) ||
5281 (isa<UsingShadowDecl>(D) &&
5282 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5283 *Storage++ = D;
5284 }
5285
5286 return TemplateName(OT);
5287}
5288
Douglas Gregordc572a32009-03-30 22:58:21 +00005289/// \brief Retrieve the template name that represents a qualified
5290/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00005291TemplateName
5292ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5293 bool TemplateKeyword,
5294 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00005295 assert(NNS && "Missing nested-name-specifier in qualified template name");
5296
Douglas Gregorc42075a2010-02-04 18:10:26 +00005297 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00005298 llvm::FoldingSetNodeID ID;
5299 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5300
5301 void *InsertPos = 0;
5302 QualifiedTemplateName *QTN =
5303 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5304 if (!QTN) {
5305 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
5306 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5307 }
5308
5309 return TemplateName(QTN);
5310}
5311
5312/// \brief Retrieve the template name that represents a dependent
5313/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00005314TemplateName
5315ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5316 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00005317 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00005318 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00005319
5320 llvm::FoldingSetNodeID ID;
5321 DependentTemplateName::Profile(ID, NNS, Name);
5322
5323 void *InsertPos = 0;
5324 DependentTemplateName *QTN =
5325 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5326
5327 if (QTN)
5328 return TemplateName(QTN);
5329
5330 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5331 if (CanonNNS == NNS) {
5332 QTN = new (*this,4) DependentTemplateName(NNS, Name);
5333 } else {
5334 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
5335 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005336 DependentTemplateName *CheckQTN =
5337 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5338 assert(!CheckQTN && "Dependent type name canonicalization broken");
5339 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00005340 }
5341
5342 DependentTemplateNames.InsertNode(QTN, InsertPos);
5343 return TemplateName(QTN);
5344}
5345
Douglas Gregor71395fa2009-11-04 00:56:37 +00005346/// \brief Retrieve the template name that represents a dependent
5347/// template name such as \c MetaFun::template operator+.
5348TemplateName
5349ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00005350 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00005351 assert((!NNS || NNS->isDependent()) &&
5352 "Nested name specifier must be dependent");
5353
5354 llvm::FoldingSetNodeID ID;
5355 DependentTemplateName::Profile(ID, NNS, Operator);
5356
5357 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00005358 DependentTemplateName *QTN
5359 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005360
5361 if (QTN)
5362 return TemplateName(QTN);
5363
5364 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5365 if (CanonNNS == NNS) {
5366 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
5367 } else {
5368 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
5369 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005370
5371 DependentTemplateName *CheckQTN
5372 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5373 assert(!CheckQTN && "Dependent template name canonicalization broken");
5374 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00005375 }
5376
5377 DependentTemplateNames.InsertNode(QTN, InsertPos);
5378 return TemplateName(QTN);
5379}
5380
Douglas Gregor5590be02011-01-15 06:45:20 +00005381TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00005382ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5383 TemplateName replacement) const {
5384 llvm::FoldingSetNodeID ID;
5385 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5386
5387 void *insertPos = 0;
5388 SubstTemplateTemplateParmStorage *subst
5389 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5390
5391 if (!subst) {
5392 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5393 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5394 }
5395
5396 return TemplateName(subst);
5397}
5398
5399TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00005400ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5401 const TemplateArgument &ArgPack) const {
5402 ASTContext &Self = const_cast<ASTContext &>(*this);
5403 llvm::FoldingSetNodeID ID;
5404 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5405
5406 void *InsertPos = 0;
5407 SubstTemplateTemplateParmPackStorage *Subst
5408 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5409
5410 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00005411 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00005412 ArgPack.pack_size(),
5413 ArgPack.pack_begin());
5414 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5415 }
5416
5417 return TemplateName(Subst);
5418}
5419
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005420/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00005421/// TargetInfo, produce the corresponding type. The unsigned @p Type
5422/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00005423CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005424 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00005425 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005426 case TargetInfo::SignedShort: return ShortTy;
5427 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5428 case TargetInfo::SignedInt: return IntTy;
5429 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5430 case TargetInfo::SignedLong: return LongTy;
5431 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5432 case TargetInfo::SignedLongLong: return LongLongTy;
5433 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5434 }
5435
David Blaikie83d382b2011-09-23 05:06:16 +00005436 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005437}
Ted Kremenek77c51b22008-07-24 23:58:27 +00005438
5439//===----------------------------------------------------------------------===//
5440// Type Predicates.
5441//===----------------------------------------------------------------------===//
5442
Fariborz Jahanian96207692009-02-18 21:49:28 +00005443/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5444/// garbage collection attribute.
5445///
John McCall553d45a2011-01-12 00:34:59 +00005446Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005447 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00005448 return Qualifiers::GCNone;
5449
David Blaikiebbafb8a2012-03-11 07:00:24 +00005450 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00005451 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5452
5453 // Default behaviour under objective-C's gc is for ObjC pointers
5454 // (or pointers to them) be treated as though they were declared
5455 // as __strong.
5456 if (GCAttrs == Qualifiers::GCNone) {
5457 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5458 return Qualifiers::Strong;
5459 else if (Ty->isPointerType())
5460 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5461 } else {
5462 // It's not valid to set GC attributes on anything that isn't a
5463 // pointer.
5464#ifndef NDEBUG
5465 QualType CT = Ty->getCanonicalTypeInternal();
5466 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5467 CT = AT->getElementType();
5468 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5469#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00005470 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00005471 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00005472}
5473
Chris Lattner49af6a42008-04-07 06:51:04 +00005474//===----------------------------------------------------------------------===//
5475// Type Compatibility Testing
5476//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00005477
Mike Stump11289f42009-09-09 15:08:12 +00005478/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005479/// compatible.
5480static bool areCompatVectorTypes(const VectorType *LHS,
5481 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00005482 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00005483 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00005484 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00005485}
5486
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005487bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5488 QualType SecondVec) {
5489 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5490 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5491
5492 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5493 return true;
5494
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005495 // Treat Neon vector types and most AltiVec vector types as if they are the
5496 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005497 const VectorType *First = FirstVec->getAs<VectorType>();
5498 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005499 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005500 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005501 First->getVectorKind() != VectorType::AltiVecPixel &&
5502 First->getVectorKind() != VectorType::AltiVecBool &&
5503 Second->getVectorKind() != VectorType::AltiVecPixel &&
5504 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005505 return true;
5506
5507 return false;
5508}
5509
Steve Naroff8e6aee52009-07-23 01:01:38 +00005510//===----------------------------------------------------------------------===//
5511// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5512//===----------------------------------------------------------------------===//
5513
5514/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5515/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00005516bool
5517ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5518 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00005519 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005520 return true;
5521 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5522 E = rProto->protocol_end(); PI != E; ++PI)
5523 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5524 return true;
5525 return false;
5526}
5527
Steve Naroff8e6aee52009-07-23 01:01:38 +00005528/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5529/// return true if lhs's protocols conform to rhs's protocol; false
5530/// otherwise.
5531bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5532 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5533 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5534 return false;
5535}
5536
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005537/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5538/// Class<p1, ...>.
5539bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5540 QualType rhs) {
5541 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5542 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5543 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5544
5545 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5546 E = lhsQID->qual_end(); I != E; ++I) {
5547 bool match = false;
5548 ObjCProtocolDecl *lhsProto = *I;
5549 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5550 E = rhsOPT->qual_end(); J != E; ++J) {
5551 ObjCProtocolDecl *rhsProto = *J;
5552 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5553 match = true;
5554 break;
5555 }
5556 }
5557 if (!match)
5558 return false;
5559 }
5560 return true;
5561}
5562
Steve Naroff8e6aee52009-07-23 01:01:38 +00005563/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5564/// ObjCQualifiedIDType.
5565bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5566 bool compare) {
5567 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00005568 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005569 lhs->isObjCIdType() || lhs->isObjCClassType())
5570 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005571 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005572 rhs->isObjCIdType() || rhs->isObjCClassType())
5573 return true;
5574
5575 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00005576 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005577
Steve Naroff8e6aee52009-07-23 01:01:38 +00005578 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00005579
Steve Naroff8e6aee52009-07-23 01:01:38 +00005580 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005581 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005582 // make sure we check the class hierarchy.
5583 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5584 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5585 E = lhsQID->qual_end(); I != E; ++I) {
5586 // when comparing an id<P> on lhs with a static type on rhs,
5587 // see if static class implements all of id's protocols, directly or
5588 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005589 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005590 return false;
5591 }
5592 }
5593 // If there are no qualifiers and no interface, we have an 'id'.
5594 return true;
5595 }
Mike Stump11289f42009-09-09 15:08:12 +00005596 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005597 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5598 E = lhsQID->qual_end(); I != E; ++I) {
5599 ObjCProtocolDecl *lhsProto = *I;
5600 bool match = false;
5601
5602 // when comparing an id<P> on lhs with a static type on rhs,
5603 // see if static class implements all of id's protocols, directly or
5604 // through its super class and categories.
5605 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5606 E = rhsOPT->qual_end(); J != E; ++J) {
5607 ObjCProtocolDecl *rhsProto = *J;
5608 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5609 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5610 match = true;
5611 break;
5612 }
5613 }
Mike Stump11289f42009-09-09 15:08:12 +00005614 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005615 // make sure we check the class hierarchy.
5616 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5617 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5618 E = lhsQID->qual_end(); I != E; ++I) {
5619 // when comparing an id<P> on lhs with a static type on rhs,
5620 // see if static class implements all of id's protocols, directly or
5621 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005622 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005623 match = true;
5624 break;
5625 }
5626 }
5627 }
5628 if (!match)
5629 return false;
5630 }
Mike Stump11289f42009-09-09 15:08:12 +00005631
Steve Naroff8e6aee52009-07-23 01:01:38 +00005632 return true;
5633 }
Mike Stump11289f42009-09-09 15:08:12 +00005634
Steve Naroff8e6aee52009-07-23 01:01:38 +00005635 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5636 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5637
Mike Stump11289f42009-09-09 15:08:12 +00005638 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00005639 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005640 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005641 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5642 E = lhsOPT->qual_end(); I != E; ++I) {
5643 ObjCProtocolDecl *lhsProto = *I;
5644 bool match = false;
5645
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005646 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00005647 // see if static class implements all of id's protocols, directly or
5648 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005649 // First, lhs protocols in the qualifier list must be found, direct
5650 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005651 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5652 E = rhsQID->qual_end(); J != E; ++J) {
5653 ObjCProtocolDecl *rhsProto = *J;
5654 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5655 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5656 match = true;
5657 break;
5658 }
5659 }
5660 if (!match)
5661 return false;
5662 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005663
5664 // Static class's protocols, or its super class or category protocols
5665 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5666 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5667 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5668 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5669 // This is rather dubious but matches gcc's behavior. If lhs has
5670 // no type qualifier and its class has no static protocol(s)
5671 // assume that it is mismatch.
5672 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5673 return false;
5674 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5675 LHSInheritedProtocols.begin(),
5676 E = LHSInheritedProtocols.end(); I != E; ++I) {
5677 bool match = false;
5678 ObjCProtocolDecl *lhsProto = (*I);
5679 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5680 E = rhsQID->qual_end(); J != E; ++J) {
5681 ObjCProtocolDecl *rhsProto = *J;
5682 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5683 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5684 match = true;
5685 break;
5686 }
5687 }
5688 if (!match)
5689 return false;
5690 }
5691 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00005692 return true;
5693 }
5694 return false;
5695}
5696
Eli Friedman47f77112008-08-22 00:56:42 +00005697/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005698/// compatible for assignment from RHS to LHS. This handles validation of any
5699/// protocol qualifiers on the LHS or RHS.
5700///
Steve Naroff7cae42b2009-07-10 23:34:53 +00005701bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5702 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00005703 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5704 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5705
Steve Naroff1329fa02009-07-15 18:40:39 +00005706 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00005707 if (LHS->isObjCUnqualifiedIdOrClass() ||
5708 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00005709 return true;
5710
John McCall8b07ec22010-05-15 11:32:37 +00005711 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00005712 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5713 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00005714 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005715
5716 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5717 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5718 QualType(RHSOPT,0));
5719
John McCall8b07ec22010-05-15 11:32:37 +00005720 // If we have 2 user-defined types, fall into that path.
5721 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00005722 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005723
Steve Naroff8e6aee52009-07-23 01:01:38 +00005724 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005725}
5726
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005727/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00005728/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005729/// arguments in block literals. When passed as arguments, passing 'A*' where
5730/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5731/// not OK. For the return type, the opposite is not OK.
5732bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5733 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005734 const ObjCObjectPointerType *RHSOPT,
5735 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005736 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005737 return true;
5738
5739 if (LHSOPT->isObjCBuiltinType()) {
5740 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5741 }
5742
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005743 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005744 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5745 QualType(RHSOPT,0),
5746 false);
5747
5748 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5749 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5750 if (LHS && RHS) { // We have 2 user-defined types.
5751 if (LHS != RHS) {
5752 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005753 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005754 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005755 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005756 }
5757 else
5758 return true;
5759 }
5760 return false;
5761}
5762
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005763/// getIntersectionOfProtocols - This routine finds the intersection of set
5764/// of protocols inherited from two distinct objective-c pointer objects.
5765/// It is used to build composite qualifier list of the composite type of
5766/// the conditional expression involving two objective-c pointer objects.
5767static
5768void getIntersectionOfProtocols(ASTContext &Context,
5769 const ObjCObjectPointerType *LHSOPT,
5770 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005771 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005772
John McCall8b07ec22010-05-15 11:32:37 +00005773 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5774 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5775 assert(LHS->getInterface() && "LHS must have an interface base");
5776 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005777
5778 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5779 unsigned LHSNumProtocols = LHS->getNumProtocols();
5780 if (LHSNumProtocols > 0)
5781 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5782 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005783 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005784 Context.CollectInheritedProtocols(LHS->getInterface(),
5785 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005786 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5787 LHSInheritedProtocols.end());
5788 }
5789
5790 unsigned RHSNumProtocols = RHS->getNumProtocols();
5791 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00005792 ObjCProtocolDecl **RHSProtocols =
5793 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005794 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5795 if (InheritedProtocolSet.count(RHSProtocols[i]))
5796 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00005797 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005798 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005799 Context.CollectInheritedProtocols(RHS->getInterface(),
5800 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005801 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5802 RHSInheritedProtocols.begin(),
5803 E = RHSInheritedProtocols.end(); I != E; ++I)
5804 if (InheritedProtocolSet.count((*I)))
5805 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005806 }
5807}
5808
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005809/// areCommonBaseCompatible - Returns common base class of the two classes if
5810/// one found. Note that this is O'2 algorithm. But it will be called as the
5811/// last type comparison in a ?-exp of ObjC pointer types before a
5812/// warning is issued. So, its invokation is extremely rare.
5813QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00005814 const ObjCObjectPointerType *Lptr,
5815 const ObjCObjectPointerType *Rptr) {
5816 const ObjCObjectType *LHS = Lptr->getObjectType();
5817 const ObjCObjectType *RHS = Rptr->getObjectType();
5818 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5819 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00005820 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005821 return QualType();
5822
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005823 do {
John McCall8b07ec22010-05-15 11:32:37 +00005824 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005825 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005826 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00005827 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5828
5829 QualType Result = QualType(LHS, 0);
5830 if (!Protocols.empty())
5831 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5832 Result = getObjCObjectPointerType(Result);
5833 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005834 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005835 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005836
5837 return QualType();
5838}
5839
John McCall8b07ec22010-05-15 11:32:37 +00005840bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5841 const ObjCObjectType *RHS) {
5842 assert(LHS->getInterface() && "LHS is not an interface type");
5843 assert(RHS->getInterface() && "RHS is not an interface type");
5844
Chris Lattner49af6a42008-04-07 06:51:04 +00005845 // Verify that the base decls are compatible: the RHS must be a subclass of
5846 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00005847 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00005848 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005849
Chris Lattner49af6a42008-04-07 06:51:04 +00005850 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5851 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00005852 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00005853 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005854
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005855 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5856 // more detailed analysis is required.
5857 if (RHS->getNumProtocols() == 0) {
5858 // OK, if LHS is a superclass of RHS *and*
5859 // this superclass is assignment compatible with LHS.
5860 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005861 bool IsSuperClass =
5862 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5863 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005864 // OK if conversion of LHS to SuperClass results in narrowing of types
5865 // ; i.e., SuperClass may implement at least one of the protocols
5866 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5867 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5868 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005869 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005870 // If super class has no protocols, it is not a match.
5871 if (SuperClassInheritedProtocols.empty())
5872 return false;
5873
5874 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5875 LHSPE = LHS->qual_end();
5876 LHSPI != LHSPE; LHSPI++) {
5877 bool SuperImplementsProtocol = false;
5878 ObjCProtocolDecl *LHSProto = (*LHSPI);
5879
5880 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5881 SuperClassInheritedProtocols.begin(),
5882 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5883 ObjCProtocolDecl *SuperClassProto = (*I);
5884 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5885 SuperImplementsProtocol = true;
5886 break;
5887 }
5888 }
5889 if (!SuperImplementsProtocol)
5890 return false;
5891 }
5892 return true;
5893 }
5894 return false;
5895 }
Mike Stump11289f42009-09-09 15:08:12 +00005896
John McCall8b07ec22010-05-15 11:32:37 +00005897 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5898 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00005899 LHSPI != LHSPE; LHSPI++) {
5900 bool RHSImplementsProtocol = false;
5901
5902 // If the RHS doesn't implement the protocol on the left, the types
5903 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00005904 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5905 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00005906 RHSPI != RHSPE; RHSPI++) {
5907 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00005908 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00005909 break;
5910 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005911 }
5912 // FIXME: For better diagnostics, consider passing back the protocol name.
5913 if (!RHSImplementsProtocol)
5914 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00005915 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005916 // The RHS implements all protocols listed on the LHS.
5917 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00005918}
5919
Steve Naroffb7605152009-02-12 17:52:19 +00005920bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5921 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00005922 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5923 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005924
Steve Naroff7cae42b2009-07-10 23:34:53 +00005925 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00005926 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005927
5928 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5929 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00005930}
5931
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005932bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5933 return canAssignObjCInterfaces(
5934 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5935 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5936}
5937
Mike Stump11289f42009-09-09 15:08:12 +00005938/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00005939/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00005940/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00005941/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005942bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5943 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005944 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00005945 return hasSameType(LHS, RHS);
5946
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005947 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00005948}
5949
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00005950bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00005951 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00005952}
5953
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005954bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5955 return !mergeTypes(LHS, RHS, true).isNull();
5956}
5957
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005958/// mergeTransparentUnionType - if T is a transparent union type and a member
5959/// of T is compatible with SubType, return the merged type, else return
5960/// QualType()
5961QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5962 bool OfBlockPointer,
5963 bool Unqualified) {
5964 if (const RecordType *UT = T->getAsUnionType()) {
5965 RecordDecl *UD = UT->getDecl();
5966 if (UD->hasAttr<TransparentUnionAttr>()) {
5967 for (RecordDecl::field_iterator it = UD->field_begin(),
5968 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00005969 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005970 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5971 if (!MT.isNull())
5972 return MT;
5973 }
5974 }
5975 }
5976
5977 return QualType();
5978}
5979
5980/// mergeFunctionArgumentTypes - merge two types which appear as function
5981/// argument types
5982QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5983 bool OfBlockPointer,
5984 bool Unqualified) {
5985 // GNU extension: two types are compatible if they appear as a function
5986 // argument, one of the types is a transparent union type and the other
5987 // type is compatible with a union member
5988 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5989 Unqualified);
5990 if (!lmerge.isNull())
5991 return lmerge;
5992
5993 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5994 Unqualified);
5995 if (!rmerge.isNull())
5996 return rmerge;
5997
5998 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5999}
6000
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006001QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006002 bool OfBlockPointer,
6003 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006004 const FunctionType *lbase = lhs->getAs<FunctionType>();
6005 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006006 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6007 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006008 bool allLTypes = true;
6009 bool allRTypes = true;
6010
6011 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006012 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006013 if (OfBlockPointer) {
6014 QualType RHS = rbase->getResultType();
6015 QualType LHS = lbase->getResultType();
6016 bool UnqualifiedResult = Unqualified;
6017 if (!UnqualifiedResult)
6018 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006019 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006020 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006021 else
John McCall8c6b56f2010-12-15 01:06:38 +00006022 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6023 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006024 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006025
6026 if (Unqualified)
6027 retType = retType.getUnqualifiedType();
6028
6029 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6030 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6031 if (Unqualified) {
6032 LRetType = LRetType.getUnqualifiedType();
6033 RRetType = RRetType.getUnqualifiedType();
6034 }
6035
6036 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006037 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006038 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006039 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006040
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006041 // FIXME: double check this
6042 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6043 // rbase->getRegParmAttr() != 0 &&
6044 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006045 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6046 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006047
Douglas Gregor8c940862010-01-18 17:14:39 +00006048 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00006049 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00006050 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006051
John McCall8c6b56f2010-12-15 01:06:38 +00006052 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006053 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6054 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006055 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6056 return QualType();
6057
John McCall31168b02011-06-15 23:02:42 +00006058 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6059 return QualType();
6060
Fariborz Jahanian48c69102011-10-05 00:05:34 +00006061 // functypes which return are preferred over those that do not.
6062 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
6063 allLTypes = false;
6064 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
6065 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006066 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6067 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006068
John McCall31168b02011-06-15 23:02:42 +00006069 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006070
Eli Friedman47f77112008-08-22 00:56:42 +00006071 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006072 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6073 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006074 unsigned lproto_nargs = lproto->getNumArgs();
6075 unsigned rproto_nargs = rproto->getNumArgs();
6076
6077 // Compatible functions must have the same number of arguments
6078 if (lproto_nargs != rproto_nargs)
6079 return QualType();
6080
6081 // Variadic and non-variadic functions aren't compatible
6082 if (lproto->isVariadic() != rproto->isVariadic())
6083 return QualType();
6084
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006085 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6086 return QualType();
6087
Fariborz Jahanian97676972011-09-28 21:52:05 +00006088 if (LangOpts.ObjCAutoRefCount &&
6089 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6090 return QualType();
6091
Eli Friedman47f77112008-08-22 00:56:42 +00006092 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006093 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00006094 for (unsigned i = 0; i < lproto_nargs; i++) {
6095 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6096 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006097 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6098 OfBlockPointer,
6099 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006100 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006101
6102 if (Unqualified)
6103 argtype = argtype.getUnqualifiedType();
6104
Eli Friedman47f77112008-08-22 00:56:42 +00006105 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006106 if (Unqualified) {
6107 largtype = largtype.getUnqualifiedType();
6108 rargtype = rargtype.getUnqualifiedType();
6109 }
6110
Chris Lattner465fa322008-10-05 17:34:18 +00006111 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6112 allLTypes = false;
6113 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6114 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006115 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006116
Eli Friedman47f77112008-08-22 00:56:42 +00006117 if (allLTypes) return lhs;
6118 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006119
6120 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6121 EPI.ExtInfo = einfo;
6122 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006123 }
6124
6125 if (lproto) allRTypes = false;
6126 if (rproto) allLTypes = false;
6127
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006128 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006129 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006130 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006131 if (proto->isVariadic()) return QualType();
6132 // Check that the types are compatible with the types that
6133 // would result from default argument promotions (C99 6.7.5.3p15).
6134 // The only types actually affected are promotable integer
6135 // types and floats, which would be passed as a different
6136 // type depending on whether the prototype is visible.
6137 unsigned proto_nargs = proto->getNumArgs();
6138 for (unsigned i = 0; i < proto_nargs; ++i) {
6139 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00006140
6141 // Look at the promotion type of enum types, since that is the type used
6142 // to pass enum values.
6143 if (const EnumType *Enum = argTy->getAs<EnumType>())
6144 argTy = Enum->getDecl()->getPromotionType();
6145
Eli Friedman47f77112008-08-22 00:56:42 +00006146 if (argTy->isPromotableIntegerType() ||
6147 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6148 return QualType();
6149 }
6150
6151 if (allLTypes) return lhs;
6152 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006153
6154 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6155 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00006156 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006157 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006158 }
6159
6160 if (allLTypes) return lhs;
6161 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00006162 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00006163}
6164
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006165QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006166 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006167 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00006168 // C++ [expr]: If an expression initially has the type "reference to T", the
6169 // type is adjusted to "T" prior to any further analysis, the expression
6170 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006171 // expression is an lvalue unless the reference is an rvalue reference and
6172 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00006173 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6174 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006175
6176 if (Unqualified) {
6177 LHS = LHS.getUnqualifiedType();
6178 RHS = RHS.getUnqualifiedType();
6179 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00006180
Eli Friedman47f77112008-08-22 00:56:42 +00006181 QualType LHSCan = getCanonicalType(LHS),
6182 RHSCan = getCanonicalType(RHS);
6183
6184 // If two types are identical, they are compatible.
6185 if (LHSCan == RHSCan)
6186 return LHS;
6187
John McCall8ccfcb52009-09-24 19:53:00 +00006188 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006189 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6190 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00006191 if (LQuals != RQuals) {
6192 // If any of these qualifiers are different, we have a type
6193 // mismatch.
6194 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00006195 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6196 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00006197 return QualType();
6198
6199 // Exactly one GC qualifier difference is allowed: __strong is
6200 // okay if the other type has no GC qualifier but is an Objective
6201 // C object pointer (i.e. implicitly strong by default). We fix
6202 // this by pretending that the unqualified type was actually
6203 // qualified __strong.
6204 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6205 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6206 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6207
6208 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6209 return QualType();
6210
6211 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6212 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6213 }
6214 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6215 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6216 }
Eli Friedman47f77112008-08-22 00:56:42 +00006217 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00006218 }
6219
6220 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00006221
Eli Friedmandcca6332009-06-01 01:22:52 +00006222 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6223 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00006224
Chris Lattnerfd652912008-01-14 05:45:46 +00006225 // We want to consider the two function types to be the same for these
6226 // comparisons, just force one to the other.
6227 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6228 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00006229
6230 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00006231 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6232 LHSClass = Type::ConstantArray;
6233 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6234 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00006235
John McCall8b07ec22010-05-15 11:32:37 +00006236 // ObjCInterfaces are just specialized ObjCObjects.
6237 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6238 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6239
Nate Begemance4d7fc2008-04-18 23:10:10 +00006240 // Canonicalize ExtVector -> Vector.
6241 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6242 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00006243
Chris Lattner95554662008-04-07 05:43:21 +00006244 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006245 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00006246 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00006247 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00006248 // Compatibility is based on the underlying type, not the promotion
6249 // type.
John McCall9dd450b2009-09-21 23:43:11 +00006250 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006251 QualType TINT = ETy->getDecl()->getIntegerType();
6252 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006253 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006254 }
John McCall9dd450b2009-09-21 23:43:11 +00006255 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006256 QualType TINT = ETy->getDecl()->getIntegerType();
6257 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006258 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006259 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006260 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00006261 if (OfBlockPointer && !BlockReturnType) {
6262 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6263 return LHS;
6264 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6265 return RHS;
6266 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006267
Eli Friedman47f77112008-08-22 00:56:42 +00006268 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00006269 }
Eli Friedman47f77112008-08-22 00:56:42 +00006270
Steve Naroffc6edcbd2008-01-09 22:43:08 +00006271 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006272 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006273#define TYPE(Class, Base)
6274#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00006275#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006276#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6277#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6278#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00006279 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006280
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006281 case Type::LValueReference:
6282 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006283 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00006284 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006285
John McCall8b07ec22010-05-15 11:32:37 +00006286 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006287 case Type::IncompleteArray:
6288 case Type::VariableArray:
6289 case Type::FunctionProto:
6290 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00006291 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006292
Chris Lattnerfd652912008-01-14 05:45:46 +00006293 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00006294 {
6295 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006296 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6297 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006298 if (Unqualified) {
6299 LHSPointee = LHSPointee.getUnqualifiedType();
6300 RHSPointee = RHSPointee.getUnqualifiedType();
6301 }
6302 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6303 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006304 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00006305 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006306 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00006307 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006308 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006309 return getPointerType(ResultType);
6310 }
Steve Naroff68e167d2008-12-10 17:49:55 +00006311 case Type::BlockPointer:
6312 {
6313 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006314 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6315 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006316 if (Unqualified) {
6317 LHSPointee = LHSPointee.getUnqualifiedType();
6318 RHSPointee = RHSPointee.getUnqualifiedType();
6319 }
6320 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6321 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00006322 if (ResultType.isNull()) return QualType();
6323 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6324 return LHS;
6325 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6326 return RHS;
6327 return getBlockPointerType(ResultType);
6328 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00006329 case Type::Atomic:
6330 {
6331 // Merge two pointer types, while trying to preserve typedef info
6332 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6333 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6334 if (Unqualified) {
6335 LHSValue = LHSValue.getUnqualifiedType();
6336 RHSValue = RHSValue.getUnqualifiedType();
6337 }
6338 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6339 Unqualified);
6340 if (ResultType.isNull()) return QualType();
6341 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6342 return LHS;
6343 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6344 return RHS;
6345 return getAtomicType(ResultType);
6346 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006347 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00006348 {
6349 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6350 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6351 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6352 return QualType();
6353
6354 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6355 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006356 if (Unqualified) {
6357 LHSElem = LHSElem.getUnqualifiedType();
6358 RHSElem = RHSElem.getUnqualifiedType();
6359 }
6360
6361 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006362 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00006363 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6364 return LHS;
6365 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6366 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00006367 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6368 ArrayType::ArraySizeModifier(), 0);
6369 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6370 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006371 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6372 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00006373 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6374 return LHS;
6375 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6376 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006377 if (LVAT) {
6378 // FIXME: This isn't correct! But tricky to implement because
6379 // the array's size has to be the size of LHS, but the type
6380 // has to be different.
6381 return LHS;
6382 }
6383 if (RVAT) {
6384 // FIXME: This isn't correct! But tricky to implement because
6385 // the array's size has to be the size of RHS, but the type
6386 // has to be different.
6387 return RHS;
6388 }
Eli Friedman3e62c212008-08-22 01:48:21 +00006389 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6390 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00006391 return getIncompleteArrayType(ResultType,
6392 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006393 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006394 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006395 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006396 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006397 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00006398 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00006399 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006400 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00006401 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00006402 case Type::Complex:
6403 // Distinct complex types are incompatible.
6404 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006405 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00006406 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00006407 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6408 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00006409 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00006410 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00006411 case Type::ObjCObject: {
6412 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00006413 // FIXME: This should be type compatibility, e.g. whether
6414 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00006415 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6416 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6417 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00006418 return LHS;
6419
Eli Friedman47f77112008-08-22 00:56:42 +00006420 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00006421 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006422 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006423 if (OfBlockPointer) {
6424 if (canAssignObjCInterfacesInBlockPointer(
6425 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006426 RHS->getAs<ObjCObjectPointerType>(),
6427 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00006428 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006429 return QualType();
6430 }
John McCall9dd450b2009-09-21 23:43:11 +00006431 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6432 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006433 return LHS;
6434
Steve Naroffc68cfcf2008-12-10 22:14:21 +00006435 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00006436 }
Steve Naroff32e44c02007-10-15 20:41:53 +00006437 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006438
David Blaikie8a40f702012-01-17 06:56:22 +00006439 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00006440}
Ted Kremenekfc581a92007-10-31 17:10:13 +00006441
Fariborz Jahanian97676972011-09-28 21:52:05 +00006442bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6443 const FunctionProtoType *FromFunctionType,
6444 const FunctionProtoType *ToFunctionType) {
6445 if (FromFunctionType->hasAnyConsumedArgs() !=
6446 ToFunctionType->hasAnyConsumedArgs())
6447 return false;
6448 FunctionProtoType::ExtProtoInfo FromEPI =
6449 FromFunctionType->getExtProtoInfo();
6450 FunctionProtoType::ExtProtoInfo ToEPI =
6451 ToFunctionType->getExtProtoInfo();
6452 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6453 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6454 ArgIdx != NumArgs; ++ArgIdx) {
6455 if (FromEPI.ConsumedArguments[ArgIdx] !=
6456 ToEPI.ConsumedArguments[ArgIdx])
6457 return false;
6458 }
6459 return true;
6460}
6461
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006462/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6463/// 'RHS' attributes and returns the merged version; including for function
6464/// return types.
6465QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6466 QualType LHSCan = getCanonicalType(LHS),
6467 RHSCan = getCanonicalType(RHS);
6468 // If two types are identical, they are compatible.
6469 if (LHSCan == RHSCan)
6470 return LHS;
6471 if (RHSCan->isFunctionType()) {
6472 if (!LHSCan->isFunctionType())
6473 return QualType();
6474 QualType OldReturnType =
6475 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6476 QualType NewReturnType =
6477 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6478 QualType ResReturnType =
6479 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6480 if (ResReturnType.isNull())
6481 return QualType();
6482 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6483 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6484 // In either case, use OldReturnType to build the new function type.
6485 const FunctionType *F = LHS->getAs<FunctionType>();
6486 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00006487 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6488 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006489 QualType ResultType
6490 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006491 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006492 return ResultType;
6493 }
6494 }
6495 return QualType();
6496 }
6497
6498 // If the qualifiers are different, the types can still be merged.
6499 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6500 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6501 if (LQuals != RQuals) {
6502 // If any of these qualifiers are different, we have a type mismatch.
6503 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6504 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6505 return QualType();
6506
6507 // Exactly one GC qualifier difference is allowed: __strong is
6508 // okay if the other type has no GC qualifier but is an Objective
6509 // C object pointer (i.e. implicitly strong by default). We fix
6510 // this by pretending that the unqualified type was actually
6511 // qualified __strong.
6512 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6513 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6514 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6515
6516 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6517 return QualType();
6518
6519 if (GC_L == Qualifiers::Strong)
6520 return LHS;
6521 if (GC_R == Qualifiers::Strong)
6522 return RHS;
6523 return QualType();
6524 }
6525
6526 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6527 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6528 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6529 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6530 if (ResQT == LHSBaseQT)
6531 return LHS;
6532 if (ResQT == RHSBaseQT)
6533 return RHS;
6534 }
6535 return QualType();
6536}
6537
Chris Lattner4ba0cef2008-04-07 07:01:58 +00006538//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006539// Integer Predicates
6540//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00006541
Jay Foad39c79802011-01-12 09:06:06 +00006542unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00006543 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00006544 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00006545 if (T->isBooleanType())
6546 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00006547 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006548 return (unsigned)getTypeSize(T);
6549}
6550
6551QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006552 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00006553
6554 // Turn <4 x signed int> -> <4 x unsigned int>
6555 if (const VectorType *VTy = T->getAs<VectorType>())
6556 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00006557 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00006558
6559 // For enums, we return the unsigned version of the base type.
6560 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006561 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00006562
6563 const BuiltinType *BTy = T->getAs<BuiltinType>();
6564 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006565 switch (BTy->getKind()) {
6566 case BuiltinType::Char_S:
6567 case BuiltinType::SChar:
6568 return UnsignedCharTy;
6569 case BuiltinType::Short:
6570 return UnsignedShortTy;
6571 case BuiltinType::Int:
6572 return UnsignedIntTy;
6573 case BuiltinType::Long:
6574 return UnsignedLongTy;
6575 case BuiltinType::LongLong:
6576 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00006577 case BuiltinType::Int128:
6578 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006579 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006580 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006581 }
6582}
6583
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00006584ASTMutationListener::~ASTMutationListener() { }
6585
Chris Lattnerecd79c62009-06-14 00:45:47 +00006586
6587//===----------------------------------------------------------------------===//
6588// Builtin Type Computation
6589//===----------------------------------------------------------------------===//
6590
6591/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00006592/// pointer over the consumed characters. This returns the resultant type. If
6593/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6594/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6595/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006596///
6597/// RequiresICE is filled in on return to indicate whether the value is required
6598/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00006599static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00006600 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006601 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00006602 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00006603 // Modifiers.
6604 int HowLong = 0;
6605 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006606 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00006607
Chris Lattnerdc226c22010-10-01 22:42:38 +00006608 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00006609 bool Done = false;
6610 while (!Done) {
6611 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00006612 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00006613 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006614 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00006615 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006616 case 'S':
6617 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6618 assert(!Signed && "Can't use 'S' modifier multiple times!");
6619 Signed = true;
6620 break;
6621 case 'U':
6622 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6623 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6624 Unsigned = true;
6625 break;
6626 case 'L':
6627 assert(HowLong <= 2 && "Can't have LLLL modifier");
6628 ++HowLong;
6629 break;
6630 }
6631 }
6632
6633 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00006634
Chris Lattnerecd79c62009-06-14 00:45:47 +00006635 // Read the base type.
6636 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00006637 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006638 case 'v':
6639 assert(HowLong == 0 && !Signed && !Unsigned &&
6640 "Bad modifiers used with 'v'!");
6641 Type = Context.VoidTy;
6642 break;
6643 case 'f':
6644 assert(HowLong == 0 && !Signed && !Unsigned &&
6645 "Bad modifiers used with 'f'!");
6646 Type = Context.FloatTy;
6647 break;
6648 case 'd':
6649 assert(HowLong < 2 && !Signed && !Unsigned &&
6650 "Bad modifiers used with 'd'!");
6651 if (HowLong)
6652 Type = Context.LongDoubleTy;
6653 else
6654 Type = Context.DoubleTy;
6655 break;
6656 case 's':
6657 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6658 if (Unsigned)
6659 Type = Context.UnsignedShortTy;
6660 else
6661 Type = Context.ShortTy;
6662 break;
6663 case 'i':
6664 if (HowLong == 3)
6665 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6666 else if (HowLong == 2)
6667 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6668 else if (HowLong == 1)
6669 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6670 else
6671 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6672 break;
6673 case 'c':
6674 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6675 if (Signed)
6676 Type = Context.SignedCharTy;
6677 else if (Unsigned)
6678 Type = Context.UnsignedCharTy;
6679 else
6680 Type = Context.CharTy;
6681 break;
6682 case 'b': // boolean
6683 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6684 Type = Context.BoolTy;
6685 break;
6686 case 'z': // size_t.
6687 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6688 Type = Context.getSizeType();
6689 break;
6690 case 'F':
6691 Type = Context.getCFConstantStringType();
6692 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00006693 case 'G':
6694 Type = Context.getObjCIdType();
6695 break;
6696 case 'H':
6697 Type = Context.getObjCSelType();
6698 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006699 case 'a':
6700 Type = Context.getBuiltinVaListType();
6701 assert(!Type.isNull() && "builtin va list type not initialized!");
6702 break;
6703 case 'A':
6704 // This is a "reference" to a va_list; however, what exactly
6705 // this means depends on how va_list is defined. There are two
6706 // different kinds of va_list: ones passed by value, and ones
6707 // passed by reference. An example of a by-value va_list is
6708 // x86, where va_list is a char*. An example of by-ref va_list
6709 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6710 // we want this argument to be a char*&; for x86-64, we want
6711 // it to be a __va_list_tag*.
6712 Type = Context.getBuiltinVaListType();
6713 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006714 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00006715 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006716 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00006717 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006718 break;
6719 case 'V': {
6720 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006721 unsigned NumElements = strtoul(Str, &End, 10);
6722 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006723 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00006724
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006725 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6726 RequiresICE, false);
6727 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00006728
6729 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00006730 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00006731 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006732 break;
6733 }
Douglas Gregorfed66992012-06-07 18:08:25 +00006734 case 'E': {
6735 char *End;
6736
6737 unsigned NumElements = strtoul(Str, &End, 10);
6738 assert(End != Str && "Missing vector size");
6739
6740 Str = End;
6741
6742 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6743 false);
6744 Type = Context.getExtVectorType(ElementType, NumElements);
6745 break;
6746 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006747 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006748 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6749 false);
6750 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006751 Type = Context.getComplexType(ElementType);
6752 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00006753 }
6754 case 'Y' : {
6755 Type = Context.getPointerDiffType();
6756 break;
6757 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00006758 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00006759 Type = Context.getFILEType();
6760 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006761 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006762 return QualType();
6763 }
Mike Stump2adb4da2009-07-28 23:47:15 +00006764 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00006765 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00006766 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00006767 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00006768 else
6769 Type = Context.getjmp_bufType();
6770
Mike Stump2adb4da2009-07-28 23:47:15 +00006771 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006772 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00006773 return QualType();
6774 }
6775 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00006776 case 'K':
6777 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
6778 Type = Context.getucontext_tType();
6779
6780 if (Type.isNull()) {
6781 Error = ASTContext::GE_Missing_ucontext;
6782 return QualType();
6783 }
6784 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00006785 }
Mike Stump11289f42009-09-09 15:08:12 +00006786
Chris Lattnerdc226c22010-10-01 22:42:38 +00006787 // If there are modifiers and if we're allowed to parse them, go for it.
6788 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006789 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00006790 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006791 default: Done = true; --Str; break;
6792 case '*':
6793 case '&': {
6794 // Both pointers and references can have their pointee types
6795 // qualified with an address space.
6796 char *End;
6797 unsigned AddrSpace = strtoul(Str, &End, 10);
6798 if (End != Str && AddrSpace != 0) {
6799 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6800 Str = End;
6801 }
6802 if (c == '*')
6803 Type = Context.getPointerType(Type);
6804 else
6805 Type = Context.getLValueReferenceType(Type);
6806 break;
6807 }
6808 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6809 case 'C':
6810 Type = Type.withConst();
6811 break;
6812 case 'D':
6813 Type = Context.getVolatileType(Type);
6814 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00006815 case 'R':
6816 Type = Type.withRestrict();
6817 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006818 }
6819 }
Chris Lattner84733392010-10-01 07:13:18 +00006820
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006821 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00006822 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00006823
Chris Lattnerecd79c62009-06-14 00:45:47 +00006824 return Type;
6825}
6826
6827/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00006828QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006829 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00006830 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006831 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00006832
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006833 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00006834
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006835 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006836 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006837 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6838 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006839 if (Error != GE_None)
6840 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006841
6842 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6843
Chris Lattnerecd79c62009-06-14 00:45:47 +00006844 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006845 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006846 if (Error != GE_None)
6847 return QualType();
6848
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006849 // If this argument is required to be an IntegerConstantExpression and the
6850 // caller cares, fill in the bitmask we return.
6851 if (RequiresICE && IntegerConstantArgs)
6852 *IntegerConstantArgs |= 1 << ArgTypes.size();
6853
Chris Lattnerecd79c62009-06-14 00:45:47 +00006854 // Do array -> pointer decay. The builtin should use the decayed type.
6855 if (Ty->isArrayType())
6856 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00006857
Chris Lattnerecd79c62009-06-14 00:45:47 +00006858 ArgTypes.push_back(Ty);
6859 }
6860
6861 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6862 "'.' should only occur at end of builtin type list!");
6863
John McCall991eb4b2010-12-21 00:44:39 +00006864 FunctionType::ExtInfo EI;
6865 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6866
6867 bool Variadic = (TypeStr[0] == '.');
6868
6869 // We really shouldn't be making a no-proto type here, especially in C++.
6870 if (ArgTypes.empty() && Variadic)
6871 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00006872
John McCalldb40c7f2010-12-14 08:05:40 +00006873 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00006874 EPI.ExtInfo = EI;
6875 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00006876
6877 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006878}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00006879
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006880GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6881 GVALinkage External = GVA_StrongExternal;
6882
6883 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006884 switch (L) {
6885 case NoLinkage:
6886 case InternalLinkage:
6887 case UniqueExternalLinkage:
6888 return GVA_Internal;
6889
6890 case ExternalLinkage:
6891 switch (FD->getTemplateSpecializationKind()) {
6892 case TSK_Undeclared:
6893 case TSK_ExplicitSpecialization:
6894 External = GVA_StrongExternal;
6895 break;
6896
6897 case TSK_ExplicitInstantiationDefinition:
6898 return GVA_ExplicitTemplateInstantiation;
6899
6900 case TSK_ExplicitInstantiationDeclaration:
6901 case TSK_ImplicitInstantiation:
6902 External = GVA_TemplateInstantiation;
6903 break;
6904 }
6905 }
6906
6907 if (!FD->isInlined())
6908 return External;
6909
David Blaikiebbafb8a2012-03-11 07:00:24 +00006910 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006911 // GNU or C99 inline semantics. Determine whether this symbol should be
6912 // externally visible.
6913 if (FD->isInlineDefinitionExternallyVisible())
6914 return External;
6915
6916 // C99 inline semantics, where the symbol is not externally visible.
6917 return GVA_C99Inline;
6918 }
6919
6920 // C++0x [temp.explicit]p9:
6921 // [ Note: The intent is that an inline function that is the subject of
6922 // an explicit instantiation declaration will still be implicitly
6923 // instantiated when used so that the body can be considered for
6924 // inlining, but that no out-of-line copy of the inline function would be
6925 // generated in the translation unit. -- end note ]
6926 if (FD->getTemplateSpecializationKind()
6927 == TSK_ExplicitInstantiationDeclaration)
6928 return GVA_C99Inline;
6929
6930 return GVA_CXXInline;
6931}
6932
6933GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6934 // If this is a static data member, compute the kind of template
6935 // specialization. Otherwise, this variable is not part of a
6936 // template.
6937 TemplateSpecializationKind TSK = TSK_Undeclared;
6938 if (VD->isStaticDataMember())
6939 TSK = VD->getTemplateSpecializationKind();
6940
6941 Linkage L = VD->getLinkage();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006942 if (L == ExternalLinkage && getLangOpts().CPlusPlus &&
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006943 VD->getType()->getLinkage() == UniqueExternalLinkage)
6944 L = UniqueExternalLinkage;
6945
6946 switch (L) {
6947 case NoLinkage:
6948 case InternalLinkage:
6949 case UniqueExternalLinkage:
6950 return GVA_Internal;
6951
6952 case ExternalLinkage:
6953 switch (TSK) {
6954 case TSK_Undeclared:
6955 case TSK_ExplicitSpecialization:
6956 return GVA_StrongExternal;
6957
6958 case TSK_ExplicitInstantiationDeclaration:
6959 llvm_unreachable("Variable should not be instantiated");
6960 // Fall through to treat this like any other instantiation.
6961
6962 case TSK_ExplicitInstantiationDefinition:
6963 return GVA_ExplicitTemplateInstantiation;
6964
6965 case TSK_ImplicitInstantiation:
6966 return GVA_TemplateInstantiation;
6967 }
6968 }
6969
David Blaikie8a40f702012-01-17 06:56:22 +00006970 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006971}
6972
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00006973bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006974 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6975 if (!VD->isFileVarDecl())
6976 return false;
Argyrios Kyrtzidisa98e8612011-09-13 21:35:00 +00006977 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006978 return false;
6979
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006980 // Weak references don't produce any output by themselves.
6981 if (D->hasAttr<WeakRefAttr>())
6982 return false;
6983
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006984 // Aliases and used decls are required.
6985 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6986 return true;
6987
6988 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6989 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00006990 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00006991 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006992
6993 // Constructors and destructors are required.
6994 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6995 return true;
6996
6997 // The key function for a class is required.
6998 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6999 const CXXRecordDecl *RD = MD->getParent();
7000 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7001 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
7002 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7003 return true;
7004 }
7005 }
7006
7007 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7008
7009 // static, static inline, always_inline, and extern inline functions can
7010 // always be deferred. Normal inline functions can be deferred in C99/C++.
7011 // Implicit template instantiations can also be deferred in C++.
7012 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007013 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007014 return false;
7015 return true;
7016 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007017
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007018 const VarDecl *VD = cast<VarDecl>(D);
7019 assert(VD->isFileVarDecl() && "Expected file scoped var");
7020
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007021 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7022 return false;
7023
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007024 // Structs that have non-trivial constructors or destructors are required.
7025
7026 // FIXME: Handle references.
Alexis Huntf479f1b2011-05-09 18:22:59 +00007027 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007028 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
7029 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Alexis Huntf479f1b2011-05-09 18:22:59 +00007030 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
7031 RD->hasTrivialCopyConstructor() &&
7032 RD->hasTrivialMoveConstructor() &&
7033 RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007034 return true;
7035 }
7036 }
7037
7038 GVALinkage L = GetGVALinkageForVariable(VD);
7039 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
7040 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
7041 return false;
7042 }
7043
7044 return true;
7045}
Charles Davis53c59df2010-08-16 03:33:14 +00007046
Charles Davis99202b32010-11-09 18:04:24 +00007047CallingConv ASTContext::getDefaultMethodCallConv() {
7048 // Pass through to the C++ ABI object
7049 return ABI->getDefaultMethodCallConv();
7050}
7051
Jay Foad39c79802011-01-12 09:06:06 +00007052bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007053 // Pass through to the C++ ABI object
7054 return ABI->isNearlyEmpty(RD);
7055}
7056
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007057MangleContext *ASTContext::createMangleContext() {
Douglas Gregore8bbc122011-09-02 00:18:52 +00007058 switch (Target->getCXXABI()) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007059 case CXXABI_ARM:
7060 case CXXABI_Itanium:
7061 return createItaniumMangleContext(*this, getDiagnostics());
7062 case CXXABI_Microsoft:
7063 return createMicrosoftMangleContext(*this, getDiagnostics());
7064 }
David Blaikie83d382b2011-09-23 05:06:16 +00007065 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007066}
7067
Charles Davis53c59df2010-08-16 03:33:14 +00007068CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007069
7070size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00007071 return ASTRecordLayouts.getMemorySize()
7072 + llvm::capacity_in_bytes(ObjCLayouts)
7073 + llvm::capacity_in_bytes(KeyFunctions)
7074 + llvm::capacity_in_bytes(ObjCImpls)
7075 + llvm::capacity_in_bytes(BlockVarCopyInits)
7076 + llvm::capacity_in_bytes(DeclAttrs)
7077 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7078 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7079 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7080 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7081 + llvm::capacity_in_bytes(OverriddenMethods)
7082 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007083 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00007084 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007085}
Ted Kremenek540017e2011-10-06 05:00:56 +00007086
Douglas Gregor63798542012-02-20 19:44:39 +00007087unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7088 CXXRecordDecl *Lambda = CallOperator->getParent();
7089 return LambdaMangleContexts[Lambda->getDeclContext()]
7090 .getManglingNumber(CallOperator);
7091}
7092
7093
Ted Kremenek540017e2011-10-06 05:00:56 +00007094void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7095 ParamIndices[D] = index;
7096}
7097
7098unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7099 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7100 assert(I != ParamIndices.end() &&
7101 "ParmIndices lacks entry set by ParmVarDecl");
7102 return I->second;
7103}