blob: d8677c2ee1baf81507520a849e4e3cc06276e923 [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
64 // TODO: handle comments for function parameters properly.
65 if (isa<ParmVarDecl>(D))
66 return NULL;
67
68 ArrayRef<RawComment> RawComments = Comments.getComments();
69
70 // If there are no comments anywhere, we won't find anything.
71 if (RawComments.empty())
72 return NULL;
73
74 // If the declaration doesn't map directly to a location in a file, we
75 // can't find the comment.
76 SourceLocation DeclLoc = D->getLocation();
77 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
78 return NULL;
79
80 // Find the comment that occurs just after this declaration.
81 ArrayRef<RawComment>::iterator Comment
82 = std::lower_bound(RawComments.begin(),
83 RawComments.end(),
84 SourceRange(DeclLoc),
85 BeforeThanCompare<RawComment>(SourceMgr));
86
87 // Decompose the location for the declaration and find the beginning of the
88 // file buffer.
89 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
90
91 // First check whether we have a trailing comment.
92 if (Comment != RawComments.end() &&
93 Comment->isDoxygen() && Comment->isTrailingComment() &&
94 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D)) {
95 std::pair<FileID, unsigned> CommentBeginDecomp
96 = SourceMgr.getDecomposedLoc(Comment->getSourceRange().getBegin());
97 // Check that Doxygen trailing comment comes after the declaration, starts
98 // on the same line and in the same file as the declaration.
99 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
100 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
101 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
102 CommentBeginDecomp.second)) {
103 return &*Comment;
104 }
105 }
106
107 // The comment just after the declaration was not a trailing comment.
108 // Let's look at the previous comment.
109 if (Comment == RawComments.begin())
110 return NULL;
111 --Comment;
112
113 // Check that we actually have a non-member Doxygen comment.
114 if (!Comment->isDoxygen() || Comment->isTrailingComment())
115 return NULL;
116
117 // Decompose the end of the comment.
118 std::pair<FileID, unsigned> CommentEndDecomp
119 = SourceMgr.getDecomposedLoc(Comment->getSourceRange().getEnd());
120
121 // If the comment and the declaration aren't in the same file, then they
122 // aren't related.
123 if (DeclLocDecomp.first != CommentEndDecomp.first)
124 return NULL;
125
126 // Get the corresponding buffer.
127 bool Invalid = false;
128 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
129 &Invalid).data();
130 if (Invalid)
131 return NULL;
132
133 // Extract text between the comment and declaration.
134 StringRef Text(Buffer + CommentEndDecomp.second,
135 DeclLocDecomp.second - CommentEndDecomp.second);
136
137 // There should be no other declarations between comment and declaration.
138 if (Text.find_first_of(",;{}") != StringRef::npos)
139 return NULL;
140
141 return &*Comment;
142}
143
144const RawComment *ASTContext::getRawCommentForDecl(const Decl *D) const {
145 // Check whether we have cached a comment string for this declaration
146 // already.
147 llvm::DenseMap<const Decl *, const RawComment *>::iterator Pos
148 = DeclComments.find(D);
149 if (Pos != DeclComments.end())
150 return Pos->second;
151
152 const RawComment *RC = getRawCommentForDeclNoCache(D);
153 DeclComments[D] = RC;
154 return RC;
155}
156
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000157void
158ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
159 TemplateTemplateParmDecl *Parm) {
160 ID.AddInteger(Parm->getDepth());
161 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000162 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000163
164 TemplateParameterList *Params = Parm->getTemplateParameters();
165 ID.AddInteger(Params->size());
166 for (TemplateParameterList::const_iterator P = Params->begin(),
167 PEnd = Params->end();
168 P != PEnd; ++P) {
169 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
170 ID.AddInteger(0);
171 ID.AddBoolean(TTP->isParameterPack());
172 continue;
173 }
174
175 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
176 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000177 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000178 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000179 if (NTTP->isExpandedParameterPack()) {
180 ID.AddBoolean(true);
181 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000182 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
183 QualType T = NTTP->getExpansionType(I);
184 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
185 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000186 } else
187 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000188 continue;
189 }
190
191 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
192 ID.AddInteger(2);
193 Profile(ID, TTP);
194 }
195}
196
197TemplateTemplateParmDecl *
198ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000199 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000200 // Check if we already have a canonical template template parameter.
201 llvm::FoldingSetNodeID ID;
202 CanonicalTemplateTemplateParm::Profile(ID, TTP);
203 void *InsertPos = 0;
204 CanonicalTemplateTemplateParm *Canonical
205 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
206 if (Canonical)
207 return Canonical->getParam();
208
209 // Build a canonical template parameter list.
210 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000211 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000212 CanonParams.reserve(Params->size());
213 for (TemplateParameterList::const_iterator P = Params->begin(),
214 PEnd = Params->end();
215 P != PEnd; ++P) {
216 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
217 CanonParams.push_back(
218 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000219 SourceLocation(),
220 SourceLocation(),
221 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000222 TTP->getIndex(), 0, false,
223 TTP->isParameterPack()));
224 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000225 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
226 QualType T = getCanonicalType(NTTP->getType());
227 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
228 NonTypeTemplateParmDecl *Param;
229 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000230 SmallVector<QualType, 2> ExpandedTypes;
231 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000232 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
233 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
234 ExpandedTInfos.push_back(
235 getTrivialTypeSourceInfo(ExpandedTypes.back()));
236 }
237
238 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000239 SourceLocation(),
240 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000241 NTTP->getDepth(),
242 NTTP->getPosition(), 0,
243 T,
244 TInfo,
245 ExpandedTypes.data(),
246 ExpandedTypes.size(),
247 ExpandedTInfos.data());
248 } else {
249 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000250 SourceLocation(),
251 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000252 NTTP->getDepth(),
253 NTTP->getPosition(), 0,
254 T,
255 NTTP->isParameterPack(),
256 TInfo);
257 }
258 CanonParams.push_back(Param);
259
260 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000261 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
262 cast<TemplateTemplateParmDecl>(*P)));
263 }
264
265 TemplateTemplateParmDecl *CanonTTP
266 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
267 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000268 TTP->getPosition(),
269 TTP->isParameterPack(),
270 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000271 TemplateParameterList::Create(*this, SourceLocation(),
272 SourceLocation(),
273 CanonParams.data(),
274 CanonParams.size(),
275 SourceLocation()));
276
277 // Get the new insert position for the node we care about.
278 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
279 assert(Canonical == 0 && "Shouldn't be in the map!");
280 (void)Canonical;
281
282 // Create the canonical template template parameter entry.
283 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
284 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
285 return CanonTTP;
286}
287
Charles Davis53c59df2010-08-16 03:33:14 +0000288CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000289 if (!LangOpts.CPlusPlus) return 0;
290
Charles Davis6bcb07a2010-08-19 02:18:14 +0000291 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000292 case CXXABI_ARM:
293 return CreateARMCXXABI(*this);
294 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000295 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000296 case CXXABI_Microsoft:
297 return CreateMicrosoftCXXABI(*this);
298 }
David Blaikie8a40f702012-01-17 06:56:22 +0000299 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000300}
301
Douglas Gregore8bbc122011-09-02 00:18:52 +0000302static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000303 const LangOptions &LOpts) {
304 if (LOpts.FakeAddressSpaceMap) {
305 // The fake address space map must have a distinct entry for each
306 // language-specific address space.
307 static const unsigned FakeAddrSpaceMap[] = {
308 1, // opencl_global
309 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000310 3, // opencl_constant
311 4, // cuda_device
312 5, // cuda_constant
313 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000314 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000315 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000316 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000317 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000318 }
319}
320
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000321ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000322 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000323 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000324 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000325 unsigned size_reserve,
326 bool DelayInitialization)
327 : FunctionProtoTypes(this_()),
328 TemplateSpecializationTypes(this_()),
329 DependentTemplateSpecializationTypes(this_()),
330 SubstTemplateTemplateParmPacks(this_()),
331 GlobalNestedNameSpecifier(0),
332 Int128Decl(0), UInt128Decl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000333 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000334 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000335 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000336 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000337 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
338 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
339 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000340 NullTypeSourceInfo(QualType()),
341 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000342 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000343 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000344 Idents(idents), Selectors(sels),
345 BuiltinInfo(builtins),
346 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000347 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000348 Comments(SM), CommentsLoaded(false),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000349 LastSDM(0, 0),
350 UniqueBlockByRefTypeID(0)
351{
Mike Stump11289f42009-09-09 15:08:12 +0000352 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000353 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000354
355 if (!DelayInitialization) {
356 assert(t && "No target supplied for ASTContext initialization");
357 InitBuiltinTypes(*t);
358 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000359}
360
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000361ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000362 // Release the DenseMaps associated with DeclContext objects.
363 // FIXME: Is this the ideal solution?
364 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000365
Douglas Gregor5b11d492010-07-25 17:53:33 +0000366 // Call all of the deallocation functions.
367 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
368 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000369
Ted Kremenek076baeb2010-06-08 23:00:58 +0000370 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000371 // because they can contain DenseMaps.
372 for (llvm::DenseMap<const ObjCContainerDecl*,
373 const ASTRecordLayout*>::iterator
374 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
375 // Increment in loop to prevent using deallocated memory.
376 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
377 R->Destroy(*this);
378
Ted Kremenek076baeb2010-06-08 23:00:58 +0000379 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
380 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
381 // Increment in loop to prevent using deallocated memory.
382 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
383 R->Destroy(*this);
384 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000385
386 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
387 AEnd = DeclAttrs.end();
388 A != AEnd; ++A)
389 A->second->~AttrVec();
390}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000391
Douglas Gregor1a809332010-05-23 18:26:36 +0000392void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
393 Deallocations.push_back(std::make_pair(Callback, Data));
394}
395
Mike Stump11289f42009-09-09 15:08:12 +0000396void
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000397ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000398 ExternalSource.reset(Source.take());
399}
400
Chris Lattner4eb445d2007-01-26 01:27:23 +0000401void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000402 llvm::errs() << "\n*** AST Context Stats:\n";
403 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000404
Douglas Gregora30d0462009-05-26 14:40:08 +0000405 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000406#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000407#define ABSTRACT_TYPE(Name, Parent)
408#include "clang/AST/TypeNodes.def"
409 0 // Extra
410 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000411
Chris Lattner4eb445d2007-01-26 01:27:23 +0000412 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
413 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000414 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000415 }
416
Douglas Gregora30d0462009-05-26 14:40:08 +0000417 unsigned Idx = 0;
418 unsigned TotalBytes = 0;
419#define TYPE(Name, Parent) \
420 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000421 llvm::errs() << " " << counts[Idx] << " " << #Name \
422 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000423 TotalBytes += counts[Idx] * sizeof(Name##Type); \
424 ++Idx;
425#define ABSTRACT_TYPE(Name, Parent)
426#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000427
Chandler Carruth3c147a72011-07-04 05:32:14 +0000428 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
429
Douglas Gregor7454c562010-07-02 20:37:36 +0000430 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000431 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
432 << NumImplicitDefaultConstructors
433 << " implicit default constructors created\n";
434 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
435 << NumImplicitCopyConstructors
436 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000437 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000438 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
439 << NumImplicitMoveConstructors
440 << " implicit move constructors created\n";
441 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
442 << NumImplicitCopyAssignmentOperators
443 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000444 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000445 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
446 << NumImplicitMoveAssignmentOperators
447 << " implicit move assignment operators created\n";
448 llvm::errs() << NumImplicitDestructorsDeclared << "/"
449 << NumImplicitDestructors
450 << " implicit destructors created\n";
451
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000452 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000453 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000454 ExternalSource->PrintStats();
455 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000456
Douglas Gregor5b11d492010-07-25 17:53:33 +0000457 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000458}
459
Douglas Gregor801c99d2011-08-12 06:49:56 +0000460TypedefDecl *ASTContext::getInt128Decl() const {
461 if (!Int128Decl) {
462 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
463 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
464 getTranslationUnitDecl(),
465 SourceLocation(),
466 SourceLocation(),
467 &Idents.get("__int128_t"),
468 TInfo);
469 }
470
471 return Int128Decl;
472}
473
474TypedefDecl *ASTContext::getUInt128Decl() const {
475 if (!UInt128Decl) {
476 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
477 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
478 getTranslationUnitDecl(),
479 SourceLocation(),
480 SourceLocation(),
481 &Idents.get("__uint128_t"),
482 TInfo);
483 }
484
485 return UInt128Decl;
486}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000487
John McCall48f2d582009-10-23 23:03:21 +0000488void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000489 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000490 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000491 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000492}
493
Douglas Gregore8bbc122011-09-02 00:18:52 +0000494void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
495 assert((!this->Target || this->Target == &Target) &&
496 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000497 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000498
Douglas Gregore8bbc122011-09-02 00:18:52 +0000499 this->Target = &Target;
500
501 ABI.reset(createCXXABI(Target));
502 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
503
Chris Lattner970e54e2006-11-12 00:37:36 +0000504 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000505 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000506
Chris Lattner970e54e2006-11-12 00:37:36 +0000507 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000508 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000509 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000510 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000511 InitBuiltinType(CharTy, BuiltinType::Char_S);
512 else
513 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000514 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000515 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
516 InitBuiltinType(ShortTy, BuiltinType::Short);
517 InitBuiltinType(IntTy, BuiltinType::Int);
518 InitBuiltinType(LongTy, BuiltinType::Long);
519 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000520
Chris Lattner970e54e2006-11-12 00:37:36 +0000521 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000522 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
523 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
524 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
525 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
526 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000527
Chris Lattner970e54e2006-11-12 00:37:36 +0000528 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000529 InitBuiltinType(FloatTy, BuiltinType::Float);
530 InitBuiltinType(DoubleTy, BuiltinType::Double);
531 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000532
Chris Lattnerf122cef2009-04-30 02:43:43 +0000533 // GNU extension, 128-bit integers.
534 InitBuiltinType(Int128Ty, BuiltinType::Int128);
535 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
536
Chris Lattnerad3467e2010-12-25 23:25:43 +0000537 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedman786d0872011-04-30 19:24:24 +0000538 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000539 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
540 else // -fshort-wchar makes wchar_t be unsigned.
541 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
542 } else // C99
Chris Lattner007cb022009-02-26 23:43:47 +0000543 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000544
James Molloy36365542012-05-04 10:55:22 +0000545 WIntTy = getFromTargetType(Target.getWIntType());
546
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000547 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
548 InitBuiltinType(Char16Ty, BuiltinType::Char16);
549 else // C99
550 Char16Ty = getFromTargetType(Target.getChar16Type());
551
552 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
553 InitBuiltinType(Char32Ty, BuiltinType::Char32);
554 else // C99
555 Char32Ty = getFromTargetType(Target.getChar32Type());
556
Douglas Gregor4619e432008-12-05 23:32:09 +0000557 // Placeholder type for type-dependent expressions whose type is
558 // completely unknown. No code should ever check a type against
559 // DependentTy and users should never see it; however, it is here to
560 // help diagnose failures to properly check for type-dependent
561 // expressions.
562 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000563
John McCall36e7fe32010-10-12 00:20:44 +0000564 // Placeholder type for functions.
565 InitBuiltinType(OverloadTy, BuiltinType::Overload);
566
John McCall0009fcc2011-04-26 20:42:42 +0000567 // Placeholder type for bound members.
568 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
569
John McCall526ab472011-10-25 17:37:35 +0000570 // Placeholder type for pseudo-objects.
571 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
572
John McCall31996342011-04-07 08:22:57 +0000573 // "any" type; useful for debugger-like clients.
574 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
575
John McCall8a6b59a2011-10-17 18:09:15 +0000576 // Placeholder type for unbridged ARC casts.
577 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
578
Chris Lattner970e54e2006-11-12 00:37:36 +0000579 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000580 FloatComplexTy = getComplexType(FloatTy);
581 DoubleComplexTy = getComplexType(DoubleTy);
582 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000583
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000584 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000585 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
586 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000587 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000588
589 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +0000590 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
591 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000592
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000593 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000594
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000595 // void * type
596 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000597
598 // nullptr type (C++0x 2.14.7)
599 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000600
601 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
602 InitBuiltinType(HalfTy, BuiltinType::Half);
Chris Lattner970e54e2006-11-12 00:37:36 +0000603}
604
David Blaikie9c902b52011-09-25 23:23:43 +0000605DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000606 return SourceMgr.getDiagnostics();
607}
608
Douglas Gregor561eceb2010-08-30 16:49:28 +0000609AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
610 AttrVec *&Result = DeclAttrs[D];
611 if (!Result) {
612 void *Mem = Allocate(sizeof(AttrVec));
613 Result = new (Mem) AttrVec;
614 }
615
616 return *Result;
617}
618
619/// \brief Erase the attributes corresponding to the given declaration.
620void ASTContext::eraseDeclAttrs(const Decl *D) {
621 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
622 if (Pos != DeclAttrs.end()) {
623 Pos->second->~AttrVec();
624 DeclAttrs.erase(Pos);
625 }
626}
627
Douglas Gregor86d142a2009-10-08 07:24:58 +0000628MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000629ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000630 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000631 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000632 = InstantiatedFromStaticDataMember.find(Var);
633 if (Pos == InstantiatedFromStaticDataMember.end())
634 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000635
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000636 return Pos->second;
637}
638
Mike Stump11289f42009-09-09 15:08:12 +0000639void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000640ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000641 TemplateSpecializationKind TSK,
642 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000643 assert(Inst->isStaticDataMember() && "Not a static data member");
644 assert(Tmpl->isStaticDataMember() && "Not a static data member");
645 assert(!InstantiatedFromStaticDataMember[Inst] &&
646 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000647 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000648 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000649}
650
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000651FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
652 const FunctionDecl *FD){
653 assert(FD && "Specialization is 0");
654 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +0000655 = ClassScopeSpecializationPattern.find(FD);
656 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000657 return 0;
658
659 return Pos->second;
660}
661
662void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
663 FunctionDecl *Pattern) {
664 assert(FD && "Specialization is 0");
665 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +0000666 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000667}
668
John McCalle61f2ba2009-11-18 02:36:19 +0000669NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000670ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000671 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000672 = InstantiatedFromUsingDecl.find(UUD);
673 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000674 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000675
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000676 return Pos->second;
677}
678
679void
John McCallb96ec562009-12-04 22:46:56 +0000680ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
681 assert((isa<UsingDecl>(Pattern) ||
682 isa<UnresolvedUsingValueDecl>(Pattern) ||
683 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
684 "pattern decl is not a using decl");
685 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
686 InstantiatedFromUsingDecl[Inst] = Pattern;
687}
688
689UsingShadowDecl *
690ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
691 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
692 = InstantiatedFromUsingShadowDecl.find(Inst);
693 if (Pos == InstantiatedFromUsingShadowDecl.end())
694 return 0;
695
696 return Pos->second;
697}
698
699void
700ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
701 UsingShadowDecl *Pattern) {
702 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
703 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000704}
705
Anders Carlsson5da84842009-09-01 04:26:58 +0000706FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
707 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
708 = InstantiatedFromUnnamedFieldDecl.find(Field);
709 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
710 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000711
Anders Carlsson5da84842009-09-01 04:26:58 +0000712 return Pos->second;
713}
714
715void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
716 FieldDecl *Tmpl) {
717 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
718 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
719 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
720 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000721
Anders Carlsson5da84842009-09-01 04:26:58 +0000722 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
723}
724
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000725bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
726 const FieldDecl *LastFD) const {
727 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000728 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000729}
730
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000731bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
732 const FieldDecl *LastFD) const {
733 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000734 FD->getBitWidthValue(*this) == 0 &&
735 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000736}
737
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000738bool ASTContext::BitfieldFollowsBitfield(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) &&
742 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000743}
744
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000745bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000746 const FieldDecl *LastFD) const {
747 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000748 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000749}
750
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000751bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000752 const FieldDecl *LastFD) const {
753 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000754 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000755}
756
Douglas Gregor832940b2010-03-02 23:58:15 +0000757ASTContext::overridden_cxx_method_iterator
758ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
759 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
760 = OverriddenMethods.find(Method);
761 if (Pos == OverriddenMethods.end())
762 return 0;
763
764 return Pos->second.begin();
765}
766
767ASTContext::overridden_cxx_method_iterator
768ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
769 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
770 = OverriddenMethods.find(Method);
771 if (Pos == OverriddenMethods.end())
772 return 0;
773
774 return Pos->second.end();
775}
776
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000777unsigned
778ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
779 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
780 = OverriddenMethods.find(Method);
781 if (Pos == OverriddenMethods.end())
782 return 0;
783
784 return Pos->second.size();
785}
786
Douglas Gregor832940b2010-03-02 23:58:15 +0000787void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
788 const CXXMethodDecl *Overridden) {
789 OverriddenMethods[Method].push_back(Overridden);
790}
791
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000792void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
793 assert(!Import->NextLocalImport && "Import declaration already in the chain");
794 assert(!Import->isFromASTFile() && "Non-local import declaration");
795 if (!FirstLocalImport) {
796 FirstLocalImport = Import;
797 LastLocalImport = Import;
798 return;
799 }
800
801 LastLocalImport->NextLocalImport = Import;
802 LastLocalImport = Import;
803}
804
Chris Lattner53cfe802007-07-18 17:52:12 +0000805//===----------------------------------------------------------------------===//
806// Type Sizing and Analysis
807//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000808
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000809/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
810/// scalar floating point type.
811const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000812 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000813 assert(BT && "Not a floating point type!");
814 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +0000815 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000816 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +0000817 case BuiltinType::Float: return Target->getFloatFormat();
818 case BuiltinType::Double: return Target->getDoubleFormat();
819 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000820 }
821}
822
Ken Dyck160146e2010-01-27 17:10:57 +0000823/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000824/// specified decl. Note that bitfields do not have a valid alignment, so
825/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000826/// If @p RefAsPointee, references are treated like their underlying type
827/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000828CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000829 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +0000830
John McCall94268702010-10-08 18:24:19 +0000831 bool UseAlignAttrOnly = false;
832 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
833 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000834
John McCall94268702010-10-08 18:24:19 +0000835 // __attribute__((aligned)) can increase or decrease alignment
836 // *except* on a struct or struct member, where it only increases
837 // alignment unless 'packed' is also specified.
838 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +0000839 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +0000840 // ignore that possibility; Sema should diagnose it.
841 if (isa<FieldDecl>(D)) {
842 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
843 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
844 } else {
845 UseAlignAttrOnly = true;
846 }
847 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +0000848 else if (isa<FieldDecl>(D))
849 UseAlignAttrOnly =
850 D->hasAttr<PackedAttr>() ||
851 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +0000852
John McCall4e819612011-01-20 07:57:12 +0000853 // If we're using the align attribute only, just ignore everything
854 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +0000855 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +0000856 // do nothing
857
John McCall94268702010-10-08 18:24:19 +0000858 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000859 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000860 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000861 if (RefAsPointee)
862 T = RT->getPointeeType();
863 else
864 T = getPointerType(RT->getPointeeType());
865 }
866 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +0000867 // Adjust alignments of declarations with array type by the
868 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +0000869 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +0000870 const ArrayType *arrayType;
871 if (MinWidth && (arrayType = getAsArrayType(T))) {
872 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000873 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +0000874 else if (isa<ConstantArrayType>(arrayType) &&
875 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000876 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +0000877
John McCall33ddac02011-01-19 10:06:00 +0000878 // Walk through any array types while we're at it.
879 T = getBaseElementType(arrayType);
880 }
Chad Rosier99ee7822011-07-26 07:03:04 +0000881 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +0000882 }
John McCall4e819612011-01-20 07:57:12 +0000883
884 // Fields can be subject to extra alignment constraints, like if
885 // the field is packed, the struct is packed, or the struct has a
886 // a max-field-alignment constraint (#pragma pack). So calculate
887 // the actual alignment of the field within the struct, and then
888 // (as we're expected to) constrain that by the alignment of the type.
889 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
890 // So calculate the alignment of the field.
891 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
892
893 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +0000894 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +0000895
896 // Use the GCD of that and the offset within the record.
897 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
898 if (offset > 0) {
899 // Alignment is always a power of 2, so the GCD will be a power of 2,
900 // which means we get to do this crazy thing instead of Euclid's.
901 uint64_t lowBitOfOffset = offset & (~offset + 1);
902 if (lowBitOfOffset < fieldAlign)
903 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
904 }
905
906 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +0000907 }
Chris Lattner68061312009-01-24 21:53:27 +0000908 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000909
Ken Dyckcc56c542011-01-15 18:38:59 +0000910 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +0000911}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000912
John McCall87fe5d52010-05-20 01:18:31 +0000913std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000914ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000915 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +0000916 return std::make_pair(toCharUnitsFromBits(Info.first),
917 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +0000918}
919
920std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000921ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000922 return getTypeInfoInChars(T.getTypePtr());
923}
924
Daniel Dunbarc6475872012-03-09 04:12:54 +0000925std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
926 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
927 if (it != MemoizedTypeInfo.end())
928 return it->second;
929
930 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
931 MemoizedTypeInfo.insert(std::make_pair(T, Info));
932 return Info;
933}
934
935/// getTypeInfoImpl - Return the size of the specified type, in bits. This
936/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000937///
938/// FIXME: Pointers into different addr spaces could have different sizes and
939/// alignment requirements: getPointerInfo should take an AddrSpace, this
940/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000941std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +0000942ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000943 uint64_t Width=0;
944 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000945 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000946#define TYPE(Class, Base)
947#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000948#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000949#define DEPENDENT_TYPE(Class, Base) case Type::Class:
950#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +0000951 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000952
Chris Lattner355332d2007-07-13 22:27:08 +0000953 case Type::FunctionNoProto:
954 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000955 // GCC extension: alignof(function) = 32 bits
956 Width = 0;
957 Align = 32;
958 break;
959
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000960 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000961 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000962 Width = 0;
963 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
964 break;
965
Steve Naroff5c131802007-08-30 01:06:46 +0000966 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000967 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000968
Chris Lattner37e05872008-03-05 18:54:05 +0000969 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +0000970 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +0000971 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
972 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +0000973 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000974 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +0000975 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000976 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000977 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000978 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000979 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000980 const VectorType *VT = cast<VectorType>(T);
981 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
982 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000983 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000984 // If the alignment is not a power of 2, round up to the next power of 2.
985 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000986 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000987 Align = llvm::NextPowerOf2(Align);
988 Width = llvm::RoundUpToAlignment(Width, Align);
989 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000990 break;
991 }
Chris Lattner647fb222007-07-18 18:26:58 +0000992
Chris Lattner7570e9c2008-03-08 08:52:55 +0000993 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000994 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +0000995 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000996 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000997 // GCC extension: alignof(void) = 8 bits.
998 Width = 0;
999 Align = 8;
1000 break;
1001
Chris Lattner6a4f7452007-12-19 19:23:28 +00001002 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001003 Width = Target->getBoolWidth();
1004 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001005 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001006 case BuiltinType::Char_S:
1007 case BuiltinType::Char_U:
1008 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001009 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001010 Width = Target->getCharWidth();
1011 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001012 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001013 case BuiltinType::WChar_S:
1014 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001015 Width = Target->getWCharWidth();
1016 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001017 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001018 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001019 Width = Target->getChar16Width();
1020 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001021 break;
1022 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001023 Width = Target->getChar32Width();
1024 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001025 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001026 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001027 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001028 Width = Target->getShortWidth();
1029 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001030 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001031 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001032 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001033 Width = Target->getIntWidth();
1034 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001035 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001036 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001037 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001038 Width = Target->getLongWidth();
1039 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001040 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001041 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001042 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001043 Width = Target->getLongLongWidth();
1044 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001045 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001046 case BuiltinType::Int128:
1047 case BuiltinType::UInt128:
1048 Width = 128;
1049 Align = 128; // int128_t is 128-bit aligned on all targets.
1050 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001051 case BuiltinType::Half:
1052 Width = Target->getHalfWidth();
1053 Align = Target->getHalfAlign();
1054 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001055 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001056 Width = Target->getFloatWidth();
1057 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001058 break;
1059 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001060 Width = Target->getDoubleWidth();
1061 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001062 break;
1063 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001064 Width = Target->getLongDoubleWidth();
1065 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001066 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001067 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001068 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1069 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001070 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001071 case BuiltinType::ObjCId:
1072 case BuiltinType::ObjCClass:
1073 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001074 Width = Target->getPointerWidth(0);
1075 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001076 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001077 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001078 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001079 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001080 Width = Target->getPointerWidth(0);
1081 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001082 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001083 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001084 unsigned AS = getTargetAddressSpace(
1085 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001086 Width = Target->getPointerWidth(AS);
1087 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001088 break;
1089 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001090 case Type::LValueReference:
1091 case Type::RValueReference: {
1092 // alignof and sizeof should never enter this code path here, so we go
1093 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001094 unsigned AS = getTargetAddressSpace(
1095 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001096 Width = Target->getPointerWidth(AS);
1097 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001098 break;
1099 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001100 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001101 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001102 Width = Target->getPointerWidth(AS);
1103 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001104 break;
1105 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001106 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001107 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001108 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +00001109 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +00001110 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001111 Align = PtrDiffInfo.second;
1112 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001113 }
Chris Lattner647fb222007-07-18 18:26:58 +00001114 case Type::Complex: {
1115 // Complex types have the same alignment as their elements, but twice the
1116 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001117 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001118 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001119 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001120 Align = EltInfo.second;
1121 break;
1122 }
John McCall8b07ec22010-05-15 11:32:37 +00001123 case Type::ObjCObject:
1124 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001125 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001126 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001127 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001128 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001129 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001130 break;
1131 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001132 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001133 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001134 const TagType *TT = cast<TagType>(T);
1135
1136 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001137 Width = 8;
1138 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001139 break;
1140 }
Mike Stump11289f42009-09-09 15:08:12 +00001141
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001142 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001143 return getTypeInfo(ET->getDecl()->getIntegerType());
1144
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001145 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001146 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001147 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001148 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001149 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001150 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001151
Chris Lattner63d2b362009-10-22 05:17:15 +00001152 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001153 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1154 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001155
Richard Smith30482bc2011-02-20 03:19:35 +00001156 case Type::Auto: {
1157 const AutoType *A = cast<AutoType>(T);
1158 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001159 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001160 }
1161
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001162 case Type::Paren:
1163 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1164
Douglas Gregoref462e62009-04-30 17:32:17 +00001165 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001166 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001167 std::pair<uint64_t, unsigned> Info
1168 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001169 // If the typedef has an aligned attribute on it, it overrides any computed
1170 // alignment we have. This violates the GCC documentation (which says that
1171 // attribute(aligned) can only round up) but matches its implementation.
1172 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1173 Align = AttrAlign;
1174 else
1175 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001176 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001177 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001178 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001179
1180 case Type::TypeOfExpr:
1181 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1182 .getTypePtr());
1183
1184 case Type::TypeOf:
1185 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1186
Anders Carlsson81df7b82009-06-24 19:06:50 +00001187 case Type::Decltype:
1188 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1189 .getTypePtr());
1190
Alexis Hunte852b102011-05-24 22:41:36 +00001191 case Type::UnaryTransform:
1192 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1193
Abramo Bagnara6150c882010-05-11 21:36:43 +00001194 case Type::Elaborated:
1195 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001196
John McCall81904512011-01-06 01:58:22 +00001197 case Type::Attributed:
1198 return getTypeInfo(
1199 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1200
Richard Smith3f1b5d02011-05-05 21:57:07 +00001201 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001202 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001203 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001204 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1205 // A type alias template specialization may refer to a typedef with the
1206 // aligned attribute on it.
1207 if (TST->isTypeAlias())
1208 return getTypeInfo(TST->getAliasedType().getTypePtr());
1209 else
1210 return getTypeInfo(getCanonicalType(T));
1211 }
1212
Eli Friedman0dfb8892011-10-06 23:00:33 +00001213 case Type::Atomic: {
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001214 std::pair<uint64_t, unsigned> Info
1215 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1216 Width = Info.first;
1217 Align = Info.second;
1218 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1219 llvm::isPowerOf2_64(Width)) {
1220 // We can potentially perform lock-free atomic operations for this
1221 // type; promote the alignment appropriately.
1222 // FIXME: We could potentially promote the width here as well...
1223 // is that worthwhile? (Non-struct atomic types generally have
1224 // power-of-two size anyway, but structs might not. Requires a bit
1225 // of implementation work to make sure we zero out the extra bits.)
1226 Align = static_cast<unsigned>(Width);
1227 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001228 }
1229
Douglas Gregoref462e62009-04-30 17:32:17 +00001230 }
Mike Stump11289f42009-09-09 15:08:12 +00001231
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001232 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001233 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001234}
1235
Ken Dyckcc56c542011-01-15 18:38:59 +00001236/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1237CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1238 return CharUnits::fromQuantity(BitSize / getCharWidth());
1239}
1240
Ken Dyckb0fcc592011-02-11 01:54:29 +00001241/// toBits - Convert a size in characters to a size in characters.
1242int64_t ASTContext::toBits(CharUnits CharSize) const {
1243 return CharSize.getQuantity() * getCharWidth();
1244}
1245
Ken Dyck8c89d592009-12-22 14:23:30 +00001246/// getTypeSizeInChars - Return the size of the specified type, in characters.
1247/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001248CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001249 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001250}
Jay Foad39c79802011-01-12 09:06:06 +00001251CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001252 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001253}
1254
Ken Dycka6046ab2010-01-26 17:25:18 +00001255/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001256/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001257CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001258 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001259}
Jay Foad39c79802011-01-12 09:06:06 +00001260CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001261 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001262}
1263
Chris Lattnera3402cd2009-01-27 18:08:34 +00001264/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1265/// type for the current target in bits. This can be different than the ABI
1266/// alignment in cases where it is beneficial for performance to overalign
1267/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001268unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001269 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001270
1271 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001272 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001273 T = CT->getElementType().getTypePtr();
1274 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001275 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1276 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001277 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1278
Chris Lattnera3402cd2009-01-27 18:08:34 +00001279 return ABIAlign;
1280}
1281
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001282/// DeepCollectObjCIvars -
1283/// This routine first collects all declared, but not synthesized, ivars in
1284/// super class and then collects all ivars, including those synthesized for
1285/// current class. This routine is used for implementation of current class
1286/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001287///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001288void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1289 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001290 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001291 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1292 DeepCollectObjCIvars(SuperClass, false, Ivars);
1293 if (!leafClass) {
1294 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1295 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001296 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001297 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001298 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001299 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001300 Iv= Iv->getNextIvar())
1301 Ivars.push_back(Iv);
1302 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001303}
1304
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001305/// CollectInheritedProtocols - Collect all protocols in current class and
1306/// those inherited by it.
1307void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001308 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001309 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001310 // We can use protocol_iterator here instead of
1311 // all_referenced_protocol_iterator since we are walking all categories.
1312 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1313 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001314 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001315 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001316 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001317 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001318 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001319 CollectInheritedProtocols(*P, Protocols);
1320 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001321 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001322
1323 // Categories of this Interface.
1324 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1325 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1326 CollectInheritedProtocols(CDeclChain, Protocols);
1327 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1328 while (SD) {
1329 CollectInheritedProtocols(SD, Protocols);
1330 SD = SD->getSuperClass();
1331 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001332 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001333 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001334 PE = OC->protocol_end(); P != PE; ++P) {
1335 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001336 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001337 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1338 PE = Proto->protocol_end(); P != PE; ++P)
1339 CollectInheritedProtocols(*P, Protocols);
1340 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001341 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001342 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1343 PE = OP->protocol_end(); P != PE; ++P) {
1344 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001345 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001346 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1347 PE = Proto->protocol_end(); P != PE; ++P)
1348 CollectInheritedProtocols(*P, Protocols);
1349 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001350 }
1351}
1352
Jay Foad39c79802011-01-12 09:06:06 +00001353unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001354 unsigned count = 0;
1355 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001356 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1357 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001358 count += CDecl->ivar_size();
1359
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001360 // Count ivar defined in this class's implementation. This
1361 // includes synthesized ivars.
1362 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001363 count += ImplDecl->ivar_size();
1364
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001365 return count;
1366}
1367
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001368bool ASTContext::isSentinelNullExpr(const Expr *E) {
1369 if (!E)
1370 return false;
1371
1372 // nullptr_t is always treated as null.
1373 if (E->getType()->isNullPtrType()) return true;
1374
1375 if (E->getType()->isAnyPointerType() &&
1376 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1377 Expr::NPC_ValueDependentIsNull))
1378 return true;
1379
1380 // Unfortunately, __null has type 'int'.
1381 if (isa<GNUNullExpr>(E)) return true;
1382
1383 return false;
1384}
1385
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001386/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1387ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1388 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1389 I = ObjCImpls.find(D);
1390 if (I != ObjCImpls.end())
1391 return cast<ObjCImplementationDecl>(I->second);
1392 return 0;
1393}
1394/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1395ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1396 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1397 I = ObjCImpls.find(D);
1398 if (I != ObjCImpls.end())
1399 return cast<ObjCCategoryImplDecl>(I->second);
1400 return 0;
1401}
1402
1403/// \brief Set the implementation of ObjCInterfaceDecl.
1404void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1405 ObjCImplementationDecl *ImplD) {
1406 assert(IFaceD && ImplD && "Passed null params");
1407 ObjCImpls[IFaceD] = ImplD;
1408}
1409/// \brief Set the implementation of ObjCCategoryDecl.
1410void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1411 ObjCCategoryImplDecl *ImplD) {
1412 assert(CatD && ImplD && "Passed null params");
1413 ObjCImpls[CatD] = ImplD;
1414}
1415
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001416ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1417 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1418 return ID;
1419 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1420 return CD->getClassInterface();
1421 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1422 return IMD->getClassInterface();
1423
1424 return 0;
1425}
1426
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001427/// \brief Get the copy initialization expression of VarDecl,or NULL if
1428/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001429Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001430 assert(VD && "Passed null params");
1431 assert(VD->hasAttr<BlocksAttr>() &&
1432 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001433 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001434 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001435 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1436}
1437
1438/// \brief Set the copy inialization expression of a block var decl.
1439void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1440 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001441 assert(VD->hasAttr<BlocksAttr>() &&
1442 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001443 BlockVarCopyInits[VD] = Init;
1444}
1445
John McCallbcd03502009-12-07 02:54:59 +00001446TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001447 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001448 if (!DataSize)
1449 DataSize = TypeLoc::getFullDataSizeForType(T);
1450 else
1451 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001452 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001453
John McCallbcd03502009-12-07 02:54:59 +00001454 TypeSourceInfo *TInfo =
1455 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1456 new (TInfo) TypeSourceInfo(T);
1457 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001458}
1459
John McCallbcd03502009-12-07 02:54:59 +00001460TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001461 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001462 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001463 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001464 return DI;
1465}
1466
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001467const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001468ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001469 return getObjCLayout(D, 0);
1470}
1471
1472const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001473ASTContext::getASTObjCImplementationLayout(
1474 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001475 return getObjCLayout(D->getClassInterface(), D);
1476}
1477
Chris Lattner983a8bb2007-07-13 22:13:22 +00001478//===----------------------------------------------------------------------===//
1479// Type creation/memoization methods
1480//===----------------------------------------------------------------------===//
1481
Jay Foad39c79802011-01-12 09:06:06 +00001482QualType
John McCall33ddac02011-01-19 10:06:00 +00001483ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1484 unsigned fastQuals = quals.getFastQualifiers();
1485 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001486
1487 // Check if we've already instantiated this type.
1488 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001489 ExtQuals::Profile(ID, baseType, quals);
1490 void *insertPos = 0;
1491 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1492 assert(eq->getQualifiers() == quals);
1493 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001494 }
1495
John McCall33ddac02011-01-19 10:06:00 +00001496 // If the base type is not canonical, make the appropriate canonical type.
1497 QualType canon;
1498 if (!baseType->isCanonicalUnqualified()) {
1499 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00001500 canonSplit.Quals.addConsistentQualifiers(quals);
1501 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001502
1503 // Re-find the insert position.
1504 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1505 }
1506
1507 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1508 ExtQualNodes.InsertNode(eq, insertPos);
1509 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001510}
1511
Jay Foad39c79802011-01-12 09:06:06 +00001512QualType
1513ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001514 QualType CanT = getCanonicalType(T);
1515 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001516 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001517
John McCall8ccfcb52009-09-24 19:53:00 +00001518 // If we are composing extended qualifiers together, merge together
1519 // into one ExtQuals node.
1520 QualifierCollector Quals;
1521 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001522
John McCall8ccfcb52009-09-24 19:53:00 +00001523 // If this type already has an address space specified, it cannot get
1524 // another one.
1525 assert(!Quals.hasAddressSpace() &&
1526 "Type cannot be in multiple addr spaces!");
1527 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001528
John McCall8ccfcb52009-09-24 19:53:00 +00001529 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001530}
1531
Chris Lattnerd60183d2009-02-18 22:53:11 +00001532QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001533 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001534 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001535 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001536 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001537
John McCall53fa7142010-12-24 02:08:15 +00001538 if (const PointerType *ptr = T->getAs<PointerType>()) {
1539 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001540 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001541 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1542 return getPointerType(ResultType);
1543 }
1544 }
Mike Stump11289f42009-09-09 15:08:12 +00001545
John McCall8ccfcb52009-09-24 19:53:00 +00001546 // If we are composing extended qualifiers together, merge together
1547 // into one ExtQuals node.
1548 QualifierCollector Quals;
1549 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001550
John McCall8ccfcb52009-09-24 19:53:00 +00001551 // If this type already has an ObjCGC specified, it cannot get
1552 // another one.
1553 assert(!Quals.hasObjCGCAttr() &&
1554 "Type cannot have multiple ObjCGCs!");
1555 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001556
John McCall8ccfcb52009-09-24 19:53:00 +00001557 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001558}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001559
John McCall4f5019e2010-12-19 02:44:49 +00001560const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1561 FunctionType::ExtInfo Info) {
1562 if (T->getExtInfo() == Info)
1563 return T;
1564
1565 QualType Result;
1566 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1567 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1568 } else {
1569 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1570 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1571 EPI.ExtInfo = Info;
1572 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1573 FPT->getNumArgs(), EPI);
1574 }
1575
1576 return cast<FunctionType>(Result.getTypePtr());
1577}
1578
Chris Lattnerc6395932007-06-22 20:56:16 +00001579/// getComplexType - Return the uniqued reference to the type for a complex
1580/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001581QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001582 // Unique pointers, to guarantee there is only one pointer of a particular
1583 // structure.
1584 llvm::FoldingSetNodeID ID;
1585 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001586
Chris Lattnerc6395932007-06-22 20:56:16 +00001587 void *InsertPos = 0;
1588 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1589 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001590
Chris Lattnerc6395932007-06-22 20:56:16 +00001591 // If the pointee type isn't canonical, this won't be a canonical type either,
1592 // so fill in the canonical type field.
1593 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001594 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001595 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001596
Chris Lattnerc6395932007-06-22 20:56:16 +00001597 // Get the new insert position for the node we care about.
1598 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001599 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001600 }
John McCall90d1c2d2009-09-24 23:30:46 +00001601 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001602 Types.push_back(New);
1603 ComplexTypes.InsertNode(New, InsertPos);
1604 return QualType(New, 0);
1605}
1606
Chris Lattner970e54e2006-11-12 00:37:36 +00001607/// getPointerType - Return the uniqued reference to the type for a pointer to
1608/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001609QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001610 // Unique pointers, to guarantee there is only one pointer of a particular
1611 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001612 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001613 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001614
Chris Lattner67521df2007-01-27 01:29:36 +00001615 void *InsertPos = 0;
1616 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001617 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001618
Chris Lattner7ccecb92006-11-12 08:50:50 +00001619 // If the pointee type isn't canonical, this won't be a canonical type either,
1620 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001621 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001622 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001623 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001624
Chris Lattner67521df2007-01-27 01:29:36 +00001625 // Get the new insert position for the node we care about.
1626 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001627 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001628 }
John McCall90d1c2d2009-09-24 23:30:46 +00001629 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001630 Types.push_back(New);
1631 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001632 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001633}
1634
Mike Stump11289f42009-09-09 15:08:12 +00001635/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001636/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001637QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001638 assert(T->isFunctionType() && "block of function types only");
1639 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001640 // structure.
1641 llvm::FoldingSetNodeID ID;
1642 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001643
Steve Naroffec33ed92008-08-27 16:04:49 +00001644 void *InsertPos = 0;
1645 if (BlockPointerType *PT =
1646 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1647 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001648
1649 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001650 // type either so fill in the canonical type field.
1651 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001652 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001653 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001654
Steve Naroffec33ed92008-08-27 16:04:49 +00001655 // Get the new insert position for the node we care about.
1656 BlockPointerType *NewIP =
1657 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001658 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001659 }
John McCall90d1c2d2009-09-24 23:30:46 +00001660 BlockPointerType *New
1661 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001662 Types.push_back(New);
1663 BlockPointerTypes.InsertNode(New, InsertPos);
1664 return QualType(New, 0);
1665}
1666
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001667/// getLValueReferenceType - Return the uniqued reference to the type for an
1668/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001669QualType
1670ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00001671 assert(getCanonicalType(T) != OverloadTy &&
1672 "Unresolved overloaded function type");
1673
Bill Wendling3708c182007-05-27 10:15:43 +00001674 // Unique pointers, to guarantee there is only one pointer of a particular
1675 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001676 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001677 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001678
1679 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001680 if (LValueReferenceType *RT =
1681 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001682 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001683
John McCallfc93cf92009-10-22 22:37:11 +00001684 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1685
Bill Wendling3708c182007-05-27 10:15:43 +00001686 // If the referencee type isn't canonical, this won't be a canonical type
1687 // either, so fill in the canonical type field.
1688 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001689 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1690 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1691 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001692
Bill Wendling3708c182007-05-27 10:15:43 +00001693 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001694 LValueReferenceType *NewIP =
1695 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001696 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001697 }
1698
John McCall90d1c2d2009-09-24 23:30:46 +00001699 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001700 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1701 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001702 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001703 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001704
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001705 return QualType(New, 0);
1706}
1707
1708/// getRValueReferenceType - Return the uniqued reference to the type for an
1709/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001710QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001711 // Unique pointers, to guarantee there is only one pointer of a particular
1712 // structure.
1713 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001714 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001715
1716 void *InsertPos = 0;
1717 if (RValueReferenceType *RT =
1718 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1719 return QualType(RT, 0);
1720
John McCallfc93cf92009-10-22 22:37:11 +00001721 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1722
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001723 // If the referencee type isn't canonical, this won't be a canonical type
1724 // either, so fill in the canonical type field.
1725 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001726 if (InnerRef || !T.isCanonical()) {
1727 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1728 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001729
1730 // Get the new insert position for the node we care about.
1731 RValueReferenceType *NewIP =
1732 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001733 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001734 }
1735
John McCall90d1c2d2009-09-24 23:30:46 +00001736 RValueReferenceType *New
1737 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001738 Types.push_back(New);
1739 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001740 return QualType(New, 0);
1741}
1742
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001743/// getMemberPointerType - Return the uniqued reference to the type for a
1744/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001745QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001746 // Unique pointers, to guarantee there is only one pointer of a particular
1747 // structure.
1748 llvm::FoldingSetNodeID ID;
1749 MemberPointerType::Profile(ID, T, Cls);
1750
1751 void *InsertPos = 0;
1752 if (MemberPointerType *PT =
1753 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1754 return QualType(PT, 0);
1755
1756 // If the pointee or class type isn't canonical, this won't be a canonical
1757 // type either, so fill in the canonical type field.
1758 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001759 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001760 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1761
1762 // Get the new insert position for the node we care about.
1763 MemberPointerType *NewIP =
1764 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001765 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001766 }
John McCall90d1c2d2009-09-24 23:30:46 +00001767 MemberPointerType *New
1768 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001769 Types.push_back(New);
1770 MemberPointerTypes.InsertNode(New, InsertPos);
1771 return QualType(New, 0);
1772}
1773
Mike Stump11289f42009-09-09 15:08:12 +00001774/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001775/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001776QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001777 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001778 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001779 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001780 assert((EltTy->isDependentType() ||
1781 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001782 "Constant array of VLAs is illegal!");
1783
Chris Lattnere2df3f92009-05-13 04:12:56 +00001784 // Convert the array size into a canonical width matching the pointer size for
1785 // the target.
1786 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001787 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001788 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00001789
Chris Lattner23b7eb62007-06-15 23:05:46 +00001790 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001791 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001792
Chris Lattner36f8e652007-01-27 08:31:04 +00001793 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001794 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001795 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001796 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001797
John McCall33ddac02011-01-19 10:06:00 +00001798 // If the element type isn't canonical or has qualifiers, this won't
1799 // be a canonical type either, so fill in the canonical type field.
1800 QualType Canon;
1801 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1802 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00001803 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001804 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00001805 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001806
Chris Lattner36f8e652007-01-27 08:31:04 +00001807 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001808 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001809 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001810 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001811 }
Mike Stump11289f42009-09-09 15:08:12 +00001812
John McCall90d1c2d2009-09-24 23:30:46 +00001813 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001814 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001815 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001816 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001817 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001818}
1819
John McCall06549462011-01-18 08:40:38 +00001820/// getVariableArrayDecayedType - Turns the given type, which may be
1821/// variably-modified, into the corresponding type with all the known
1822/// sizes replaced with [*].
1823QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1824 // Vastly most common case.
1825 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001826
John McCall06549462011-01-18 08:40:38 +00001827 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001828
John McCall06549462011-01-18 08:40:38 +00001829 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00001830 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00001831 switch (ty->getTypeClass()) {
1832#define TYPE(Class, Base)
1833#define ABSTRACT_TYPE(Class, Base)
1834#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1835#include "clang/AST/TypeNodes.def"
1836 llvm_unreachable("didn't desugar past all non-canonical types?");
1837
1838 // These types should never be variably-modified.
1839 case Type::Builtin:
1840 case Type::Complex:
1841 case Type::Vector:
1842 case Type::ExtVector:
1843 case Type::DependentSizedExtVector:
1844 case Type::ObjCObject:
1845 case Type::ObjCInterface:
1846 case Type::ObjCObjectPointer:
1847 case Type::Record:
1848 case Type::Enum:
1849 case Type::UnresolvedUsing:
1850 case Type::TypeOfExpr:
1851 case Type::TypeOf:
1852 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00001853 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00001854 case Type::DependentName:
1855 case Type::InjectedClassName:
1856 case Type::TemplateSpecialization:
1857 case Type::DependentTemplateSpecialization:
1858 case Type::TemplateTypeParm:
1859 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00001860 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00001861 case Type::PackExpansion:
1862 llvm_unreachable("type should never be variably-modified");
1863
1864 // These types can be variably-modified but should never need to
1865 // further decay.
1866 case Type::FunctionNoProto:
1867 case Type::FunctionProto:
1868 case Type::BlockPointer:
1869 case Type::MemberPointer:
1870 return type;
1871
1872 // These types can be variably-modified. All these modifications
1873 // preserve structure except as noted by comments.
1874 // TODO: if we ever care about optimizing VLAs, there are no-op
1875 // optimizations available here.
1876 case Type::Pointer:
1877 result = getPointerType(getVariableArrayDecayedType(
1878 cast<PointerType>(ty)->getPointeeType()));
1879 break;
1880
1881 case Type::LValueReference: {
1882 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1883 result = getLValueReferenceType(
1884 getVariableArrayDecayedType(lv->getPointeeType()),
1885 lv->isSpelledAsLValue());
1886 break;
1887 }
1888
1889 case Type::RValueReference: {
1890 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1891 result = getRValueReferenceType(
1892 getVariableArrayDecayedType(lv->getPointeeType()));
1893 break;
1894 }
1895
Eli Friedman0dfb8892011-10-06 23:00:33 +00001896 case Type::Atomic: {
1897 const AtomicType *at = cast<AtomicType>(ty);
1898 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1899 break;
1900 }
1901
John McCall06549462011-01-18 08:40:38 +00001902 case Type::ConstantArray: {
1903 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1904 result = getConstantArrayType(
1905 getVariableArrayDecayedType(cat->getElementType()),
1906 cat->getSize(),
1907 cat->getSizeModifier(),
1908 cat->getIndexTypeCVRQualifiers());
1909 break;
1910 }
1911
1912 case Type::DependentSizedArray: {
1913 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1914 result = getDependentSizedArrayType(
1915 getVariableArrayDecayedType(dat->getElementType()),
1916 dat->getSizeExpr(),
1917 dat->getSizeModifier(),
1918 dat->getIndexTypeCVRQualifiers(),
1919 dat->getBracketsRange());
1920 break;
1921 }
1922
1923 // Turn incomplete types into [*] types.
1924 case Type::IncompleteArray: {
1925 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1926 result = getVariableArrayType(
1927 getVariableArrayDecayedType(iat->getElementType()),
1928 /*size*/ 0,
1929 ArrayType::Normal,
1930 iat->getIndexTypeCVRQualifiers(),
1931 SourceRange());
1932 break;
1933 }
1934
1935 // Turn VLA types into [*] types.
1936 case Type::VariableArray: {
1937 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1938 result = getVariableArrayType(
1939 getVariableArrayDecayedType(vat->getElementType()),
1940 /*size*/ 0,
1941 ArrayType::Star,
1942 vat->getIndexTypeCVRQualifiers(),
1943 vat->getBracketsRange());
1944 break;
1945 }
1946 }
1947
1948 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00001949 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00001950}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001951
Steve Naroffcadebd02007-08-30 18:14:25 +00001952/// getVariableArrayType - Returns a non-unique reference to the type for a
1953/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001954QualType ASTContext::getVariableArrayType(QualType EltTy,
1955 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001956 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001957 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001958 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001959 // Since we don't unique expressions, it isn't possible to unique VLA's
1960 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00001961 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001962
John McCall33ddac02011-01-19 10:06:00 +00001963 // Be sure to pull qualifiers off the element type.
1964 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1965 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00001966 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001967 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00001968 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001969 }
1970
John McCall90d1c2d2009-09-24 23:30:46 +00001971 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001972 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001973
1974 VariableArrayTypes.push_back(New);
1975 Types.push_back(New);
1976 return QualType(New, 0);
1977}
1978
Douglas Gregor4619e432008-12-05 23:32:09 +00001979/// getDependentSizedArrayType - Returns a non-unique reference to
1980/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001981/// type.
John McCall33ddac02011-01-19 10:06:00 +00001982QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1983 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00001984 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001985 unsigned elementTypeQuals,
1986 SourceRange brackets) const {
1987 assert((!numElements || numElements->isTypeDependent() ||
1988 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001989 "Size must be type- or value-dependent!");
1990
John McCall33ddac02011-01-19 10:06:00 +00001991 // Dependently-sized array types that do not have a specified number
1992 // of elements will have their sizes deduced from a dependent
1993 // initializer. We do no canonicalization here at all, which is okay
1994 // because they can't be used in most locations.
1995 if (!numElements) {
1996 DependentSizedArrayType *newType
1997 = new (*this, TypeAlignment)
1998 DependentSizedArrayType(*this, elementType, QualType(),
1999 numElements, ASM, elementTypeQuals,
2000 brackets);
2001 Types.push_back(newType);
2002 return QualType(newType, 0);
2003 }
2004
2005 // Otherwise, we actually build a new type every time, but we
2006 // also build a canonical type.
2007
2008 SplitQualType canonElementType = getCanonicalType(elementType).split();
2009
2010 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002011 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002012 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002013 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002014 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002015
John McCall33ddac02011-01-19 10:06:00 +00002016 // Look for an existing type with these properties.
2017 DependentSizedArrayType *canonTy =
2018 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002019
John McCall33ddac02011-01-19 10:06:00 +00002020 // If we don't have one, build one.
2021 if (!canonTy) {
2022 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002023 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002024 QualType(), numElements, ASM, elementTypeQuals,
2025 brackets);
2026 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2027 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002028 }
2029
John McCall33ddac02011-01-19 10:06:00 +00002030 // Apply qualifiers from the element type to the array.
2031 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002032 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002033
John McCall33ddac02011-01-19 10:06:00 +00002034 // If we didn't need extra canonicalization for the element type,
2035 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002036 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002037 return canon;
2038
2039 // Otherwise, we need to build a type which follows the spelling
2040 // of the element type.
2041 DependentSizedArrayType *sugaredType
2042 = new (*this, TypeAlignment)
2043 DependentSizedArrayType(*this, elementType, canon, numElements,
2044 ASM, elementTypeQuals, brackets);
2045 Types.push_back(sugaredType);
2046 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002047}
2048
John McCall33ddac02011-01-19 10:06:00 +00002049QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002050 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002051 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002052 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002053 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002054
John McCall33ddac02011-01-19 10:06:00 +00002055 void *insertPos = 0;
2056 if (IncompleteArrayType *iat =
2057 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2058 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002059
2060 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002061 // either, so fill in the canonical type field. We also have to pull
2062 // qualifiers off the element type.
2063 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002064
John McCall33ddac02011-01-19 10:06:00 +00002065 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2066 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002067 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002068 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002069 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002070
2071 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002072 IncompleteArrayType *existing =
2073 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2074 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002075 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002076
John McCall33ddac02011-01-19 10:06:00 +00002077 IncompleteArrayType *newType = new (*this, TypeAlignment)
2078 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002079
John McCall33ddac02011-01-19 10:06:00 +00002080 IncompleteArrayTypes.InsertNode(newType, insertPos);
2081 Types.push_back(newType);
2082 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002083}
2084
Steve Naroff91fcddb2007-07-18 18:00:27 +00002085/// getVectorType - Return the unique reference to a vector type of
2086/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002087QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002088 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002089 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002090
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002091 // Check if we've already instantiated a vector of this type.
2092 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002093 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002094
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002095 void *InsertPos = 0;
2096 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2097 return QualType(VTP, 0);
2098
2099 // If the element type isn't canonical, this won't be a canonical type either,
2100 // so fill in the canonical type field.
2101 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002102 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002103 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002104
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002105 // Get the new insert position for the node we care about.
2106 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002107 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002108 }
John McCall90d1c2d2009-09-24 23:30:46 +00002109 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002110 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002111 VectorTypes.InsertNode(New, InsertPos);
2112 Types.push_back(New);
2113 return QualType(New, 0);
2114}
2115
Nate Begemance4d7fc2008-04-18 23:10:10 +00002116/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002117/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002118QualType
2119ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002120 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002121
Steve Naroff91fcddb2007-07-18 18:00:27 +00002122 // Check if we've already instantiated a vector of this type.
2123 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002124 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002125 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002126 void *InsertPos = 0;
2127 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2128 return QualType(VTP, 0);
2129
2130 // If the element type isn't canonical, this won't be a canonical type either,
2131 // so fill in the canonical type field.
2132 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002133 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002134 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002135
Steve Naroff91fcddb2007-07-18 18:00:27 +00002136 // Get the new insert position for the node we care about.
2137 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002138 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002139 }
John McCall90d1c2d2009-09-24 23:30:46 +00002140 ExtVectorType *New = new (*this, TypeAlignment)
2141 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002142 VectorTypes.InsertNode(New, InsertPos);
2143 Types.push_back(New);
2144 return QualType(New, 0);
2145}
2146
Jay Foad39c79802011-01-12 09:06:06 +00002147QualType
2148ASTContext::getDependentSizedExtVectorType(QualType vecType,
2149 Expr *SizeExpr,
2150 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002151 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002152 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002153 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002154
Douglas Gregor352169a2009-07-31 03:54:25 +00002155 void *InsertPos = 0;
2156 DependentSizedExtVectorType *Canon
2157 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2158 DependentSizedExtVectorType *New;
2159 if (Canon) {
2160 // We already have a canonical version of this array type; use it as
2161 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002162 New = new (*this, TypeAlignment)
2163 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2164 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002165 } else {
2166 QualType CanonVecTy = getCanonicalType(vecType);
2167 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002168 New = new (*this, TypeAlignment)
2169 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2170 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002171
2172 DependentSizedExtVectorType *CanonCheck
2173 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2174 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2175 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002176 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2177 } else {
2178 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2179 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002180 New = new (*this, TypeAlignment)
2181 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002182 }
2183 }
Mike Stump11289f42009-09-09 15:08:12 +00002184
Douglas Gregor758a8692009-06-17 21:51:59 +00002185 Types.push_back(New);
2186 return QualType(New, 0);
2187}
2188
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002189/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002190///
Jay Foad39c79802011-01-12 09:06:06 +00002191QualType
2192ASTContext::getFunctionNoProtoType(QualType ResultTy,
2193 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002194 const CallingConv DefaultCC = Info.getCC();
2195 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2196 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002197 // Unique functions, to guarantee there is only one function of a particular
2198 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002199 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002200 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002201
Chris Lattner47955de2007-01-27 08:37:20 +00002202 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002203 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002204 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002205 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002206
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002207 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002208 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002209 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002210 Canonical =
2211 getFunctionNoProtoType(getCanonicalType(ResultTy),
2212 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002213
Chris Lattner47955de2007-01-27 08:37:20 +00002214 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002215 FunctionNoProtoType *NewIP =
2216 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002217 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002218 }
Mike Stump11289f42009-09-09 15:08:12 +00002219
Roman Divacky65b88cd2011-03-01 17:40:53 +00002220 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002221 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002222 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002223 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002224 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002225 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002226}
2227
2228/// getFunctionType - Return a normal function type with a typed argument
2229/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002230QualType
2231ASTContext::getFunctionType(QualType ResultTy,
2232 const QualType *ArgArray, unsigned NumArgs,
2233 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002234 // Unique functions, to guarantee there is only one function of a particular
2235 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002236 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002237 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002238
2239 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002240 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002241 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002242 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002243
2244 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002245 bool isCanonical =
2246 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2247 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002248 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002249 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002250 isCanonical = false;
2251
Roman Divacky65b88cd2011-03-01 17:40:53 +00002252 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2253 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2254 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002255
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002256 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002257 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002258 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002259 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002260 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002261 CanonicalArgs.reserve(NumArgs);
2262 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002263 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002264
John McCalldb40c7f2010-12-14 08:05:40 +00002265 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002266 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002267 CanonicalEPI.ExceptionSpecType = EST_None;
2268 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002269 CanonicalEPI.ExtInfo
2270 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2271
Chris Lattner76a00cf2008-04-06 22:59:24 +00002272 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002273 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002274 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002275
Chris Lattnerfd4de792007-01-27 01:15:32 +00002276 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002277 FunctionProtoType *NewIP =
2278 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002279 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002280 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002281
John McCall31168b02011-06-15 23:02:42 +00002282 // FunctionProtoType objects are allocated with extra bytes after
2283 // them for three variable size arrays at the end:
2284 // - parameter types
2285 // - exception types
2286 // - consumed-arguments flags
2287 // Instead of the exception types, there could be a noexcept
2288 // expression.
John McCalldb40c7f2010-12-14 08:05:40 +00002289 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002290 NumArgs * sizeof(QualType);
2291 if (EPI.ExceptionSpecType == EST_Dynamic)
2292 Size += EPI.NumExceptions * sizeof(QualType);
2293 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002294 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002295 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002296 Size += 2 * sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002297 }
John McCall31168b02011-06-15 23:02:42 +00002298 if (EPI.ConsumedArguments)
2299 Size += NumArgs * sizeof(bool);
2300
John McCalldb40c7f2010-12-14 08:05:40 +00002301 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002302 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2303 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002304 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002305 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002306 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002307 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002308}
Chris Lattneref51c202006-11-10 07:17:23 +00002309
John McCalle78aac42010-03-10 03:28:59 +00002310#ifndef NDEBUG
2311static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2312 if (!isa<CXXRecordDecl>(D)) return false;
2313 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2314 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2315 return true;
2316 if (RD->getDescribedClassTemplate() &&
2317 !isa<ClassTemplateSpecializationDecl>(RD))
2318 return true;
2319 return false;
2320}
2321#endif
2322
2323/// getInjectedClassNameType - Return the unique reference to the
2324/// injected class name type for the specified templated declaration.
2325QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002326 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002327 assert(NeedsInjectedClassNameType(Decl));
2328 if (Decl->TypeForDecl) {
2329 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002330 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002331 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2332 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2333 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2334 } else {
John McCall424cec92011-01-19 06:33:43 +00002335 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002336 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002337 Decl->TypeForDecl = newType;
2338 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002339 }
2340 return QualType(Decl->TypeForDecl, 0);
2341}
2342
Douglas Gregor83a586e2008-04-13 21:07:44 +00002343/// getTypeDeclType - Return the unique reference to the type for the
2344/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002345QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002346 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002347 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002348
Richard Smithdda56e42011-04-15 14:24:37 +00002349 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002350 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002351
John McCall96f0b5f2010-03-10 06:48:02 +00002352 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2353 "Template type parameter types are always available.");
2354
John McCall81e38502010-02-16 03:57:14 +00002355 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002356 assert(!Record->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002357 "struct/union has previous declaration");
2358 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002359 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002360 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002361 assert(!Enum->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002362 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002363 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002364 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002365 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002366 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2367 Decl->TypeForDecl = newType;
2368 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002369 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002370 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002371
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002372 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002373}
2374
Chris Lattner32d920b2007-01-26 02:01:53 +00002375/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002376/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002377QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002378ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2379 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002380 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002381
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002382 if (Canonical.isNull())
2383 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002384 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002385 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002386 Decl->TypeForDecl = newType;
2387 Types.push_back(newType);
2388 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002389}
2390
Jay Foad39c79802011-01-12 09:06:06 +00002391QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002392 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2393
Douglas Gregorec9fd132012-01-14 16:38:05 +00002394 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002395 if (PrevDecl->TypeForDecl)
2396 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2397
John McCall424cec92011-01-19 06:33:43 +00002398 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2399 Decl->TypeForDecl = newType;
2400 Types.push_back(newType);
2401 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002402}
2403
Jay Foad39c79802011-01-12 09:06:06 +00002404QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002405 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2406
Douglas Gregorec9fd132012-01-14 16:38:05 +00002407 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002408 if (PrevDecl->TypeForDecl)
2409 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2410
John McCall424cec92011-01-19 06:33:43 +00002411 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2412 Decl->TypeForDecl = newType;
2413 Types.push_back(newType);
2414 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002415}
2416
John McCall81904512011-01-06 01:58:22 +00002417QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2418 QualType modifiedType,
2419 QualType equivalentType) {
2420 llvm::FoldingSetNodeID id;
2421 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2422
2423 void *insertPos = 0;
2424 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2425 if (type) return QualType(type, 0);
2426
2427 QualType canon = getCanonicalType(equivalentType);
2428 type = new (*this, TypeAlignment)
2429 AttributedType(canon, attrKind, modifiedType, equivalentType);
2430
2431 Types.push_back(type);
2432 AttributedTypes.InsertNode(type, insertPos);
2433
2434 return QualType(type, 0);
2435}
2436
2437
John McCallcebee162009-10-18 09:09:24 +00002438/// \brief Retrieve a substitution-result type.
2439QualType
2440ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002441 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002442 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002443 && "replacement types must always be canonical");
2444
2445 llvm::FoldingSetNodeID ID;
2446 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2447 void *InsertPos = 0;
2448 SubstTemplateTypeParmType *SubstParm
2449 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2450
2451 if (!SubstParm) {
2452 SubstParm = new (*this, TypeAlignment)
2453 SubstTemplateTypeParmType(Parm, Replacement);
2454 Types.push_back(SubstParm);
2455 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2456 }
2457
2458 return QualType(SubstParm, 0);
2459}
2460
Douglas Gregorada4b792011-01-14 02:55:32 +00002461/// \brief Retrieve a
2462QualType ASTContext::getSubstTemplateTypeParmPackType(
2463 const TemplateTypeParmType *Parm,
2464 const TemplateArgument &ArgPack) {
2465#ifndef NDEBUG
2466 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2467 PEnd = ArgPack.pack_end();
2468 P != PEnd; ++P) {
2469 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2470 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2471 }
2472#endif
2473
2474 llvm::FoldingSetNodeID ID;
2475 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2476 void *InsertPos = 0;
2477 if (SubstTemplateTypeParmPackType *SubstParm
2478 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2479 return QualType(SubstParm, 0);
2480
2481 QualType Canon;
2482 if (!Parm->isCanonicalUnqualified()) {
2483 Canon = getCanonicalType(QualType(Parm, 0));
2484 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2485 ArgPack);
2486 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2487 }
2488
2489 SubstTemplateTypeParmPackType *SubstParm
2490 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2491 ArgPack);
2492 Types.push_back(SubstParm);
2493 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2494 return QualType(SubstParm, 0);
2495}
2496
Douglas Gregoreff93e02009-02-05 23:33:38 +00002497/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002498/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002499/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002500QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002501 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002502 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002503 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002504 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002505 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002506 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002507 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2508
2509 if (TypeParm)
2510 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002511
Chandler Carruth08836322011-05-01 00:51:33 +00002512 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002513 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002514 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002515
2516 TemplateTypeParmType *TypeCheck
2517 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2518 assert(!TypeCheck && "Template type parameter canonical type broken");
2519 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002520 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002521 TypeParm = new (*this, TypeAlignment)
2522 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002523
2524 Types.push_back(TypeParm);
2525 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2526
2527 return QualType(TypeParm, 0);
2528}
2529
John McCalle78aac42010-03-10 03:28:59 +00002530TypeSourceInfo *
2531ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2532 SourceLocation NameLoc,
2533 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002534 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002535 assert(!Name.getAsDependentTemplateName() &&
2536 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002537 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002538
2539 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2540 TemplateSpecializationTypeLoc TL
2541 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002542 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00002543 TL.setTemplateNameLoc(NameLoc);
2544 TL.setLAngleLoc(Args.getLAngleLoc());
2545 TL.setRAngleLoc(Args.getRAngleLoc());
2546 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2547 TL.setArgLocInfo(i, Args[i].getLocInfo());
2548 return DI;
2549}
2550
Mike Stump11289f42009-09-09 15:08:12 +00002551QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002552ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002553 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002554 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002555 assert(!Template.getAsDependentTemplateName() &&
2556 "No dependent template names here!");
2557
John McCall6b51f282009-11-23 01:53:49 +00002558 unsigned NumArgs = Args.size();
2559
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002560 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002561 ArgVec.reserve(NumArgs);
2562 for (unsigned i = 0; i != NumArgs; ++i)
2563 ArgVec.push_back(Args[i].getArgument());
2564
John McCall2408e322010-04-27 00:57:59 +00002565 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002566 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002567}
2568
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002569#ifndef NDEBUG
2570static bool hasAnyPackExpansions(const TemplateArgument *Args,
2571 unsigned NumArgs) {
2572 for (unsigned I = 0; I != NumArgs; ++I)
2573 if (Args[I].isPackExpansion())
2574 return true;
2575
2576 return true;
2577}
2578#endif
2579
John McCall0ad16662009-10-29 08:12:44 +00002580QualType
2581ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002582 const TemplateArgument *Args,
2583 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002584 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002585 assert(!Template.getAsDependentTemplateName() &&
2586 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002587 // Look through qualified template names.
2588 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2589 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002590
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002591 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00002592 Template.getAsTemplateDecl() &&
2593 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00002594 QualType CanonType;
2595 if (!Underlying.isNull())
2596 CanonType = getCanonicalType(Underlying);
2597 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002598 // We can get here with an alias template when the specialization contains
2599 // a pack expansion that does not match up with a parameter pack.
2600 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2601 "Caller must compute aliased type");
2602 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00002603 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2604 NumArgs);
2605 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002606
Douglas Gregora8e02e72009-07-28 23:00:59 +00002607 // Allocate the (non-canonical) template specialization type, but don't
2608 // try to unique it: these types typically have location information that
2609 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002610 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2611 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002612 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002613 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002614 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002615 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2616 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002617
Douglas Gregor8bf42052009-02-09 18:46:07 +00002618 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002619 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002620}
2621
Mike Stump11289f42009-09-09 15:08:12 +00002622QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002623ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2624 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002625 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002626 assert(!Template.getAsDependentTemplateName() &&
2627 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002628
Douglas Gregore29139c2011-03-03 17:04:51 +00002629 // Look through qualified template names.
2630 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2631 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002632
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002633 // Build the canonical template specialization type.
2634 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002635 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002636 CanonArgs.reserve(NumArgs);
2637 for (unsigned I = 0; I != NumArgs; ++I)
2638 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2639
2640 // Determine whether this canonical template specialization type already
2641 // exists.
2642 llvm::FoldingSetNodeID ID;
2643 TemplateSpecializationType::Profile(ID, CanonTemplate,
2644 CanonArgs.data(), NumArgs, *this);
2645
2646 void *InsertPos = 0;
2647 TemplateSpecializationType *Spec
2648 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2649
2650 if (!Spec) {
2651 // Allocate a new canonical template specialization type.
2652 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2653 sizeof(TemplateArgument) * NumArgs),
2654 TypeAlignment);
2655 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2656 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002657 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002658 Types.push_back(Spec);
2659 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2660 }
2661
2662 assert(Spec->isDependentType() &&
2663 "Non-dependent template-id type must have a canonical type");
2664 return QualType(Spec, 0);
2665}
2666
2667QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002668ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2669 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002670 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002671 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002672 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002673
2674 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002675 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002676 if (T)
2677 return QualType(T, 0);
2678
Douglas Gregorc42075a2010-02-04 18:10:26 +00002679 QualType Canon = NamedType;
2680 if (!Canon.isCanonical()) {
2681 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002682 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2683 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002684 (void)CheckT;
2685 }
2686
Abramo Bagnara6150c882010-05-11 21:36:43 +00002687 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002688 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002689 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002690 return QualType(T, 0);
2691}
2692
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002693QualType
Jay Foad39c79802011-01-12 09:06:06 +00002694ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002695 llvm::FoldingSetNodeID ID;
2696 ParenType::Profile(ID, InnerType);
2697
2698 void *InsertPos = 0;
2699 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2700 if (T)
2701 return QualType(T, 0);
2702
2703 QualType Canon = InnerType;
2704 if (!Canon.isCanonical()) {
2705 Canon = getCanonicalType(InnerType);
2706 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2707 assert(!CheckT && "Paren canonical type broken");
2708 (void)CheckT;
2709 }
2710
2711 T = new (*this) ParenType(InnerType, Canon);
2712 Types.push_back(T);
2713 ParenTypes.InsertNode(T, InsertPos);
2714 return QualType(T, 0);
2715}
2716
Douglas Gregor02085352010-03-31 20:19:30 +00002717QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2718 NestedNameSpecifier *NNS,
2719 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002720 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002721 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2722
2723 if (Canon.isNull()) {
2724 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002725 ElaboratedTypeKeyword CanonKeyword = Keyword;
2726 if (Keyword == ETK_None)
2727 CanonKeyword = ETK_Typename;
2728
2729 if (CanonNNS != NNS || CanonKeyword != Keyword)
2730 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002731 }
2732
2733 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002734 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002735
2736 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002737 DependentNameType *T
2738 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002739 if (T)
2740 return QualType(T, 0);
2741
Douglas Gregor02085352010-03-31 20:19:30 +00002742 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002743 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002744 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002745 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002746}
2747
Mike Stump11289f42009-09-09 15:08:12 +00002748QualType
John McCallc392f372010-06-11 00:33:02 +00002749ASTContext::getDependentTemplateSpecializationType(
2750 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002751 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002752 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002753 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002754 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002755 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00002756 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2757 ArgCopy.push_back(Args[I].getArgument());
2758 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2759 ArgCopy.size(),
2760 ArgCopy.data());
2761}
2762
2763QualType
2764ASTContext::getDependentTemplateSpecializationType(
2765 ElaboratedTypeKeyword Keyword,
2766 NestedNameSpecifier *NNS,
2767 const IdentifierInfo *Name,
2768 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002769 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00002770 assert((!NNS || NNS->isDependent()) &&
2771 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00002772
Douglas Gregorc42075a2010-02-04 18:10:26 +00002773 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002774 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2775 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002776
2777 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002778 DependentTemplateSpecializationType *T
2779 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002780 if (T)
2781 return QualType(T, 0);
2782
John McCallc392f372010-06-11 00:33:02 +00002783 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002784
John McCallc392f372010-06-11 00:33:02 +00002785 ElaboratedTypeKeyword CanonKeyword = Keyword;
2786 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2787
2788 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002789 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00002790 for (unsigned I = 0; I != NumArgs; ++I) {
2791 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2792 if (!CanonArgs[I].structurallyEquals(Args[I]))
2793 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002794 }
2795
John McCallc392f372010-06-11 00:33:02 +00002796 QualType Canon;
2797 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2798 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2799 Name, NumArgs,
2800 CanonArgs.data());
2801
2802 // Find the insert position again.
2803 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2804 }
2805
2806 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2807 sizeof(TemplateArgument) * NumArgs),
2808 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002809 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002810 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002811 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002812 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002813 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002814}
2815
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002816QualType ASTContext::getPackExpansionType(QualType Pattern,
2817 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002818 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002819 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002820
2821 assert(Pattern->containsUnexpandedParameterPack() &&
2822 "Pack expansions must expand one or more parameter packs");
2823 void *InsertPos = 0;
2824 PackExpansionType *T
2825 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2826 if (T)
2827 return QualType(T, 0);
2828
2829 QualType Canon;
2830 if (!Pattern.isCanonical()) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002831 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002832
2833 // Find the insert position again.
2834 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2835 }
2836
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002837 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002838 Types.push_back(T);
2839 PackExpansionTypes.InsertNode(T, InsertPos);
2840 return QualType(T, 0);
2841}
2842
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002843/// CmpProtocolNames - Comparison predicate for sorting protocols
2844/// alphabetically.
2845static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2846 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002847 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002848}
2849
John McCall8b07ec22010-05-15 11:32:37 +00002850static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002851 unsigned NumProtocols) {
2852 if (NumProtocols == 0) return true;
2853
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002854 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
2855 return false;
2856
John McCallfc93cf92009-10-22 22:37:11 +00002857 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002858 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
2859 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00002860 return false;
2861 return true;
2862}
2863
2864static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002865 unsigned &NumProtocols) {
2866 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002867
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002868 // Sort protocols, keyed by name.
2869 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2870
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002871 // Canonicalize.
2872 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
2873 Protocols[I] = Protocols[I]->getCanonicalDecl();
2874
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002875 // Remove duplicates.
2876 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2877 NumProtocols = ProtocolsEnd-Protocols;
2878}
2879
John McCall8b07ec22010-05-15 11:32:37 +00002880QualType ASTContext::getObjCObjectType(QualType BaseType,
2881 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002882 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002883 // If the base type is an interface and there aren't any protocols
2884 // to add, then the interface type will do just fine.
2885 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2886 return BaseType;
2887
2888 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002889 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002890 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002891 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002892 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2893 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002894
John McCall8b07ec22010-05-15 11:32:37 +00002895 // Build the canonical type, which has the canonical base type and
2896 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002897 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002898 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2899 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2900 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002901 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002902 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002903 unsigned UniqueCount = NumProtocols;
2904
John McCallfc93cf92009-10-22 22:37:11 +00002905 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002906 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2907 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002908 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002909 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2910 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002911 }
2912
2913 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002914 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2915 }
2916
2917 unsigned Size = sizeof(ObjCObjectTypeImpl);
2918 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2919 void *Mem = Allocate(Size, TypeAlignment);
2920 ObjCObjectTypeImpl *T =
2921 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2922
2923 Types.push_back(T);
2924 ObjCObjectTypes.InsertNode(T, InsertPos);
2925 return QualType(T, 0);
2926}
2927
2928/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2929/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00002930QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00002931 llvm::FoldingSetNodeID ID;
2932 ObjCObjectPointerType::Profile(ID, ObjectT);
2933
2934 void *InsertPos = 0;
2935 if (ObjCObjectPointerType *QT =
2936 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2937 return QualType(QT, 0);
2938
2939 // Find the canonical object type.
2940 QualType Canonical;
2941 if (!ObjectT.isCanonical()) {
2942 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2943
2944 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002945 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2946 }
2947
Douglas Gregorf85bee62010-02-08 22:59:26 +00002948 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002949 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2950 ObjCObjectPointerType *QType =
2951 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002952
Steve Narofffb4330f2009-06-17 22:40:22 +00002953 Types.push_back(QType);
2954 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002955 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002956}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002957
Douglas Gregor1c283312010-08-11 12:19:30 +00002958/// getObjCInterfaceType - Return the unique reference to the type for the
2959/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00002960QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
2961 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00002962 if (Decl->TypeForDecl)
2963 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002964
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00002965 if (PrevDecl) {
2966 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
2967 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2968 return QualType(PrevDecl->TypeForDecl, 0);
2969 }
2970
Douglas Gregor7671e532011-12-16 16:34:57 +00002971 // Prefer the definition, if there is one.
2972 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
2973 Decl = Def;
2974
Douglas Gregor1c283312010-08-11 12:19:30 +00002975 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2976 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2977 Decl->TypeForDecl = T;
2978 Types.push_back(T);
2979 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002980}
2981
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002982/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2983/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002984/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002985/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002986/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002987QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002988 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002989 if (tofExpr->isTypeDependent()) {
2990 llvm::FoldingSetNodeID ID;
2991 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002992
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002993 void *InsertPos = 0;
2994 DependentTypeOfExprType *Canon
2995 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2996 if (Canon) {
2997 // We already have a "canonical" version of an identical, dependent
2998 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002999 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003000 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003001 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003002 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003003 Canon
3004 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003005 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3006 toe = Canon;
3007 }
3008 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003009 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003010 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003011 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003012 Types.push_back(toe);
3013 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003014}
3015
Steve Naroffa773cd52007-08-01 18:02:17 +00003016/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3017/// TypeOfType AST's. The only motivation to unique these nodes would be
3018/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003019/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003020/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003021QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003022 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003023 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003024 Types.push_back(tot);
3025 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003026}
3027
Anders Carlssonad6bd352009-06-24 21:24:56 +00003028
Anders Carlsson81df7b82009-06-24 19:06:50 +00003029/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3030/// DecltypeType AST's. The only motivation to unique these nodes would be
3031/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003032/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003033/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003034QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003035 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003036
3037 // C++0x [temp.type]p2:
3038 // If an expression e involves a template parameter, decltype(e) denotes a
3039 // unique dependent type. Two such decltype-specifiers refer to the same
3040 // type only if their expressions are equivalent (14.5.6.1).
3041 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003042 llvm::FoldingSetNodeID ID;
3043 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003044
Douglas Gregora21f6c32009-07-30 23:36:40 +00003045 void *InsertPos = 0;
3046 DependentDecltypeType *Canon
3047 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3048 if (Canon) {
3049 // We already have a "canonical" version of an equivalent, dependent
3050 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003051 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003052 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003053 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003054 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003055 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003056 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3057 dt = Canon;
3058 }
3059 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003060 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3061 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003062 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003063 Types.push_back(dt);
3064 return QualType(dt, 0);
3065}
3066
Alexis Hunte852b102011-05-24 22:41:36 +00003067/// getUnaryTransformationType - We don't unique these, since the memory
3068/// savings are minimal and these are rare.
3069QualType ASTContext::getUnaryTransformType(QualType BaseType,
3070 QualType UnderlyingType,
3071 UnaryTransformType::UTTKind Kind)
3072 const {
3073 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003074 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3075 Kind,
3076 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003077 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003078 Types.push_back(Ty);
3079 return QualType(Ty, 0);
3080}
3081
Richard Smithb2bc2e62011-02-21 20:05:19 +00003082/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003083QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00003084 void *InsertPos = 0;
3085 if (!DeducedType.isNull()) {
3086 // Look in the folding set for an existing type.
3087 llvm::FoldingSetNodeID ID;
3088 AutoType::Profile(ID, DeducedType);
3089 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3090 return QualType(AT, 0);
3091 }
3092
3093 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3094 Types.push_back(AT);
3095 if (InsertPos)
3096 AutoTypes.InsertNode(AT, InsertPos);
3097 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003098}
3099
Eli Friedman0dfb8892011-10-06 23:00:33 +00003100/// getAtomicType - Return the uniqued reference to the atomic type for
3101/// the given value type.
3102QualType ASTContext::getAtomicType(QualType T) const {
3103 // Unique pointers, to guarantee there is only one pointer of a particular
3104 // structure.
3105 llvm::FoldingSetNodeID ID;
3106 AtomicType::Profile(ID, T);
3107
3108 void *InsertPos = 0;
3109 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3110 return QualType(AT, 0);
3111
3112 // If the atomic value type isn't canonical, this won't be a canonical type
3113 // either, so fill in the canonical type field.
3114 QualType Canonical;
3115 if (!T.isCanonical()) {
3116 Canonical = getAtomicType(getCanonicalType(T));
3117
3118 // Get the new insert position for the node we care about.
3119 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3120 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3121 }
3122 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3123 Types.push_back(New);
3124 AtomicTypes.InsertNode(New, InsertPos);
3125 return QualType(New, 0);
3126}
3127
Richard Smith02e85f32011-04-14 22:09:26 +00003128/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3129QualType ASTContext::getAutoDeductType() const {
3130 if (AutoDeductTy.isNull())
3131 AutoDeductTy = getAutoType(QualType());
3132 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3133 return AutoDeductTy;
3134}
3135
3136/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3137QualType ASTContext::getAutoRRefDeductType() const {
3138 if (AutoRRefDeductTy.isNull())
3139 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3140 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3141 return AutoRRefDeductTy;
3142}
3143
Chris Lattnerfb072462007-01-23 05:45:31 +00003144/// getTagDeclType - Return the unique reference to the type for the
3145/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003146QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003147 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003148 // FIXME: What is the design on getTagDeclType when it requires casting
3149 // away const? mutable?
3150 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003151}
3152
Mike Stump11289f42009-09-09 15:08:12 +00003153/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3154/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3155/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003156CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003157 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003158}
Chris Lattnerfb072462007-01-23 05:45:31 +00003159
Hans Wennborg27541db2011-10-27 08:29:09 +00003160/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3161CanQualType ASTContext::getIntMaxType() const {
3162 return getFromTargetType(Target->getIntMaxType());
3163}
3164
3165/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3166CanQualType ASTContext::getUIntMaxType() const {
3167 return getFromTargetType(Target->getUIntMaxType());
3168}
3169
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003170/// getSignedWCharType - Return the type of "signed wchar_t".
3171/// Used when in C++, as a GCC extension.
3172QualType ASTContext::getSignedWCharType() const {
3173 // FIXME: derive from "Target" ?
3174 return WCharTy;
3175}
3176
3177/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3178/// Used when in C++, as a GCC extension.
3179QualType ASTContext::getUnsignedWCharType() const {
3180 // FIXME: derive from "Target" ?
3181 return UnsignedIntTy;
3182}
3183
Hans Wennborg27541db2011-10-27 08:29:09 +00003184/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003185/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3186QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003187 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003188}
3189
Chris Lattnera21ad802008-04-02 05:18:44 +00003190//===----------------------------------------------------------------------===//
3191// Type Operators
3192//===----------------------------------------------------------------------===//
3193
Jay Foad39c79802011-01-12 09:06:06 +00003194CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003195 // Push qualifiers into arrays, and then discard any remaining
3196 // qualifiers.
3197 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003198 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003199 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003200 QualType Result;
3201 if (isa<ArrayType>(Ty)) {
3202 Result = getArrayDecayedType(QualType(Ty,0));
3203 } else if (isa<FunctionType>(Ty)) {
3204 Result = getPointerType(QualType(Ty, 0));
3205 } else {
3206 Result = QualType(Ty, 0);
3207 }
3208
3209 return CanQualType::CreateUnsafe(Result);
3210}
3211
John McCall6c9dd522011-01-18 07:41:22 +00003212QualType ASTContext::getUnqualifiedArrayType(QualType type,
3213 Qualifiers &quals) {
3214 SplitQualType splitType = type.getSplitUnqualifiedType();
3215
3216 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3217 // the unqualified desugared type and then drops it on the floor.
3218 // We then have to strip that sugar back off with
3219 // getUnqualifiedDesugaredType(), which is silly.
3220 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003221 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003222
3223 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003224 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003225 quals = splitType.Quals;
3226 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003227 }
3228
John McCall6c9dd522011-01-18 07:41:22 +00003229 // Otherwise, recurse on the array's element type.
3230 QualType elementType = AT->getElementType();
3231 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3232
3233 // If that didn't change the element type, AT has no qualifiers, so we
3234 // can just use the results in splitType.
3235 if (elementType == unqualElementType) {
3236 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003237 quals = splitType.Quals;
3238 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003239 }
3240
3241 // Otherwise, add in the qualifiers from the outermost type, then
3242 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003243 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003244
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003245 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003246 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003247 CAT->getSizeModifier(), 0);
3248 }
3249
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003250 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003251 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003252 }
3253
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003254 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003255 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003256 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003257 VAT->getSizeModifier(),
3258 VAT->getIndexTypeCVRQualifiers(),
3259 VAT->getBracketsRange());
3260 }
3261
3262 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003263 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003264 DSAT->getSizeModifier(), 0,
3265 SourceRange());
3266}
3267
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003268/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3269/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3270/// they point to and return true. If T1 and T2 aren't pointer types
3271/// or pointer-to-member types, or if they are not similar at this
3272/// level, returns false and leaves T1 and T2 unchanged. Top-level
3273/// qualifiers on T1 and T2 are ignored. This function will typically
3274/// be called in a loop that successively "unwraps" pointer and
3275/// pointer-to-member types to compare them at each level.
3276bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3277 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3278 *T2PtrType = T2->getAs<PointerType>();
3279 if (T1PtrType && T2PtrType) {
3280 T1 = T1PtrType->getPointeeType();
3281 T2 = T2PtrType->getPointeeType();
3282 return true;
3283 }
3284
3285 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3286 *T2MPType = T2->getAs<MemberPointerType>();
3287 if (T1MPType && T2MPType &&
3288 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3289 QualType(T2MPType->getClass(), 0))) {
3290 T1 = T1MPType->getPointeeType();
3291 T2 = T2MPType->getPointeeType();
3292 return true;
3293 }
3294
David Blaikiebbafb8a2012-03-11 07:00:24 +00003295 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003296 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3297 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3298 if (T1OPType && T2OPType) {
3299 T1 = T1OPType->getPointeeType();
3300 T2 = T2OPType->getPointeeType();
3301 return true;
3302 }
3303 }
3304
3305 // FIXME: Block pointers, too?
3306
3307 return false;
3308}
3309
Jay Foad39c79802011-01-12 09:06:06 +00003310DeclarationNameInfo
3311ASTContext::getNameForTemplate(TemplateName Name,
3312 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003313 switch (Name.getKind()) {
3314 case TemplateName::QualifiedTemplate:
3315 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003316 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003317 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3318 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003319
John McCalld9dfe3a2011-06-30 08:33:18 +00003320 case TemplateName::OverloadedTemplate: {
3321 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3322 // DNInfo work in progress: CHECKME: what about DNLoc?
3323 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3324 }
3325
3326 case TemplateName::DependentTemplate: {
3327 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003328 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003329 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003330 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3331 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003332 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003333 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3334 // DNInfo work in progress: FIXME: source locations?
3335 DeclarationNameLoc DNLoc;
3336 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3337 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3338 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003339 }
3340 }
3341
John McCalld9dfe3a2011-06-30 08:33:18 +00003342 case TemplateName::SubstTemplateTemplateParm: {
3343 SubstTemplateTemplateParmStorage *subst
3344 = Name.getAsSubstTemplateTemplateParm();
3345 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3346 NameLoc);
3347 }
3348
3349 case TemplateName::SubstTemplateTemplateParmPack: {
3350 SubstTemplateTemplateParmPackStorage *subst
3351 = Name.getAsSubstTemplateTemplateParmPack();
3352 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3353 NameLoc);
3354 }
3355 }
3356
3357 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003358}
3359
Jay Foad39c79802011-01-12 09:06:06 +00003360TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003361 switch (Name.getKind()) {
3362 case TemplateName::QualifiedTemplate:
3363 case TemplateName::Template: {
3364 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003365 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003366 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003367 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3368
3369 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003370 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003371 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003372
John McCalld9dfe3a2011-06-30 08:33:18 +00003373 case TemplateName::OverloadedTemplate:
3374 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003375
John McCalld9dfe3a2011-06-30 08:33:18 +00003376 case TemplateName::DependentTemplate: {
3377 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3378 assert(DTN && "Non-dependent template names must refer to template decls.");
3379 return DTN->CanonicalTemplateName;
3380 }
3381
3382 case TemplateName::SubstTemplateTemplateParm: {
3383 SubstTemplateTemplateParmStorage *subst
3384 = Name.getAsSubstTemplateTemplateParm();
3385 return getCanonicalTemplateName(subst->getReplacement());
3386 }
3387
3388 case TemplateName::SubstTemplateTemplateParmPack: {
3389 SubstTemplateTemplateParmPackStorage *subst
3390 = Name.getAsSubstTemplateTemplateParmPack();
3391 TemplateTemplateParmDecl *canonParameter
3392 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3393 TemplateArgument canonArgPack
3394 = getCanonicalTemplateArgument(subst->getArgumentPack());
3395 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3396 }
3397 }
3398
3399 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003400}
3401
Douglas Gregoradee3e32009-11-11 23:06:43 +00003402bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3403 X = getCanonicalTemplateName(X);
3404 Y = getCanonicalTemplateName(Y);
3405 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3406}
3407
Mike Stump11289f42009-09-09 15:08:12 +00003408TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003409ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003410 switch (Arg.getKind()) {
3411 case TemplateArgument::Null:
3412 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003413
Douglas Gregora8e02e72009-07-28 23:00:59 +00003414 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003415 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003416
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003417 case TemplateArgument::Declaration: {
3418 if (Decl *D = Arg.getAsDecl())
3419 return TemplateArgument(D->getCanonicalDecl());
3420 return TemplateArgument((Decl*)0);
3421 }
Mike Stump11289f42009-09-09 15:08:12 +00003422
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003423 case TemplateArgument::Template:
3424 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003425
3426 case TemplateArgument::TemplateExpansion:
3427 return TemplateArgument(getCanonicalTemplateName(
3428 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003429 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003430
Douglas Gregora8e02e72009-07-28 23:00:59 +00003431 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00003432 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003433
Douglas Gregora8e02e72009-07-28 23:00:59 +00003434 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003435 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003436
Douglas Gregora8e02e72009-07-28 23:00:59 +00003437 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003438 if (Arg.pack_size() == 0)
3439 return Arg;
3440
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003441 TemplateArgument *CanonArgs
3442 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003443 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003444 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003445 AEnd = Arg.pack_end();
3446 A != AEnd; (void)++A, ++Idx)
3447 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003448
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003449 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003450 }
3451 }
3452
3453 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003454 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003455}
3456
Douglas Gregor333489b2009-03-27 23:10:48 +00003457NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003458ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003459 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003460 return 0;
3461
3462 switch (NNS->getKind()) {
3463 case NestedNameSpecifier::Identifier:
3464 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003465 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003466 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3467 NNS->getAsIdentifier());
3468
3469 case NestedNameSpecifier::Namespace:
3470 // A namespace is canonical; build a nested-name-specifier with
3471 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003472 return NestedNameSpecifier::Create(*this, 0,
3473 NNS->getAsNamespace()->getOriginalNamespace());
3474
3475 case NestedNameSpecifier::NamespaceAlias:
3476 // A namespace is canonical; build a nested-name-specifier with
3477 // this namespace and no prefix.
3478 return NestedNameSpecifier::Create(*this, 0,
3479 NNS->getAsNamespaceAlias()->getNamespace()
3480 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003481
3482 case NestedNameSpecifier::TypeSpec:
3483 case NestedNameSpecifier::TypeSpecWithTemplate: {
3484 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003485
3486 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3487 // break it apart into its prefix and identifier, then reconsititute those
3488 // as the canonical nested-name-specifier. This is required to canonicalize
3489 // a dependent nested-name-specifier involving typedefs of dependent-name
3490 // types, e.g.,
3491 // typedef typename T::type T1;
3492 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00003493 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3494 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00003495 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003496
Eli Friedman5358a0a2012-03-03 04:09:56 +00003497 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3498 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3499 // first place?
John McCall33ddac02011-01-19 10:06:00 +00003500 return NestedNameSpecifier::Create(*this, 0, false,
3501 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003502 }
3503
3504 case NestedNameSpecifier::Global:
3505 // The global specifier is canonical and unique.
3506 return NNS;
3507 }
3508
David Blaikie8a40f702012-01-17 06:56:22 +00003509 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00003510}
3511
Chris Lattner7adf0762008-08-04 07:31:14 +00003512
Jay Foad39c79802011-01-12 09:06:06 +00003513const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003514 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003515 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003516 // Handle the common positive case fast.
3517 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3518 return AT;
3519 }
Mike Stump11289f42009-09-09 15:08:12 +00003520
John McCall8ccfcb52009-09-24 19:53:00 +00003521 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003522 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003523 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003524
John McCall8ccfcb52009-09-24 19:53:00 +00003525 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003526 // implements C99 6.7.3p8: "If the specification of an array type includes
3527 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003528
Chris Lattner7adf0762008-08-04 07:31:14 +00003529 // If we get here, we either have type qualifiers on the type, or we have
3530 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003531 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003532
John McCall33ddac02011-01-19 10:06:00 +00003533 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003534 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00003535
Chris Lattner7adf0762008-08-04 07:31:14 +00003536 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00003537 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00003538 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003539 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003540
Chris Lattner7adf0762008-08-04 07:31:14 +00003541 // Otherwise, we have an array and we have qualifiers on it. Push the
3542 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003543 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003544
Chris Lattner7adf0762008-08-04 07:31:14 +00003545 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3546 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3547 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003548 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003549 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3550 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3551 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003552 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003553
Mike Stump11289f42009-09-09 15:08:12 +00003554 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003555 = dyn_cast<DependentSizedArrayType>(ATy))
3556 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003557 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003558 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003559 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003560 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003561 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003562
Chris Lattner7adf0762008-08-04 07:31:14 +00003563 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003564 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003565 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003566 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003567 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003568 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003569}
3570
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003571QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003572 // C99 6.7.5.3p7:
3573 // A declaration of a parameter as "array of type" shall be
3574 // adjusted to "qualified pointer to type", where the type
3575 // qualifiers (if any) are those specified within the [ and ] of
3576 // the array type derivation.
3577 if (T->isArrayType())
3578 return getArrayDecayedType(T);
3579
3580 // C99 6.7.5.3p8:
3581 // A declaration of a parameter as "function returning type"
3582 // shall be adjusted to "pointer to function returning type", as
3583 // in 6.3.2.1.
3584 if (T->isFunctionType())
3585 return getPointerType(T);
3586
3587 return T;
3588}
3589
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003590QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003591 T = getVariableArrayDecayedType(T);
3592 T = getAdjustedParameterType(T);
3593 return T.getUnqualifiedType();
3594}
3595
Chris Lattnera21ad802008-04-02 05:18:44 +00003596/// getArrayDecayedType - Return the properly qualified result of decaying the
3597/// specified array type to a pointer. This operation is non-trivial when
3598/// handling typedefs etc. The canonical type of "T" must be an array type,
3599/// this returns a pointer to a properly qualified element of the array.
3600///
3601/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003602QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003603 // Get the element type with 'getAsArrayType' so that we don't lose any
3604 // typedefs in the element type of the array. This also handles propagation
3605 // of type qualifiers from the array type into the element type if present
3606 // (C99 6.7.3p8).
3607 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3608 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003609
Chris Lattner7adf0762008-08-04 07:31:14 +00003610 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003611
3612 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003613 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003614}
3615
John McCall33ddac02011-01-19 10:06:00 +00003616QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3617 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003618}
3619
John McCall33ddac02011-01-19 10:06:00 +00003620QualType ASTContext::getBaseElementType(QualType type) const {
3621 Qualifiers qs;
3622 while (true) {
3623 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003624 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00003625 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003626
John McCall33ddac02011-01-19 10:06:00 +00003627 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00003628 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003629 }
Mike Stump11289f42009-09-09 15:08:12 +00003630
John McCall33ddac02011-01-19 10:06:00 +00003631 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003632}
3633
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003634/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003635uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003636ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3637 uint64_t ElementCount = 1;
3638 do {
3639 ElementCount *= CA->getSize().getZExtValue();
3640 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3641 } while (CA);
3642 return ElementCount;
3643}
3644
Steve Naroff0af91202007-04-27 21:51:21 +00003645/// getFloatingRank - Return a relative rank for floating point types.
3646/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003647static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003648 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003649 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003650
John McCall9dd450b2009-09-21 23:43:11 +00003651 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3652 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003653 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003654 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00003655 case BuiltinType::Float: return FloatRank;
3656 case BuiltinType::Double: return DoubleRank;
3657 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003658 }
3659}
3660
Mike Stump11289f42009-09-09 15:08:12 +00003661/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3662/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003663/// 'typeDomain' is a real floating point or complex type.
3664/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003665QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3666 QualType Domain) const {
3667 FloatingRank EltRank = getFloatingRank(Size);
3668 if (Domain->isComplexType()) {
3669 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003670 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00003671 case FloatRank: return FloatComplexTy;
3672 case DoubleRank: return DoubleComplexTy;
3673 case LongDoubleRank: return LongDoubleComplexTy;
3674 }
Steve Naroff0af91202007-04-27 21:51:21 +00003675 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003676
3677 assert(Domain->isRealFloatingType() && "Unknown domain!");
3678 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003679 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003680 case FloatRank: return FloatTy;
3681 case DoubleRank: return DoubleTy;
3682 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003683 }
David Blaikief47fa302012-01-17 02:30:50 +00003684 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00003685}
3686
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003687/// getFloatingTypeOrder - Compare the rank of the two specified floating
3688/// point types, ignoring the domain of the type (i.e. 'double' ==
3689/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003690/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003691int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003692 FloatingRank LHSR = getFloatingRank(LHS);
3693 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003694
Chris Lattnerb90739d2008-04-06 23:38:49 +00003695 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003696 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003697 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003698 return 1;
3699 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003700}
3701
Chris Lattner76a00cf2008-04-06 22:59:24 +00003702/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3703/// routine will assert if passed a built-in type that isn't an integer or enum,
3704/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003705unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003706 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003707
Chris Lattner76a00cf2008-04-06 22:59:24 +00003708 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003709 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003710 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003711 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003712 case BuiltinType::Char_S:
3713 case BuiltinType::Char_U:
3714 case BuiltinType::SChar:
3715 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003716 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003717 case BuiltinType::Short:
3718 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003719 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003720 case BuiltinType::Int:
3721 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003722 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003723 case BuiltinType::Long:
3724 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003725 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003726 case BuiltinType::LongLong:
3727 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003728 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003729 case BuiltinType::Int128:
3730 case BuiltinType::UInt128:
3731 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003732 }
3733}
3734
Eli Friedman629ffb92009-08-20 04:21:42 +00003735/// \brief Whether this is a promotable bitfield reference according
3736/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3737///
3738/// \returns the type this bit-field will promote to, or NULL if no
3739/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003740QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003741 if (E->isTypeDependent() || E->isValueDependent())
3742 return QualType();
3743
Eli Friedman629ffb92009-08-20 04:21:42 +00003744 FieldDecl *Field = E->getBitField();
3745 if (!Field)
3746 return QualType();
3747
3748 QualType FT = Field->getType();
3749
Richard Smithcaf33902011-10-10 18:28:20 +00003750 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00003751 uint64_t IntSize = getTypeSize(IntTy);
3752 // GCC extension compatibility: if the bit-field size is less than or equal
3753 // to the size of int, it gets promoted no matter what its type is.
3754 // For instance, unsigned long bf : 4 gets promoted to signed int.
3755 if (BitWidth < IntSize)
3756 return IntTy;
3757
3758 if (BitWidth == IntSize)
3759 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3760
3761 // Types bigger than int are not subject to promotions, and therefore act
3762 // like the base type.
3763 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3764 // is ridiculous.
3765 return QualType();
3766}
3767
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003768/// getPromotedIntegerType - Returns the type that Promotable will
3769/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3770/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003771QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003772 assert(!Promotable.isNull());
3773 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003774 if (const EnumType *ET = Promotable->getAs<EnumType>())
3775 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00003776
3777 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3778 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3779 // (3.9.1) can be converted to a prvalue of the first of the following
3780 // types that can represent all the values of its underlying type:
3781 // int, unsigned int, long int, unsigned long int, long long int, or
3782 // unsigned long long int [...]
3783 // FIXME: Is there some better way to compute this?
3784 if (BT->getKind() == BuiltinType::WChar_S ||
3785 BT->getKind() == BuiltinType::WChar_U ||
3786 BT->getKind() == BuiltinType::Char16 ||
3787 BT->getKind() == BuiltinType::Char32) {
3788 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3789 uint64_t FromSize = getTypeSize(BT);
3790 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3791 LongLongTy, UnsignedLongLongTy };
3792 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3793 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3794 if (FromSize < ToSize ||
3795 (FromSize == ToSize &&
3796 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3797 return PromoteTypes[Idx];
3798 }
3799 llvm_unreachable("char type should fit into long long");
3800 }
3801 }
3802
3803 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003804 if (Promotable->isSignedIntegerType())
3805 return IntTy;
3806 uint64_t PromotableSize = getTypeSize(Promotable);
3807 uint64_t IntSize = getTypeSize(IntTy);
3808 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3809 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3810}
3811
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003812/// \brief Recurses in pointer/array types until it finds an objc retainable
3813/// type and returns its ownership.
3814Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3815 while (!T.isNull()) {
3816 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3817 return T.getObjCLifetime();
3818 if (T->isArrayType())
3819 T = getBaseElementType(T);
3820 else if (const PointerType *PT = T->getAs<PointerType>())
3821 T = PT->getPointeeType();
3822 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00003823 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003824 else
3825 break;
3826 }
3827
3828 return Qualifiers::OCL_None;
3829}
3830
Mike Stump11289f42009-09-09 15:08:12 +00003831/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003832/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003833/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003834int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00003835 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3836 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003837 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003838
Chris Lattner76a00cf2008-04-06 22:59:24 +00003839 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3840 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003841
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003842 unsigned LHSRank = getIntegerRank(LHSC);
3843 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003844
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003845 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3846 if (LHSRank == RHSRank) return 0;
3847 return LHSRank > RHSRank ? 1 : -1;
3848 }
Mike Stump11289f42009-09-09 15:08:12 +00003849
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003850 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3851 if (LHSUnsigned) {
3852 // If the unsigned [LHS] type is larger, return it.
3853 if (LHSRank >= RHSRank)
3854 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003855
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003856 // If the signed type can represent all values of the unsigned type, it
3857 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003858 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003859 return -1;
3860 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003861
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003862 // If the unsigned [RHS] type is larger, return it.
3863 if (RHSRank >= LHSRank)
3864 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003865
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003866 // If the signed type can represent all values of the unsigned type, it
3867 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003868 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003869 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003870}
Anders Carlsson98f07902007-08-17 05:31:46 +00003871
Anders Carlsson6d417272009-11-14 21:45:58 +00003872static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003873CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3874 DeclContext *DC, IdentifierInfo *Id) {
3875 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003876 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003877 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003878 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003879 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003880}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003881
Mike Stump11289f42009-09-09 15:08:12 +00003882// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003883QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003884 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003885 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003886 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003887 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003888 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003889
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003890 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003891
Anders Carlsson98f07902007-08-17 05:31:46 +00003892 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003893 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003894 // int flags;
3895 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003896 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003897 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003898 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003899 FieldTypes[3] = LongTy;
3900
Anders Carlsson98f07902007-08-17 05:31:46 +00003901 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003902 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003903 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003904 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00003905 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003906 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003907 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003908 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003909 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00003910 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003911 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003912 }
3913
Douglas Gregord5058122010-02-11 01:19:42 +00003914 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003915 }
Mike Stump11289f42009-09-09 15:08:12 +00003916
Anders Carlsson98f07902007-08-17 05:31:46 +00003917 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003918}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003919
Douglas Gregor512b0772009-04-23 22:29:11 +00003920void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003921 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003922 assert(Rec && "Invalid CFConstantStringType");
3923 CFConstantStringTypeDecl = Rec->getDecl();
3924}
3925
Jay Foad39c79802011-01-12 09:06:06 +00003926QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003927 if (BlockDescriptorType)
3928 return getTagDeclType(BlockDescriptorType);
3929
3930 RecordDecl *T;
3931 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003932 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003933 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003934 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003935
3936 QualType FieldTypes[] = {
3937 UnsignedLongTy,
3938 UnsignedLongTy,
3939 };
3940
3941 const char *FieldNames[] = {
3942 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003943 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003944 };
3945
3946 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003947 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003948 SourceLocation(),
3949 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003950 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003951 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003952 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003953 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00003954 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003955 T->addDecl(Field);
3956 }
3957
Douglas Gregord5058122010-02-11 01:19:42 +00003958 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003959
3960 BlockDescriptorType = T;
3961
3962 return getTagDeclType(BlockDescriptorType);
3963}
3964
Jay Foad39c79802011-01-12 09:06:06 +00003965QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003966 if (BlockDescriptorExtendedType)
3967 return getTagDeclType(BlockDescriptorExtendedType);
3968
3969 RecordDecl *T;
3970 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003971 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003972 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003973 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003974
3975 QualType FieldTypes[] = {
3976 UnsignedLongTy,
3977 UnsignedLongTy,
3978 getPointerType(VoidPtrTy),
3979 getPointerType(VoidPtrTy)
3980 };
3981
3982 const char *FieldNames[] = {
3983 "reserved",
3984 "Size",
3985 "CopyFuncPtr",
3986 "DestroyFuncPtr"
3987 };
3988
3989 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003990 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003991 SourceLocation(),
3992 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003993 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003994 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003995 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003996 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00003997 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003998 T->addDecl(Field);
3999 }
4000
Douglas Gregord5058122010-02-11 01:19:42 +00004001 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004002
4003 BlockDescriptorExtendedType = T;
4004
4005 return getTagDeclType(BlockDescriptorExtendedType);
4006}
4007
Jay Foad39c79802011-01-12 09:06:06 +00004008bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCall31168b02011-06-15 23:02:42 +00004009 if (Ty->isObjCRetainableType())
Mike Stump94967902009-10-21 18:16:27 +00004010 return true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004011 if (getLangOpts().CPlusPlus) {
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004012 if (const RecordType *RT = Ty->getAs<RecordType>()) {
4013 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntfcaeae42011-05-25 20:50:04 +00004014 return RD->hasConstCopyConstructor();
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004015
4016 }
4017 }
Mike Stump94967902009-10-21 18:16:27 +00004018 return false;
4019}
4020
Jay Foad39c79802011-01-12 09:06:06 +00004021QualType
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004022ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00004023 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00004024 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00004025 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00004026 // unsigned int __flags;
4027 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00004028 // void *__copy_helper; // as needed
4029 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00004030 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00004031 // } *
4032
Mike Stump94967902009-10-21 18:16:27 +00004033 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
4034
4035 // FIXME: Move up
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004036 SmallString<36> Name;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00004037 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
4038 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00004039 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004040 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00004041 T->startDefinition();
4042 QualType Int32Ty = IntTy;
4043 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
4044 QualType FieldTypes[] = {
4045 getPointerType(VoidPtrTy),
4046 getPointerType(getTagDeclType(T)),
4047 Int32Ty,
4048 Int32Ty,
4049 getPointerType(VoidPtrTy),
4050 getPointerType(VoidPtrTy),
4051 Ty
4052 };
4053
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004054 StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00004055 "__isa",
4056 "__forwarding",
4057 "__flags",
4058 "__size",
4059 "__copy_helper",
4060 "__destroy_helper",
4061 DeclName,
4062 };
4063
4064 for (size_t i = 0; i < 7; ++i) {
4065 if (!HasCopyAndDispose && i >=4 && i <= 5)
4066 continue;
4067 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00004068 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00004069 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004070 FieldTypes[i], /*TInfo=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004071 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004072 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004073 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00004074 T->addDecl(Field);
4075 }
4076
Douglas Gregord5058122010-02-11 01:19:42 +00004077 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00004078
4079 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00004080}
4081
Douglas Gregorbab8a962011-09-08 01:46:34 +00004082TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4083 if (!ObjCInstanceTypeDecl)
4084 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4085 getTranslationUnitDecl(),
4086 SourceLocation(),
4087 SourceLocation(),
4088 &Idents.get("instancetype"),
4089 getTrivialTypeSourceInfo(getObjCIdType()));
4090 return ObjCInstanceTypeDecl;
4091}
4092
Anders Carlsson18acd442007-10-29 06:33:42 +00004093// This returns true if a type has been typedefed to BOOL:
4094// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004095static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004096 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004097 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4098 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004099
Anders Carlssond8499822007-10-29 05:01:08 +00004100 return false;
4101}
4102
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004103/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004104/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004105CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004106 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4107 return CharUnits::Zero();
4108
Ken Dyck40775002010-01-11 17:06:35 +00004109 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004110
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004111 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004112 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004113 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004114 // Treat arrays as pointers, since that's how they're passed in.
4115 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004116 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004117 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004118}
4119
4120static inline
4121std::string charUnitsToString(const CharUnits &CU) {
4122 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004123}
4124
John McCall351762c2011-02-07 10:33:21 +00004125/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004126/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004127std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4128 std::string S;
4129
David Chisnall950a9512009-11-17 19:33:30 +00004130 const BlockDecl *Decl = Expr->getBlockDecl();
4131 QualType BlockTy =
4132 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4133 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00004134 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004135 // Compute size of all parameters.
4136 // Start with computing size of a pointer in number of bytes.
4137 // FIXME: There might(should) be a better way of doing this computation!
4138 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004139 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4140 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004141 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004142 E = Decl->param_end(); PI != E; ++PI) {
4143 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004144 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00004145 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004146 ParmOffset += sz;
4147 }
4148 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004149 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004150 // Block pointer and offset.
4151 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004152
4153 // Argument types.
4154 ParmOffset = PtrSize;
4155 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4156 Decl->param_end(); PI != E; ++PI) {
4157 ParmVarDecl *PVDecl = *PI;
4158 QualType PType = PVDecl->getOriginalType();
4159 if (const ArrayType *AT =
4160 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4161 // Use array's original type only if it has known number of
4162 // elements.
4163 if (!isa<ConstantArrayType>(AT))
4164 PType = PVDecl->getType();
4165 } else if (PType->isFunctionType())
4166 PType = PVDecl->getType();
4167 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004168 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004169 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004170 }
John McCall351762c2011-02-07 10:33:21 +00004171
4172 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004173}
4174
Douglas Gregora9d84932011-05-27 01:19:52 +00004175bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004176 std::string& S) {
4177 // Encode result type.
4178 getObjCEncodingForType(Decl->getResultType(), S);
4179 CharUnits ParmOffset;
4180 // Compute size of all parameters.
4181 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4182 E = Decl->param_end(); PI != E; ++PI) {
4183 QualType PType = (*PI)->getType();
4184 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004185 if (sz.isZero())
4186 return true;
4187
David Chisnall50e4eba2010-12-30 14:05:53 +00004188 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004189 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004190 ParmOffset += sz;
4191 }
4192 S += charUnitsToString(ParmOffset);
4193 ParmOffset = CharUnits::Zero();
4194
4195 // Argument types.
4196 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4197 E = Decl->param_end(); PI != E; ++PI) {
4198 ParmVarDecl *PVDecl = *PI;
4199 QualType PType = PVDecl->getOriginalType();
4200 if (const ArrayType *AT =
4201 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4202 // Use array's original type only if it has known number of
4203 // elements.
4204 if (!isa<ConstantArrayType>(AT))
4205 PType = PVDecl->getType();
4206 } else if (PType->isFunctionType())
4207 PType = PVDecl->getType();
4208 getObjCEncodingForType(PType, S);
4209 S += charUnitsToString(ParmOffset);
4210 ParmOffset += getObjCEncodingTypeSize(PType);
4211 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004212
4213 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004214}
4215
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004216/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4217/// method parameter or return type. If Extended, include class names and
4218/// block object types.
4219void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4220 QualType T, std::string& S,
4221 bool Extended) const {
4222 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4223 getObjCEncodingForTypeQualifier(QT, S);
4224 // Encode parameter type.
4225 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4226 true /*OutermostType*/,
4227 false /*EncodingProperty*/,
4228 false /*StructField*/,
4229 Extended /*EncodeBlockParameters*/,
4230 Extended /*EncodeClassNames*/);
4231}
4232
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004233/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004234/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004235bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004236 std::string& S,
4237 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004238 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004239 // Encode return type.
4240 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4241 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004242 // Compute size of all parameters.
4243 // Start with computing size of a pointer in number of bytes.
4244 // FIXME: There might(should) be a better way of doing this computation!
4245 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004246 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004247 // The first two arguments (self and _cmd) are pointers; account for
4248 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004249 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004250 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004251 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004252 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004253 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004254 if (sz.isZero())
4255 return true;
4256
Ken Dyck40775002010-01-11 17:06:35 +00004257 assert (sz.isPositive() &&
4258 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004259 ParmOffset += sz;
4260 }
Ken Dyck40775002010-01-11 17:06:35 +00004261 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004262 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004263 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004264
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004265 // Argument types.
4266 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004267 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004268 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004269 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004270 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004271 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004272 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4273 // Use array's original type only if it has known number of
4274 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004275 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004276 PType = PVDecl->getType();
4277 } else if (PType->isFunctionType())
4278 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004279 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4280 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004281 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004282 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004283 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004284
4285 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004286}
4287
Daniel Dunbar4932b362008-08-28 04:38:10 +00004288/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004289/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004290/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4291/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004292/// Property attributes are stored as a comma-delimited C string. The simple
4293/// attributes readonly and bycopy are encoded as single characters. The
4294/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4295/// encoded as single characters, followed by an identifier. Property types
4296/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004297/// these attributes are defined by the following enumeration:
4298/// @code
4299/// enum PropertyAttributes {
4300/// kPropertyReadOnly = 'R', // property is read-only.
4301/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4302/// kPropertyByref = '&', // property is a reference to the value last assigned
4303/// kPropertyDynamic = 'D', // property is dynamic
4304/// kPropertyGetter = 'G', // followed by getter selector name
4305/// kPropertySetter = 'S', // followed by setter selector name
4306/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004307/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004308/// kPropertyWeak = 'W' // 'weak' property
4309/// kPropertyStrong = 'P' // property GC'able
4310/// kPropertyNonAtomic = 'N' // property non-atomic
4311/// };
4312/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004313void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004314 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004315 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004316 // Collect information from the property implementation decl(s).
4317 bool Dynamic = false;
4318 ObjCPropertyImplDecl *SynthesizePID = 0;
4319
4320 // FIXME: Duplicated code due to poor abstraction.
4321 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004322 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004323 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4324 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004325 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004326 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004327 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004328 if (PID->getPropertyDecl() == PD) {
4329 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4330 Dynamic = true;
4331 } else {
4332 SynthesizePID = PID;
4333 }
4334 }
4335 }
4336 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004337 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004338 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004339 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004340 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004341 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004342 if (PID->getPropertyDecl() == PD) {
4343 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4344 Dynamic = true;
4345 } else {
4346 SynthesizePID = PID;
4347 }
4348 }
Mike Stump11289f42009-09-09 15:08:12 +00004349 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004350 }
4351 }
4352
4353 // FIXME: This is not very efficient.
4354 S = "T";
4355
4356 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004357 // GCC has some special rules regarding encoding of properties which
4358 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004359 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004360 true /* outermost type */,
4361 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004362
4363 if (PD->isReadOnly()) {
4364 S += ",R";
4365 } else {
4366 switch (PD->getSetterKind()) {
4367 case ObjCPropertyDecl::Assign: break;
4368 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004369 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004370 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004371 }
4372 }
4373
4374 // It really isn't clear at all what this means, since properties
4375 // are "dynamic by default".
4376 if (Dynamic)
4377 S += ",D";
4378
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004379 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4380 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004381
Daniel Dunbar4932b362008-08-28 04:38:10 +00004382 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4383 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004384 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004385 }
4386
4387 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4388 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004389 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004390 }
4391
4392 if (SynthesizePID) {
4393 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4394 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004395 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004396 }
4397
4398 // FIXME: OBJCGC: weak & strong
4399}
4400
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004401/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004402/// Another legacy compatibility encoding: 32-bit longs are encoded as
4403/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004404/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4405///
4406void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004407 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004408 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004409 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004410 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004411 else
Jay Foad39c79802011-01-12 09:06:06 +00004412 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004413 PointeeTy = IntTy;
4414 }
4415 }
4416}
4417
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004418void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004419 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004420 // We follow the behavior of gcc, expanding structures which are
4421 // directly pointed to, and expanding embedded structures. Note that
4422 // these rules are sufficient to prevent recursive encoding of the
4423 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004424 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004425 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004426}
4427
David Chisnallb190a2c2010-06-04 01:10:52 +00004428static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4429 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004430 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnallb190a2c2010-06-04 01:10:52 +00004431 case BuiltinType::Void: return 'v';
4432 case BuiltinType::Bool: return 'B';
4433 case BuiltinType::Char_U:
4434 case BuiltinType::UChar: return 'C';
4435 case BuiltinType::UShort: return 'S';
4436 case BuiltinType::UInt: return 'I';
4437 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004438 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004439 case BuiltinType::UInt128: return 'T';
4440 case BuiltinType::ULongLong: return 'Q';
4441 case BuiltinType::Char_S:
4442 case BuiltinType::SChar: return 'c';
4443 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004444 case BuiltinType::WChar_S:
4445 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004446 case BuiltinType::Int: return 'i';
4447 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004448 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004449 case BuiltinType::LongLong: return 'q';
4450 case BuiltinType::Int128: return 't';
4451 case BuiltinType::Float: return 'f';
4452 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004453 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004454 }
4455}
4456
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004457static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4458 EnumDecl *Enum = ET->getDecl();
4459
4460 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4461 if (!Enum->isFixed())
4462 return 'i';
4463
4464 // The encoding of a fixed enum type matches its fixed underlying type.
4465 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4466}
4467
Jay Foad39c79802011-01-12 09:06:06 +00004468static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004469 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00004470 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004471 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004472 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4473 // The GNU runtime requires more information; bitfields are encoded as b,
4474 // then the offset (in bits) of the first element, then the type of the
4475 // bitfield, then the size in bits. For example, in this structure:
4476 //
4477 // struct
4478 // {
4479 // int integer;
4480 // int flags:2;
4481 // };
4482 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4483 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4484 // information is not especially sensible, but we're stuck with it for
4485 // compatibility with GCC, although providing it breaks anything that
4486 // actually uses runtime introspection and wants to work on both runtimes...
David Blaikiebbafb8a2012-03-11 07:00:24 +00004487 if (!Ctx->getLangOpts().NeXTRuntime) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004488 const RecordDecl *RD = FD->getParent();
4489 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004490 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004491 if (const EnumType *ET = T->getAs<EnumType>())
4492 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnall6f0a7d22010-12-26 20:12:30 +00004493 else
Jay Foad39c79802011-01-12 09:06:06 +00004494 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004495 }
Richard Smithcaf33902011-10-10 18:28:20 +00004496 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004497}
4498
Daniel Dunbar07d07852009-10-18 21:17:35 +00004499// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004500void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4501 bool ExpandPointedToStructures,
4502 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004503 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004504 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004505 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004506 bool StructField,
4507 bool EncodeBlockParameters,
4508 bool EncodeClassNames) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004509 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004510 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004511 return EncodeBitField(this, S, T, FD);
4512 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004513 return;
4514 }
Mike Stump11289f42009-09-09 15:08:12 +00004515
John McCall9dd450b2009-09-21 23:43:11 +00004516 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004517 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004518 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004519 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004520 return;
4521 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004522
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004523 // encoding for pointer or r3eference types.
4524 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004525 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004526 if (PT->isObjCSelType()) {
4527 S += ':';
4528 return;
4529 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004530 PointeeTy = PT->getPointeeType();
4531 }
4532 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4533 PointeeTy = RT->getPointeeType();
4534 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004535 bool isReadOnly = false;
4536 // For historical/compatibility reasons, the read-only qualifier of the
4537 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4538 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004539 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004540 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004541 if (OutermostType && T.isConstQualified()) {
4542 isReadOnly = true;
4543 S += 'r';
4544 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004545 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004546 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004547 while (P->getAs<PointerType>())
4548 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004549 if (P.isConstQualified()) {
4550 isReadOnly = true;
4551 S += 'r';
4552 }
4553 }
4554 if (isReadOnly) {
4555 // Another legacy compatibility encoding. Some ObjC qualifier and type
4556 // combinations need to be rearranged.
4557 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004558 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004559 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004560 }
Mike Stump11289f42009-09-09 15:08:12 +00004561
Anders Carlssond8499822007-10-29 05:01:08 +00004562 if (PointeeTy->isCharType()) {
4563 // char pointer types should be encoded as '*' unless it is a
4564 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004565 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004566 S += '*';
4567 return;
4568 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004569 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004570 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4571 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4572 S += '#';
4573 return;
4574 }
4575 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4576 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4577 S += '@';
4578 return;
4579 }
4580 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004581 }
Anders Carlssond8499822007-10-29 05:01:08 +00004582 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004583 getLegacyIntegralTypeEncoding(PointeeTy);
4584
Mike Stump11289f42009-09-09 15:08:12 +00004585 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004586 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004587 return;
4588 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004589
Chris Lattnere7cabb92009-07-13 00:10:46 +00004590 if (const ArrayType *AT =
4591 // Ignore type qualifiers etc.
4592 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004593 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004594 // Incomplete arrays are encoded as a pointer to the array element.
4595 S += '^';
4596
Mike Stump11289f42009-09-09 15:08:12 +00004597 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004598 false, ExpandStructures, FD);
4599 } else {
4600 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004601
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004602 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4603 if (getTypeSize(CAT->getElementType()) == 0)
4604 S += '0';
4605 else
4606 S += llvm::utostr(CAT->getSize().getZExtValue());
4607 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004608 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004609 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4610 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00004611 S += '0';
4612 }
Mike Stump11289f42009-09-09 15:08:12 +00004613
4614 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004615 false, ExpandStructures, FD);
4616 S += ']';
4617 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004618 return;
4619 }
Mike Stump11289f42009-09-09 15:08:12 +00004620
John McCall9dd450b2009-09-21 23:43:11 +00004621 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004622 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004623 return;
4624 }
Mike Stump11289f42009-09-09 15:08:12 +00004625
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004626 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004627 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004628 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004629 // Anonymous structures print as '?'
4630 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4631 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004632 if (ClassTemplateSpecializationDecl *Spec
4633 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4634 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4635 std::string TemplateArgsStr
4636 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004637 TemplateArgs.data(),
4638 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00004639 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004640
4641 S += TemplateArgsStr;
4642 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004643 } else {
4644 S += '?';
4645 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004646 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004647 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004648 if (!RDecl->isUnion()) {
4649 getObjCEncodingForStructureImpl(RDecl, S, FD);
4650 } else {
4651 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4652 FieldEnd = RDecl->field_end();
4653 Field != FieldEnd; ++Field) {
4654 if (FD) {
4655 S += '"';
4656 S += Field->getNameAsString();
4657 S += '"';
4658 }
Mike Stump11289f42009-09-09 15:08:12 +00004659
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004660 // Special case bit-fields.
4661 if (Field->isBitField()) {
4662 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00004663 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004664 } else {
4665 QualType qt = Field->getType();
4666 getLegacyIntegralTypeEncoding(qt);
4667 getObjCEncodingForTypeImpl(qt, S, false, true,
4668 FD, /*OutermostType*/false,
4669 /*EncodingProperty*/false,
4670 /*StructField*/true);
4671 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004672 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004673 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004674 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004675 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004676 return;
4677 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004678
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004679 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004680 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004681 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004682 else
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004683 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004684 return;
4685 }
Mike Stump11289f42009-09-09 15:08:12 +00004686
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004687 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004688 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004689 if (EncodeBlockParameters) {
4690 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4691
4692 S += '<';
4693 // Block return type
4694 getObjCEncodingForTypeImpl(FT->getResultType(), S,
4695 ExpandPointedToStructures, ExpandStructures,
4696 FD,
4697 false /* OutermostType */,
4698 EncodingProperty,
4699 false /* StructField */,
4700 EncodeBlockParameters,
4701 EncodeClassNames);
4702 // Block self
4703 S += "@?";
4704 // Block parameters
4705 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4706 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4707 E = FPT->arg_type_end(); I && (I != E); ++I) {
4708 getObjCEncodingForTypeImpl(*I, S,
4709 ExpandPointedToStructures,
4710 ExpandStructures,
4711 FD,
4712 false /* OutermostType */,
4713 EncodingProperty,
4714 false /* StructField */,
4715 EncodeBlockParameters,
4716 EncodeClassNames);
4717 }
4718 }
4719 S += '>';
4720 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004721 return;
4722 }
Mike Stump11289f42009-09-09 15:08:12 +00004723
John McCall8b07ec22010-05-15 11:32:37 +00004724 // Ignore protocol qualifiers when mangling at this level.
4725 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4726 T = OT->getBaseType();
4727
John McCall8ccfcb52009-09-24 19:53:00 +00004728 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004729 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004730 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004731 S += '{';
4732 const IdentifierInfo *II = OI->getIdentifier();
4733 S += II->getName();
4734 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00004735 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004736 DeepCollectObjCIvars(OI, true, Ivars);
4737 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004738 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004739 if (Field->isBitField())
4740 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004741 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004742 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004743 }
4744 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004745 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004746 }
Mike Stump11289f42009-09-09 15:08:12 +00004747
John McCall9dd450b2009-09-21 23:43:11 +00004748 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004749 if (OPT->isObjCIdType()) {
4750 S += '@';
4751 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004752 }
Mike Stump11289f42009-09-09 15:08:12 +00004753
Steve Narofff0c86112009-10-28 22:03:49 +00004754 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4755 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4756 // Since this is a binary compatibility issue, need to consult with runtime
4757 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004758 S += '#';
4759 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004760 }
Mike Stump11289f42009-09-09 15:08:12 +00004761
Chris Lattnere7cabb92009-07-13 00:10:46 +00004762 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004763 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004764 ExpandPointedToStructures,
4765 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004766 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004767 // Note that we do extended encoding of protocol qualifer list
4768 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004769 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004770 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4771 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004772 S += '<';
4773 S += (*I)->getNameAsString();
4774 S += '>';
4775 }
4776 S += '"';
4777 }
4778 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004779 }
Mike Stump11289f42009-09-09 15:08:12 +00004780
Chris Lattnere7cabb92009-07-13 00:10:46 +00004781 QualType PointeeTy = OPT->getPointeeType();
4782 if (!EncodingProperty &&
4783 isa<TypedefType>(PointeeTy.getTypePtr())) {
4784 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004785 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004786 // {...};
4787 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004788 getObjCEncodingForTypeImpl(PointeeTy, S,
4789 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004790 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004791 return;
4792 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004793
4794 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004795 if (OPT->getInterfaceDecl() &&
4796 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004797 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004798 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004799 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4800 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004801 S += '<';
4802 S += (*I)->getNameAsString();
4803 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004804 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004805 S += '"';
4806 }
4807 return;
4808 }
Mike Stump11289f42009-09-09 15:08:12 +00004809
John McCalla9e6e8d2010-05-17 23:56:34 +00004810 // gcc just blithely ignores member pointers.
4811 // TODO: maybe there should be a mangling for these
4812 if (T->getAs<MemberPointerType>())
4813 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004814
4815 if (T->isVectorType()) {
4816 // This matches gcc's encoding, even though technically it is
4817 // insufficient.
4818 // FIXME. We should do a better job than gcc.
4819 return;
4820 }
4821
David Blaikie83d382b2011-09-23 05:06:16 +00004822 llvm_unreachable("@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004823}
4824
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004825void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4826 std::string &S,
4827 const FieldDecl *FD,
4828 bool includeVBases) const {
4829 assert(RDecl && "Expected non-null RecordDecl");
4830 assert(!RDecl->isUnion() && "Should not be called for unions");
4831 if (!RDecl->getDefinition())
4832 return;
4833
4834 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4835 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4836 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4837
4838 if (CXXRec) {
4839 for (CXXRecordDecl::base_class_iterator
4840 BI = CXXRec->bases_begin(),
4841 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4842 if (!BI->isVirtual()) {
4843 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004844 if (base->isEmpty())
4845 continue;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004846 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4847 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4848 std::make_pair(offs, base));
4849 }
4850 }
4851 }
4852
4853 unsigned i = 0;
4854 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4855 FieldEnd = RDecl->field_end();
4856 Field != FieldEnd; ++Field, ++i) {
4857 uint64_t offs = layout.getFieldOffset(i);
4858 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00004859 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004860 }
4861
4862 if (CXXRec && includeVBases) {
4863 for (CXXRecordDecl::base_class_iterator
4864 BI = CXXRec->vbases_begin(),
4865 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4866 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004867 if (base->isEmpty())
4868 continue;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004869 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00004870 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4871 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4872 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004873 }
4874 }
4875
4876 CharUnits size;
4877 if (CXXRec) {
4878 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4879 } else {
4880 size = layout.getSize();
4881 }
4882
4883 uint64_t CurOffs = 0;
4884 std::multimap<uint64_t, NamedDecl *>::iterator
4885 CurLayObj = FieldOrBaseOffsets.begin();
4886
Douglas Gregorf5d6c742012-04-27 22:30:01 +00004887 if (CXXRec && CXXRec->isDynamicClass() &&
4888 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004889 if (FD) {
4890 S += "\"_vptr$";
4891 std::string recname = CXXRec->getNameAsString();
4892 if (recname.empty()) recname = "?";
4893 S += recname;
4894 S += '"';
4895 }
4896 S += "^^?";
4897 CurOffs += getTypeSize(VoidPtrTy);
4898 }
4899
4900 if (!RDecl->hasFlexibleArrayMember()) {
4901 // Mark the end of the structure.
4902 uint64_t offs = toBits(size);
4903 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4904 std::make_pair(offs, (NamedDecl*)0));
4905 }
4906
4907 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4908 assert(CurOffs <= CurLayObj->first);
4909
4910 if (CurOffs < CurLayObj->first) {
4911 uint64_t padding = CurLayObj->first - CurOffs;
4912 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4913 // packing/alignment of members is different that normal, in which case
4914 // the encoding will be out-of-sync with the real layout.
4915 // If the runtime switches to just consider the size of types without
4916 // taking into account alignment, we could make padding explicit in the
4917 // encoding (e.g. using arrays of chars). The encoding strings would be
4918 // longer then though.
4919 CurOffs += padding;
4920 }
4921
4922 NamedDecl *dcl = CurLayObj->second;
4923 if (dcl == 0)
4924 break; // reached end of structure.
4925
4926 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4927 // We expand the bases without their virtual bases since those are going
4928 // in the initial structure. Note that this differs from gcc which
4929 // expands virtual bases each time one is encountered in the hierarchy,
4930 // making the encoding type bigger than it really is.
4931 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004932 assert(!base->isEmpty());
4933 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004934 } else {
4935 FieldDecl *field = cast<FieldDecl>(dcl);
4936 if (FD) {
4937 S += '"';
4938 S += field->getNameAsString();
4939 S += '"';
4940 }
4941
4942 if (field->isBitField()) {
4943 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00004944 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004945 } else {
4946 QualType qt = field->getType();
4947 getLegacyIntegralTypeEncoding(qt);
4948 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4949 /*OutermostType*/false,
4950 /*EncodingProperty*/false,
4951 /*StructField*/true);
4952 CurOffs += getTypeSize(field->getType());
4953 }
4954 }
4955 }
4956}
4957
Mike Stump11289f42009-09-09 15:08:12 +00004958void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004959 std::string& S) const {
4960 if (QT & Decl::OBJC_TQ_In)
4961 S += 'n';
4962 if (QT & Decl::OBJC_TQ_Inout)
4963 S += 'N';
4964 if (QT & Decl::OBJC_TQ_Out)
4965 S += 'o';
4966 if (QT & Decl::OBJC_TQ_Bycopy)
4967 S += 'O';
4968 if (QT & Decl::OBJC_TQ_Byref)
4969 S += 'R';
4970 if (QT & Decl::OBJC_TQ_Oneway)
4971 S += 'V';
4972}
4973
Douglas Gregor3ea72692011-08-12 05:46:01 +00004974TypedefDecl *ASTContext::getObjCIdDecl() const {
4975 if (!ObjCIdDecl) {
4976 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
4977 T = getObjCObjectPointerType(T);
4978 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
4979 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4980 getTranslationUnitDecl(),
4981 SourceLocation(), SourceLocation(),
4982 &Idents.get("id"), IdInfo);
4983 }
4984
4985 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00004986}
4987
Douglas Gregor52e02802011-08-12 06:17:30 +00004988TypedefDecl *ASTContext::getObjCSelDecl() const {
4989 if (!ObjCSelDecl) {
4990 QualType SelT = getPointerType(ObjCBuiltinSelTy);
4991 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
4992 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4993 getTranslationUnitDecl(),
4994 SourceLocation(), SourceLocation(),
4995 &Idents.get("SEL"), SelInfo);
4996 }
4997 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00004998}
4999
Douglas Gregor0a586182011-08-12 05:59:41 +00005000TypedefDecl *ASTContext::getObjCClassDecl() const {
5001 if (!ObjCClassDecl) {
5002 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5003 T = getObjCObjectPointerType(T);
5004 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5005 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5006 getTranslationUnitDecl(),
5007 SourceLocation(), SourceLocation(),
5008 &Idents.get("Class"), ClassInfo);
5009 }
5010
5011 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005012}
5013
Douglas Gregord53ae832012-01-17 18:09:05 +00005014ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5015 if (!ObjCProtocolClassDecl) {
5016 ObjCProtocolClassDecl
5017 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5018 SourceLocation(),
5019 &Idents.get("Protocol"),
5020 /*PrevDecl=*/0,
5021 SourceLocation(), true);
5022 }
5023
5024 return ObjCProtocolClassDecl;
5025}
5026
Meador Inge5d3fb222012-06-16 03:34:49 +00005027//===----------------------------------------------------------------------===//
5028// __builtin_va_list Construction Functions
5029//===----------------------------------------------------------------------===//
5030
5031static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5032 // typedef char* __builtin_va_list;
5033 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5034 TypeSourceInfo *TInfo
5035 = Context->getTrivialTypeSourceInfo(CharPtrType);
5036
5037 TypedefDecl *VaListTypeDecl
5038 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5039 Context->getTranslationUnitDecl(),
5040 SourceLocation(), SourceLocation(),
5041 &Context->Idents.get("__builtin_va_list"),
5042 TInfo);
5043 return VaListTypeDecl;
5044}
5045
5046static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5047 // typedef void* __builtin_va_list;
5048 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5049 TypeSourceInfo *TInfo
5050 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5051
5052 TypedefDecl *VaListTypeDecl
5053 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5054 Context->getTranslationUnitDecl(),
5055 SourceLocation(), SourceLocation(),
5056 &Context->Idents.get("__builtin_va_list"),
5057 TInfo);
5058 return VaListTypeDecl;
5059}
5060
5061static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5062 // typedef struct __va_list_tag {
5063 RecordDecl *VaListTagDecl;
5064
5065 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5066 Context->getTranslationUnitDecl(),
5067 &Context->Idents.get("__va_list_tag"));
5068 VaListTagDecl->startDefinition();
5069
5070 const size_t NumFields = 5;
5071 QualType FieldTypes[NumFields];
5072 const char *FieldNames[NumFields];
5073
5074 // unsigned char gpr;
5075 FieldTypes[0] = Context->UnsignedCharTy;
5076 FieldNames[0] = "gpr";
5077
5078 // unsigned char fpr;
5079 FieldTypes[1] = Context->UnsignedCharTy;
5080 FieldNames[1] = "fpr";
5081
5082 // unsigned short reserved;
5083 FieldTypes[2] = Context->UnsignedShortTy;
5084 FieldNames[2] = "reserved";
5085
5086 // void* overflow_arg_area;
5087 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5088 FieldNames[3] = "overflow_arg_area";
5089
5090 // void* reg_save_area;
5091 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5092 FieldNames[4] = "reg_save_area";
5093
5094 // Create fields
5095 for (unsigned i = 0; i < NumFields; ++i) {
5096 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5097 SourceLocation(),
5098 SourceLocation(),
5099 &Context->Idents.get(FieldNames[i]),
5100 FieldTypes[i], /*TInfo=*/0,
5101 /*BitWidth=*/0,
5102 /*Mutable=*/false,
5103 ICIS_NoInit);
5104 Field->setAccess(AS_public);
5105 VaListTagDecl->addDecl(Field);
5106 }
5107 VaListTagDecl->completeDefinition();
5108 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5109
5110 // } __va_list_tag;
5111 TypedefDecl *VaListTagTypedefDecl
5112 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5113 Context->getTranslationUnitDecl(),
5114 SourceLocation(), SourceLocation(),
5115 &Context->Idents.get("__va_list_tag"),
5116 Context->getTrivialTypeSourceInfo(VaListTagType));
5117 QualType VaListTagTypedefType =
5118 Context->getTypedefType(VaListTagTypedefDecl);
5119
5120 // typedef __va_list_tag __builtin_va_list[1];
5121 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5122 QualType VaListTagArrayType
5123 = Context->getConstantArrayType(VaListTagTypedefType,
5124 Size, ArrayType::Normal, 0);
5125 TypeSourceInfo *TInfo
5126 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5127 TypedefDecl *VaListTypedefDecl
5128 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5129 Context->getTranslationUnitDecl(),
5130 SourceLocation(), SourceLocation(),
5131 &Context->Idents.get("__builtin_va_list"),
5132 TInfo);
5133
5134 return VaListTypedefDecl;
5135}
5136
5137static TypedefDecl *
5138CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5139 // typedef struct __va_list_tag {
5140 RecordDecl *VaListTagDecl;
5141 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5142 Context->getTranslationUnitDecl(),
5143 &Context->Idents.get("__va_list_tag"));
5144 VaListTagDecl->startDefinition();
5145
5146 const size_t NumFields = 4;
5147 QualType FieldTypes[NumFields];
5148 const char *FieldNames[NumFields];
5149
5150 // unsigned gp_offset;
5151 FieldTypes[0] = Context->UnsignedIntTy;
5152 FieldNames[0] = "gp_offset";
5153
5154 // unsigned fp_offset;
5155 FieldTypes[1] = Context->UnsignedIntTy;
5156 FieldNames[1] = "fp_offset";
5157
5158 // void* overflow_arg_area;
5159 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5160 FieldNames[2] = "overflow_arg_area";
5161
5162 // void* reg_save_area;
5163 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5164 FieldNames[3] = "reg_save_area";
5165
5166 // Create fields
5167 for (unsigned i = 0; i < NumFields; ++i) {
5168 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5169 VaListTagDecl,
5170 SourceLocation(),
5171 SourceLocation(),
5172 &Context->Idents.get(FieldNames[i]),
5173 FieldTypes[i], /*TInfo=*/0,
5174 /*BitWidth=*/0,
5175 /*Mutable=*/false,
5176 ICIS_NoInit);
5177 Field->setAccess(AS_public);
5178 VaListTagDecl->addDecl(Field);
5179 }
5180 VaListTagDecl->completeDefinition();
5181 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5182
5183 // } __va_list_tag;
5184 TypedefDecl *VaListTagTypedefDecl
5185 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5186 Context->getTranslationUnitDecl(),
5187 SourceLocation(), SourceLocation(),
5188 &Context->Idents.get("__va_list_tag"),
5189 Context->getTrivialTypeSourceInfo(VaListTagType));
5190 QualType VaListTagTypedefType =
5191 Context->getTypedefType(VaListTagTypedefDecl);
5192
5193 // typedef __va_list_tag __builtin_va_list[1];
5194 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5195 QualType VaListTagArrayType
5196 = Context->getConstantArrayType(VaListTagTypedefType,
5197 Size, ArrayType::Normal,0);
5198 TypeSourceInfo *TInfo
5199 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5200 TypedefDecl *VaListTypedefDecl
5201 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5202 Context->getTranslationUnitDecl(),
5203 SourceLocation(), SourceLocation(),
5204 &Context->Idents.get("__builtin_va_list"),
5205 TInfo);
5206
5207 return VaListTypedefDecl;
5208}
5209
5210static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5211 // typedef int __builtin_va_list[4];
5212 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5213 QualType IntArrayType
5214 = Context->getConstantArrayType(Context->IntTy,
5215 Size, ArrayType::Normal, 0);
5216 TypedefDecl *VaListTypedefDecl
5217 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5218 Context->getTranslationUnitDecl(),
5219 SourceLocation(), SourceLocation(),
5220 &Context->Idents.get("__builtin_va_list"),
5221 Context->getTrivialTypeSourceInfo(IntArrayType));
5222
5223 return VaListTypedefDecl;
5224}
5225
5226static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5227 TargetInfo::BuiltinVaListKind Kind) {
5228 switch (Kind) {
5229 case TargetInfo::CharPtrBuiltinVaList:
5230 return CreateCharPtrBuiltinVaListDecl(Context);
5231 case TargetInfo::VoidPtrBuiltinVaList:
5232 return CreateVoidPtrBuiltinVaListDecl(Context);
5233 case TargetInfo::PowerABIBuiltinVaList:
5234 return CreatePowerABIBuiltinVaListDecl(Context);
5235 case TargetInfo::X86_64ABIBuiltinVaList:
5236 return CreateX86_64ABIBuiltinVaListDecl(Context);
5237 case TargetInfo::PNaClABIBuiltinVaList:
5238 return CreatePNaClABIBuiltinVaListDecl(Context);
5239 }
5240
5241 llvm_unreachable("Unhandled __builtin_va_list type kind");
5242}
5243
5244TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5245 if (!BuiltinVaListDecl)
5246 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5247
5248 return BuiltinVaListDecl;
5249}
5250
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005251void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00005252 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00005253 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00005254
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005255 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00005256}
5257
John McCalld28ae272009-12-02 08:04:21 +00005258/// \brief Retrieve the template name that corresponds to a non-empty
5259/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00005260TemplateName
5261ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5262 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00005263 unsigned size = End - Begin;
5264 assert(size > 1 && "set is not overloaded!");
5265
5266 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5267 size * sizeof(FunctionTemplateDecl*));
5268 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5269
5270 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00005271 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00005272 NamedDecl *D = *I;
5273 assert(isa<FunctionTemplateDecl>(D) ||
5274 (isa<UsingShadowDecl>(D) &&
5275 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5276 *Storage++ = D;
5277 }
5278
5279 return TemplateName(OT);
5280}
5281
Douglas Gregordc572a32009-03-30 22:58:21 +00005282/// \brief Retrieve the template name that represents a qualified
5283/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00005284TemplateName
5285ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5286 bool TemplateKeyword,
5287 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00005288 assert(NNS && "Missing nested-name-specifier in qualified template name");
5289
Douglas Gregorc42075a2010-02-04 18:10:26 +00005290 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00005291 llvm::FoldingSetNodeID ID;
5292 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5293
5294 void *InsertPos = 0;
5295 QualifiedTemplateName *QTN =
5296 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5297 if (!QTN) {
5298 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
5299 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5300 }
5301
5302 return TemplateName(QTN);
5303}
5304
5305/// \brief Retrieve the template name that represents a dependent
5306/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00005307TemplateName
5308ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5309 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00005310 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00005311 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00005312
5313 llvm::FoldingSetNodeID ID;
5314 DependentTemplateName::Profile(ID, NNS, Name);
5315
5316 void *InsertPos = 0;
5317 DependentTemplateName *QTN =
5318 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5319
5320 if (QTN)
5321 return TemplateName(QTN);
5322
5323 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5324 if (CanonNNS == NNS) {
5325 QTN = new (*this,4) DependentTemplateName(NNS, Name);
5326 } else {
5327 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
5328 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005329 DependentTemplateName *CheckQTN =
5330 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5331 assert(!CheckQTN && "Dependent type name canonicalization broken");
5332 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00005333 }
5334
5335 DependentTemplateNames.InsertNode(QTN, InsertPos);
5336 return TemplateName(QTN);
5337}
5338
Douglas Gregor71395fa2009-11-04 00:56:37 +00005339/// \brief Retrieve the template name that represents a dependent
5340/// template name such as \c MetaFun::template operator+.
5341TemplateName
5342ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00005343 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00005344 assert((!NNS || NNS->isDependent()) &&
5345 "Nested name specifier must be dependent");
5346
5347 llvm::FoldingSetNodeID ID;
5348 DependentTemplateName::Profile(ID, NNS, Operator);
5349
5350 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00005351 DependentTemplateName *QTN
5352 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005353
5354 if (QTN)
5355 return TemplateName(QTN);
5356
5357 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5358 if (CanonNNS == NNS) {
5359 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
5360 } else {
5361 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
5362 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005363
5364 DependentTemplateName *CheckQTN
5365 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5366 assert(!CheckQTN && "Dependent template name canonicalization broken");
5367 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00005368 }
5369
5370 DependentTemplateNames.InsertNode(QTN, InsertPos);
5371 return TemplateName(QTN);
5372}
5373
Douglas Gregor5590be02011-01-15 06:45:20 +00005374TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00005375ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5376 TemplateName replacement) const {
5377 llvm::FoldingSetNodeID ID;
5378 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5379
5380 void *insertPos = 0;
5381 SubstTemplateTemplateParmStorage *subst
5382 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5383
5384 if (!subst) {
5385 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5386 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5387 }
5388
5389 return TemplateName(subst);
5390}
5391
5392TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00005393ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5394 const TemplateArgument &ArgPack) const {
5395 ASTContext &Self = const_cast<ASTContext &>(*this);
5396 llvm::FoldingSetNodeID ID;
5397 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5398
5399 void *InsertPos = 0;
5400 SubstTemplateTemplateParmPackStorage *Subst
5401 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5402
5403 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00005404 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00005405 ArgPack.pack_size(),
5406 ArgPack.pack_begin());
5407 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5408 }
5409
5410 return TemplateName(Subst);
5411}
5412
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005413/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00005414/// TargetInfo, produce the corresponding type. The unsigned @p Type
5415/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00005416CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005417 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00005418 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005419 case TargetInfo::SignedShort: return ShortTy;
5420 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5421 case TargetInfo::SignedInt: return IntTy;
5422 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5423 case TargetInfo::SignedLong: return LongTy;
5424 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5425 case TargetInfo::SignedLongLong: return LongLongTy;
5426 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5427 }
5428
David Blaikie83d382b2011-09-23 05:06:16 +00005429 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005430}
Ted Kremenek77c51b22008-07-24 23:58:27 +00005431
5432//===----------------------------------------------------------------------===//
5433// Type Predicates.
5434//===----------------------------------------------------------------------===//
5435
Fariborz Jahanian96207692009-02-18 21:49:28 +00005436/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5437/// garbage collection attribute.
5438///
John McCall553d45a2011-01-12 00:34:59 +00005439Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005440 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00005441 return Qualifiers::GCNone;
5442
David Blaikiebbafb8a2012-03-11 07:00:24 +00005443 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00005444 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5445
5446 // Default behaviour under objective-C's gc is for ObjC pointers
5447 // (or pointers to them) be treated as though they were declared
5448 // as __strong.
5449 if (GCAttrs == Qualifiers::GCNone) {
5450 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5451 return Qualifiers::Strong;
5452 else if (Ty->isPointerType())
5453 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5454 } else {
5455 // It's not valid to set GC attributes on anything that isn't a
5456 // pointer.
5457#ifndef NDEBUG
5458 QualType CT = Ty->getCanonicalTypeInternal();
5459 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5460 CT = AT->getElementType();
5461 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5462#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00005463 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00005464 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00005465}
5466
Chris Lattner49af6a42008-04-07 06:51:04 +00005467//===----------------------------------------------------------------------===//
5468// Type Compatibility Testing
5469//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00005470
Mike Stump11289f42009-09-09 15:08:12 +00005471/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005472/// compatible.
5473static bool areCompatVectorTypes(const VectorType *LHS,
5474 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00005475 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00005476 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00005477 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00005478}
5479
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005480bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5481 QualType SecondVec) {
5482 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5483 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5484
5485 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5486 return true;
5487
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005488 // Treat Neon vector types and most AltiVec vector types as if they are the
5489 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005490 const VectorType *First = FirstVec->getAs<VectorType>();
5491 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005492 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005493 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005494 First->getVectorKind() != VectorType::AltiVecPixel &&
5495 First->getVectorKind() != VectorType::AltiVecBool &&
5496 Second->getVectorKind() != VectorType::AltiVecPixel &&
5497 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005498 return true;
5499
5500 return false;
5501}
5502
Steve Naroff8e6aee52009-07-23 01:01:38 +00005503//===----------------------------------------------------------------------===//
5504// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5505//===----------------------------------------------------------------------===//
5506
5507/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5508/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00005509bool
5510ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5511 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00005512 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005513 return true;
5514 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5515 E = rProto->protocol_end(); PI != E; ++PI)
5516 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5517 return true;
5518 return false;
5519}
5520
Steve Naroff8e6aee52009-07-23 01:01:38 +00005521/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5522/// return true if lhs's protocols conform to rhs's protocol; false
5523/// otherwise.
5524bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5525 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5526 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5527 return false;
5528}
5529
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005530/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5531/// Class<p1, ...>.
5532bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5533 QualType rhs) {
5534 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5535 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5536 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5537
5538 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5539 E = lhsQID->qual_end(); I != E; ++I) {
5540 bool match = false;
5541 ObjCProtocolDecl *lhsProto = *I;
5542 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5543 E = rhsOPT->qual_end(); J != E; ++J) {
5544 ObjCProtocolDecl *rhsProto = *J;
5545 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5546 match = true;
5547 break;
5548 }
5549 }
5550 if (!match)
5551 return false;
5552 }
5553 return true;
5554}
5555
Steve Naroff8e6aee52009-07-23 01:01:38 +00005556/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5557/// ObjCQualifiedIDType.
5558bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5559 bool compare) {
5560 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00005561 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005562 lhs->isObjCIdType() || lhs->isObjCClassType())
5563 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005564 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005565 rhs->isObjCIdType() || rhs->isObjCClassType())
5566 return true;
5567
5568 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00005569 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005570
Steve Naroff8e6aee52009-07-23 01:01:38 +00005571 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00005572
Steve Naroff8e6aee52009-07-23 01:01:38 +00005573 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005574 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005575 // make sure we check the class hierarchy.
5576 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5577 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5578 E = lhsQID->qual_end(); I != E; ++I) {
5579 // when comparing an id<P> on lhs with a static type on rhs,
5580 // see if static class implements all of id's protocols, directly or
5581 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005582 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005583 return false;
5584 }
5585 }
5586 // If there are no qualifiers and no interface, we have an 'id'.
5587 return true;
5588 }
Mike Stump11289f42009-09-09 15:08:12 +00005589 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005590 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5591 E = lhsQID->qual_end(); I != E; ++I) {
5592 ObjCProtocolDecl *lhsProto = *I;
5593 bool match = false;
5594
5595 // when comparing an id<P> on lhs with a static type on rhs,
5596 // see if static class implements all of id's protocols, directly or
5597 // through its super class and categories.
5598 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5599 E = rhsOPT->qual_end(); J != E; ++J) {
5600 ObjCProtocolDecl *rhsProto = *J;
5601 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5602 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5603 match = true;
5604 break;
5605 }
5606 }
Mike Stump11289f42009-09-09 15:08:12 +00005607 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005608 // make sure we check the class hierarchy.
5609 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5610 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5611 E = lhsQID->qual_end(); I != E; ++I) {
5612 // when comparing an id<P> on lhs with a static type on rhs,
5613 // see if static class implements all of id's protocols, directly or
5614 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005615 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005616 match = true;
5617 break;
5618 }
5619 }
5620 }
5621 if (!match)
5622 return false;
5623 }
Mike Stump11289f42009-09-09 15:08:12 +00005624
Steve Naroff8e6aee52009-07-23 01:01:38 +00005625 return true;
5626 }
Mike Stump11289f42009-09-09 15:08:12 +00005627
Steve Naroff8e6aee52009-07-23 01:01:38 +00005628 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5629 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5630
Mike Stump11289f42009-09-09 15:08:12 +00005631 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00005632 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005633 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005634 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5635 E = lhsOPT->qual_end(); I != E; ++I) {
5636 ObjCProtocolDecl *lhsProto = *I;
5637 bool match = false;
5638
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005639 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00005640 // see if static class implements all of id's protocols, directly or
5641 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005642 // First, lhs protocols in the qualifier list must be found, direct
5643 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005644 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5645 E = rhsQID->qual_end(); J != E; ++J) {
5646 ObjCProtocolDecl *rhsProto = *J;
5647 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5648 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5649 match = true;
5650 break;
5651 }
5652 }
5653 if (!match)
5654 return false;
5655 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005656
5657 // Static class's protocols, or its super class or category protocols
5658 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5659 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5660 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5661 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5662 // This is rather dubious but matches gcc's behavior. If lhs has
5663 // no type qualifier and its class has no static protocol(s)
5664 // assume that it is mismatch.
5665 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5666 return false;
5667 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5668 LHSInheritedProtocols.begin(),
5669 E = LHSInheritedProtocols.end(); I != E; ++I) {
5670 bool match = false;
5671 ObjCProtocolDecl *lhsProto = (*I);
5672 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5673 E = rhsQID->qual_end(); J != E; ++J) {
5674 ObjCProtocolDecl *rhsProto = *J;
5675 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5676 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5677 match = true;
5678 break;
5679 }
5680 }
5681 if (!match)
5682 return false;
5683 }
5684 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00005685 return true;
5686 }
5687 return false;
5688}
5689
Eli Friedman47f77112008-08-22 00:56:42 +00005690/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005691/// compatible for assignment from RHS to LHS. This handles validation of any
5692/// protocol qualifiers on the LHS or RHS.
5693///
Steve Naroff7cae42b2009-07-10 23:34:53 +00005694bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5695 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00005696 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5697 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5698
Steve Naroff1329fa02009-07-15 18:40:39 +00005699 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00005700 if (LHS->isObjCUnqualifiedIdOrClass() ||
5701 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00005702 return true;
5703
John McCall8b07ec22010-05-15 11:32:37 +00005704 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00005705 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5706 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00005707 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005708
5709 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5710 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5711 QualType(RHSOPT,0));
5712
John McCall8b07ec22010-05-15 11:32:37 +00005713 // If we have 2 user-defined types, fall into that path.
5714 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00005715 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005716
Steve Naroff8e6aee52009-07-23 01:01:38 +00005717 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005718}
5719
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005720/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00005721/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005722/// arguments in block literals. When passed as arguments, passing 'A*' where
5723/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5724/// not OK. For the return type, the opposite is not OK.
5725bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5726 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005727 const ObjCObjectPointerType *RHSOPT,
5728 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005729 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005730 return true;
5731
5732 if (LHSOPT->isObjCBuiltinType()) {
5733 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5734 }
5735
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005736 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005737 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5738 QualType(RHSOPT,0),
5739 false);
5740
5741 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5742 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5743 if (LHS && RHS) { // We have 2 user-defined types.
5744 if (LHS != RHS) {
5745 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005746 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005747 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005748 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005749 }
5750 else
5751 return true;
5752 }
5753 return false;
5754}
5755
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005756/// getIntersectionOfProtocols - This routine finds the intersection of set
5757/// of protocols inherited from two distinct objective-c pointer objects.
5758/// It is used to build composite qualifier list of the composite type of
5759/// the conditional expression involving two objective-c pointer objects.
5760static
5761void getIntersectionOfProtocols(ASTContext &Context,
5762 const ObjCObjectPointerType *LHSOPT,
5763 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005764 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005765
John McCall8b07ec22010-05-15 11:32:37 +00005766 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5767 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5768 assert(LHS->getInterface() && "LHS must have an interface base");
5769 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005770
5771 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5772 unsigned LHSNumProtocols = LHS->getNumProtocols();
5773 if (LHSNumProtocols > 0)
5774 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5775 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005776 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005777 Context.CollectInheritedProtocols(LHS->getInterface(),
5778 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005779 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5780 LHSInheritedProtocols.end());
5781 }
5782
5783 unsigned RHSNumProtocols = RHS->getNumProtocols();
5784 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00005785 ObjCProtocolDecl **RHSProtocols =
5786 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005787 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5788 if (InheritedProtocolSet.count(RHSProtocols[i]))
5789 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00005790 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005791 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005792 Context.CollectInheritedProtocols(RHS->getInterface(),
5793 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005794 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5795 RHSInheritedProtocols.begin(),
5796 E = RHSInheritedProtocols.end(); I != E; ++I)
5797 if (InheritedProtocolSet.count((*I)))
5798 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005799 }
5800}
5801
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005802/// areCommonBaseCompatible - Returns common base class of the two classes if
5803/// one found. Note that this is O'2 algorithm. But it will be called as the
5804/// last type comparison in a ?-exp of ObjC pointer types before a
5805/// warning is issued. So, its invokation is extremely rare.
5806QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00005807 const ObjCObjectPointerType *Lptr,
5808 const ObjCObjectPointerType *Rptr) {
5809 const ObjCObjectType *LHS = Lptr->getObjectType();
5810 const ObjCObjectType *RHS = Rptr->getObjectType();
5811 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5812 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00005813 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005814 return QualType();
5815
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005816 do {
John McCall8b07ec22010-05-15 11:32:37 +00005817 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005818 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005819 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00005820 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5821
5822 QualType Result = QualType(LHS, 0);
5823 if (!Protocols.empty())
5824 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5825 Result = getObjCObjectPointerType(Result);
5826 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005827 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005828 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005829
5830 return QualType();
5831}
5832
John McCall8b07ec22010-05-15 11:32:37 +00005833bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5834 const ObjCObjectType *RHS) {
5835 assert(LHS->getInterface() && "LHS is not an interface type");
5836 assert(RHS->getInterface() && "RHS is not an interface type");
5837
Chris Lattner49af6a42008-04-07 06:51:04 +00005838 // Verify that the base decls are compatible: the RHS must be a subclass of
5839 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00005840 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00005841 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005842
Chris Lattner49af6a42008-04-07 06:51:04 +00005843 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5844 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00005845 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00005846 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005847
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005848 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5849 // more detailed analysis is required.
5850 if (RHS->getNumProtocols() == 0) {
5851 // OK, if LHS is a superclass of RHS *and*
5852 // this superclass is assignment compatible with LHS.
5853 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005854 bool IsSuperClass =
5855 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5856 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005857 // OK if conversion of LHS to SuperClass results in narrowing of types
5858 // ; i.e., SuperClass may implement at least one of the protocols
5859 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5860 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5861 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005862 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005863 // If super class has no protocols, it is not a match.
5864 if (SuperClassInheritedProtocols.empty())
5865 return false;
5866
5867 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5868 LHSPE = LHS->qual_end();
5869 LHSPI != LHSPE; LHSPI++) {
5870 bool SuperImplementsProtocol = false;
5871 ObjCProtocolDecl *LHSProto = (*LHSPI);
5872
5873 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5874 SuperClassInheritedProtocols.begin(),
5875 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5876 ObjCProtocolDecl *SuperClassProto = (*I);
5877 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5878 SuperImplementsProtocol = true;
5879 break;
5880 }
5881 }
5882 if (!SuperImplementsProtocol)
5883 return false;
5884 }
5885 return true;
5886 }
5887 return false;
5888 }
Mike Stump11289f42009-09-09 15:08:12 +00005889
John McCall8b07ec22010-05-15 11:32:37 +00005890 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5891 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00005892 LHSPI != LHSPE; LHSPI++) {
5893 bool RHSImplementsProtocol = false;
5894
5895 // If the RHS doesn't implement the protocol on the left, the types
5896 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00005897 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5898 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00005899 RHSPI != RHSPE; RHSPI++) {
5900 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00005901 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00005902 break;
5903 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005904 }
5905 // FIXME: For better diagnostics, consider passing back the protocol name.
5906 if (!RHSImplementsProtocol)
5907 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00005908 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005909 // The RHS implements all protocols listed on the LHS.
5910 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00005911}
5912
Steve Naroffb7605152009-02-12 17:52:19 +00005913bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5914 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00005915 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5916 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005917
Steve Naroff7cae42b2009-07-10 23:34:53 +00005918 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00005919 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005920
5921 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5922 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00005923}
5924
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005925bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5926 return canAssignObjCInterfaces(
5927 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5928 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5929}
5930
Mike Stump11289f42009-09-09 15:08:12 +00005931/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00005932/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00005933/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00005934/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005935bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5936 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005937 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00005938 return hasSameType(LHS, RHS);
5939
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005940 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00005941}
5942
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00005943bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00005944 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00005945}
5946
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005947bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5948 return !mergeTypes(LHS, RHS, true).isNull();
5949}
5950
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005951/// mergeTransparentUnionType - if T is a transparent union type and a member
5952/// of T is compatible with SubType, return the merged type, else return
5953/// QualType()
5954QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5955 bool OfBlockPointer,
5956 bool Unqualified) {
5957 if (const RecordType *UT = T->getAsUnionType()) {
5958 RecordDecl *UD = UT->getDecl();
5959 if (UD->hasAttr<TransparentUnionAttr>()) {
5960 for (RecordDecl::field_iterator it = UD->field_begin(),
5961 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00005962 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005963 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5964 if (!MT.isNull())
5965 return MT;
5966 }
5967 }
5968 }
5969
5970 return QualType();
5971}
5972
5973/// mergeFunctionArgumentTypes - merge two types which appear as function
5974/// argument types
5975QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5976 bool OfBlockPointer,
5977 bool Unqualified) {
5978 // GNU extension: two types are compatible if they appear as a function
5979 // argument, one of the types is a transparent union type and the other
5980 // type is compatible with a union member
5981 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5982 Unqualified);
5983 if (!lmerge.isNull())
5984 return lmerge;
5985
5986 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5987 Unqualified);
5988 if (!rmerge.isNull())
5989 return rmerge;
5990
5991 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5992}
5993
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005994QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005995 bool OfBlockPointer,
5996 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00005997 const FunctionType *lbase = lhs->getAs<FunctionType>();
5998 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005999 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6000 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006001 bool allLTypes = true;
6002 bool allRTypes = true;
6003
6004 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006005 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006006 if (OfBlockPointer) {
6007 QualType RHS = rbase->getResultType();
6008 QualType LHS = lbase->getResultType();
6009 bool UnqualifiedResult = Unqualified;
6010 if (!UnqualifiedResult)
6011 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006012 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006013 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006014 else
John McCall8c6b56f2010-12-15 01:06:38 +00006015 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6016 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006017 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006018
6019 if (Unqualified)
6020 retType = retType.getUnqualifiedType();
6021
6022 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6023 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6024 if (Unqualified) {
6025 LRetType = LRetType.getUnqualifiedType();
6026 RRetType = RRetType.getUnqualifiedType();
6027 }
6028
6029 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006030 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006031 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006032 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006033
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006034 // FIXME: double check this
6035 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6036 // rbase->getRegParmAttr() != 0 &&
6037 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006038 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6039 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006040
Douglas Gregor8c940862010-01-18 17:14:39 +00006041 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00006042 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00006043 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006044
John McCall8c6b56f2010-12-15 01:06:38 +00006045 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006046 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6047 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006048 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6049 return QualType();
6050
John McCall31168b02011-06-15 23:02:42 +00006051 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6052 return QualType();
6053
Fariborz Jahanian48c69102011-10-05 00:05:34 +00006054 // functypes which return are preferred over those that do not.
6055 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
6056 allLTypes = false;
6057 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
6058 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006059 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6060 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006061
John McCall31168b02011-06-15 23:02:42 +00006062 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006063
Eli Friedman47f77112008-08-22 00:56:42 +00006064 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006065 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6066 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006067 unsigned lproto_nargs = lproto->getNumArgs();
6068 unsigned rproto_nargs = rproto->getNumArgs();
6069
6070 // Compatible functions must have the same number of arguments
6071 if (lproto_nargs != rproto_nargs)
6072 return QualType();
6073
6074 // Variadic and non-variadic functions aren't compatible
6075 if (lproto->isVariadic() != rproto->isVariadic())
6076 return QualType();
6077
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006078 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6079 return QualType();
6080
Fariborz Jahanian97676972011-09-28 21:52:05 +00006081 if (LangOpts.ObjCAutoRefCount &&
6082 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6083 return QualType();
6084
Eli Friedman47f77112008-08-22 00:56:42 +00006085 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006086 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00006087 for (unsigned i = 0; i < lproto_nargs; i++) {
6088 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6089 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006090 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6091 OfBlockPointer,
6092 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006093 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006094
6095 if (Unqualified)
6096 argtype = argtype.getUnqualifiedType();
6097
Eli Friedman47f77112008-08-22 00:56:42 +00006098 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006099 if (Unqualified) {
6100 largtype = largtype.getUnqualifiedType();
6101 rargtype = rargtype.getUnqualifiedType();
6102 }
6103
Chris Lattner465fa322008-10-05 17:34:18 +00006104 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6105 allLTypes = false;
6106 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6107 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006108 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006109
Eli Friedman47f77112008-08-22 00:56:42 +00006110 if (allLTypes) return lhs;
6111 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006112
6113 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6114 EPI.ExtInfo = einfo;
6115 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006116 }
6117
6118 if (lproto) allRTypes = false;
6119 if (rproto) allLTypes = false;
6120
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006121 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006122 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006123 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006124 if (proto->isVariadic()) return QualType();
6125 // Check that the types are compatible with the types that
6126 // would result from default argument promotions (C99 6.7.5.3p15).
6127 // The only types actually affected are promotable integer
6128 // types and floats, which would be passed as a different
6129 // type depending on whether the prototype is visible.
6130 unsigned proto_nargs = proto->getNumArgs();
6131 for (unsigned i = 0; i < proto_nargs; ++i) {
6132 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00006133
6134 // Look at the promotion type of enum types, since that is the type used
6135 // to pass enum values.
6136 if (const EnumType *Enum = argTy->getAs<EnumType>())
6137 argTy = Enum->getDecl()->getPromotionType();
6138
Eli Friedman47f77112008-08-22 00:56:42 +00006139 if (argTy->isPromotableIntegerType() ||
6140 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6141 return QualType();
6142 }
6143
6144 if (allLTypes) return lhs;
6145 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006146
6147 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6148 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00006149 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006150 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006151 }
6152
6153 if (allLTypes) return lhs;
6154 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00006155 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00006156}
6157
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006158QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006159 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006160 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00006161 // C++ [expr]: If an expression initially has the type "reference to T", the
6162 // type is adjusted to "T" prior to any further analysis, the expression
6163 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006164 // expression is an lvalue unless the reference is an rvalue reference and
6165 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00006166 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6167 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006168
6169 if (Unqualified) {
6170 LHS = LHS.getUnqualifiedType();
6171 RHS = RHS.getUnqualifiedType();
6172 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00006173
Eli Friedman47f77112008-08-22 00:56:42 +00006174 QualType LHSCan = getCanonicalType(LHS),
6175 RHSCan = getCanonicalType(RHS);
6176
6177 // If two types are identical, they are compatible.
6178 if (LHSCan == RHSCan)
6179 return LHS;
6180
John McCall8ccfcb52009-09-24 19:53:00 +00006181 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006182 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6183 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00006184 if (LQuals != RQuals) {
6185 // If any of these qualifiers are different, we have a type
6186 // mismatch.
6187 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00006188 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6189 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00006190 return QualType();
6191
6192 // Exactly one GC qualifier difference is allowed: __strong is
6193 // okay if the other type has no GC qualifier but is an Objective
6194 // C object pointer (i.e. implicitly strong by default). We fix
6195 // this by pretending that the unqualified type was actually
6196 // qualified __strong.
6197 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6198 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6199 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6200
6201 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6202 return QualType();
6203
6204 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6205 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6206 }
6207 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6208 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6209 }
Eli Friedman47f77112008-08-22 00:56:42 +00006210 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00006211 }
6212
6213 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00006214
Eli Friedmandcca6332009-06-01 01:22:52 +00006215 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6216 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00006217
Chris Lattnerfd652912008-01-14 05:45:46 +00006218 // We want to consider the two function types to be the same for these
6219 // comparisons, just force one to the other.
6220 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6221 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00006222
6223 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00006224 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6225 LHSClass = Type::ConstantArray;
6226 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6227 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00006228
John McCall8b07ec22010-05-15 11:32:37 +00006229 // ObjCInterfaces are just specialized ObjCObjects.
6230 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6231 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6232
Nate Begemance4d7fc2008-04-18 23:10:10 +00006233 // Canonicalize ExtVector -> Vector.
6234 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6235 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00006236
Chris Lattner95554662008-04-07 05:43:21 +00006237 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006238 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00006239 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00006240 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00006241 // Compatibility is based on the underlying type, not the promotion
6242 // type.
John McCall9dd450b2009-09-21 23:43:11 +00006243 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006244 QualType TINT = ETy->getDecl()->getIntegerType();
6245 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006246 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006247 }
John McCall9dd450b2009-09-21 23:43:11 +00006248 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006249 QualType TINT = ETy->getDecl()->getIntegerType();
6250 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006251 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006252 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006253 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00006254 if (OfBlockPointer && !BlockReturnType) {
6255 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6256 return LHS;
6257 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6258 return RHS;
6259 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006260
Eli Friedman47f77112008-08-22 00:56:42 +00006261 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00006262 }
Eli Friedman47f77112008-08-22 00:56:42 +00006263
Steve Naroffc6edcbd2008-01-09 22:43:08 +00006264 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006265 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006266#define TYPE(Class, Base)
6267#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00006268#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006269#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6270#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6271#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00006272 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006273
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006274 case Type::LValueReference:
6275 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006276 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00006277 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006278
John McCall8b07ec22010-05-15 11:32:37 +00006279 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006280 case Type::IncompleteArray:
6281 case Type::VariableArray:
6282 case Type::FunctionProto:
6283 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00006284 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006285
Chris Lattnerfd652912008-01-14 05:45:46 +00006286 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00006287 {
6288 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006289 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6290 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006291 if (Unqualified) {
6292 LHSPointee = LHSPointee.getUnqualifiedType();
6293 RHSPointee = RHSPointee.getUnqualifiedType();
6294 }
6295 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6296 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006297 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00006298 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006299 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00006300 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006301 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006302 return getPointerType(ResultType);
6303 }
Steve Naroff68e167d2008-12-10 17:49:55 +00006304 case Type::BlockPointer:
6305 {
6306 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006307 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6308 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006309 if (Unqualified) {
6310 LHSPointee = LHSPointee.getUnqualifiedType();
6311 RHSPointee = RHSPointee.getUnqualifiedType();
6312 }
6313 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6314 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00006315 if (ResultType.isNull()) return QualType();
6316 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6317 return LHS;
6318 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6319 return RHS;
6320 return getBlockPointerType(ResultType);
6321 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00006322 case Type::Atomic:
6323 {
6324 // Merge two pointer types, while trying to preserve typedef info
6325 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6326 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6327 if (Unqualified) {
6328 LHSValue = LHSValue.getUnqualifiedType();
6329 RHSValue = RHSValue.getUnqualifiedType();
6330 }
6331 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6332 Unqualified);
6333 if (ResultType.isNull()) return QualType();
6334 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6335 return LHS;
6336 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6337 return RHS;
6338 return getAtomicType(ResultType);
6339 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006340 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00006341 {
6342 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6343 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6344 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6345 return QualType();
6346
6347 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6348 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006349 if (Unqualified) {
6350 LHSElem = LHSElem.getUnqualifiedType();
6351 RHSElem = RHSElem.getUnqualifiedType();
6352 }
6353
6354 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006355 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00006356 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6357 return LHS;
6358 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6359 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00006360 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6361 ArrayType::ArraySizeModifier(), 0);
6362 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6363 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006364 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6365 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00006366 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6367 return LHS;
6368 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6369 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006370 if (LVAT) {
6371 // FIXME: This isn't correct! But tricky to implement because
6372 // the array's size has to be the size of LHS, but the type
6373 // has to be different.
6374 return LHS;
6375 }
6376 if (RVAT) {
6377 // FIXME: This isn't correct! But tricky to implement because
6378 // the array's size has to be the size of RHS, but the type
6379 // has to be different.
6380 return RHS;
6381 }
Eli Friedman3e62c212008-08-22 01:48:21 +00006382 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6383 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00006384 return getIncompleteArrayType(ResultType,
6385 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006386 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006387 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006388 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006389 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006390 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00006391 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00006392 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006393 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00006394 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00006395 case Type::Complex:
6396 // Distinct complex types are incompatible.
6397 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006398 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00006399 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00006400 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6401 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00006402 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00006403 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00006404 case Type::ObjCObject: {
6405 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00006406 // FIXME: This should be type compatibility, e.g. whether
6407 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00006408 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6409 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6410 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00006411 return LHS;
6412
Eli Friedman47f77112008-08-22 00:56:42 +00006413 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00006414 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006415 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006416 if (OfBlockPointer) {
6417 if (canAssignObjCInterfacesInBlockPointer(
6418 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006419 RHS->getAs<ObjCObjectPointerType>(),
6420 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00006421 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006422 return QualType();
6423 }
John McCall9dd450b2009-09-21 23:43:11 +00006424 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6425 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006426 return LHS;
6427
Steve Naroffc68cfcf2008-12-10 22:14:21 +00006428 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00006429 }
Steve Naroff32e44c02007-10-15 20:41:53 +00006430 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006431
David Blaikie8a40f702012-01-17 06:56:22 +00006432 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00006433}
Ted Kremenekfc581a92007-10-31 17:10:13 +00006434
Fariborz Jahanian97676972011-09-28 21:52:05 +00006435bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6436 const FunctionProtoType *FromFunctionType,
6437 const FunctionProtoType *ToFunctionType) {
6438 if (FromFunctionType->hasAnyConsumedArgs() !=
6439 ToFunctionType->hasAnyConsumedArgs())
6440 return false;
6441 FunctionProtoType::ExtProtoInfo FromEPI =
6442 FromFunctionType->getExtProtoInfo();
6443 FunctionProtoType::ExtProtoInfo ToEPI =
6444 ToFunctionType->getExtProtoInfo();
6445 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6446 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6447 ArgIdx != NumArgs; ++ArgIdx) {
6448 if (FromEPI.ConsumedArguments[ArgIdx] !=
6449 ToEPI.ConsumedArguments[ArgIdx])
6450 return false;
6451 }
6452 return true;
6453}
6454
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006455/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6456/// 'RHS' attributes and returns the merged version; including for function
6457/// return types.
6458QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6459 QualType LHSCan = getCanonicalType(LHS),
6460 RHSCan = getCanonicalType(RHS);
6461 // If two types are identical, they are compatible.
6462 if (LHSCan == RHSCan)
6463 return LHS;
6464 if (RHSCan->isFunctionType()) {
6465 if (!LHSCan->isFunctionType())
6466 return QualType();
6467 QualType OldReturnType =
6468 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6469 QualType NewReturnType =
6470 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6471 QualType ResReturnType =
6472 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6473 if (ResReturnType.isNull())
6474 return QualType();
6475 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6476 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6477 // In either case, use OldReturnType to build the new function type.
6478 const FunctionType *F = LHS->getAs<FunctionType>();
6479 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00006480 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6481 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006482 QualType ResultType
6483 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006484 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006485 return ResultType;
6486 }
6487 }
6488 return QualType();
6489 }
6490
6491 // If the qualifiers are different, the types can still be merged.
6492 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6493 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6494 if (LQuals != RQuals) {
6495 // If any of these qualifiers are different, we have a type mismatch.
6496 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6497 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6498 return QualType();
6499
6500 // Exactly one GC qualifier difference is allowed: __strong is
6501 // okay if the other type has no GC qualifier but is an Objective
6502 // C object pointer (i.e. implicitly strong by default). We fix
6503 // this by pretending that the unqualified type was actually
6504 // qualified __strong.
6505 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6506 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6507 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6508
6509 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6510 return QualType();
6511
6512 if (GC_L == Qualifiers::Strong)
6513 return LHS;
6514 if (GC_R == Qualifiers::Strong)
6515 return RHS;
6516 return QualType();
6517 }
6518
6519 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6520 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6521 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6522 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6523 if (ResQT == LHSBaseQT)
6524 return LHS;
6525 if (ResQT == RHSBaseQT)
6526 return RHS;
6527 }
6528 return QualType();
6529}
6530
Chris Lattner4ba0cef2008-04-07 07:01:58 +00006531//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006532// Integer Predicates
6533//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00006534
Jay Foad39c79802011-01-12 09:06:06 +00006535unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00006536 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00006537 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00006538 if (T->isBooleanType())
6539 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00006540 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006541 return (unsigned)getTypeSize(T);
6542}
6543
6544QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006545 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00006546
6547 // Turn <4 x signed int> -> <4 x unsigned int>
6548 if (const VectorType *VTy = T->getAs<VectorType>())
6549 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00006550 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00006551
6552 // For enums, we return the unsigned version of the base type.
6553 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006554 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00006555
6556 const BuiltinType *BTy = T->getAs<BuiltinType>();
6557 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006558 switch (BTy->getKind()) {
6559 case BuiltinType::Char_S:
6560 case BuiltinType::SChar:
6561 return UnsignedCharTy;
6562 case BuiltinType::Short:
6563 return UnsignedShortTy;
6564 case BuiltinType::Int:
6565 return UnsignedIntTy;
6566 case BuiltinType::Long:
6567 return UnsignedLongTy;
6568 case BuiltinType::LongLong:
6569 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00006570 case BuiltinType::Int128:
6571 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006572 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006573 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006574 }
6575}
6576
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00006577ASTMutationListener::~ASTMutationListener() { }
6578
Chris Lattnerecd79c62009-06-14 00:45:47 +00006579
6580//===----------------------------------------------------------------------===//
6581// Builtin Type Computation
6582//===----------------------------------------------------------------------===//
6583
6584/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00006585/// pointer over the consumed characters. This returns the resultant type. If
6586/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6587/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6588/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006589///
6590/// RequiresICE is filled in on return to indicate whether the value is required
6591/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00006592static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00006593 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006594 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00006595 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00006596 // Modifiers.
6597 int HowLong = 0;
6598 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006599 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00006600
Chris Lattnerdc226c22010-10-01 22:42:38 +00006601 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00006602 bool Done = false;
6603 while (!Done) {
6604 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00006605 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00006606 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006607 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00006608 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006609 case 'S':
6610 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6611 assert(!Signed && "Can't use 'S' modifier multiple times!");
6612 Signed = true;
6613 break;
6614 case 'U':
6615 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6616 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6617 Unsigned = true;
6618 break;
6619 case 'L':
6620 assert(HowLong <= 2 && "Can't have LLLL modifier");
6621 ++HowLong;
6622 break;
6623 }
6624 }
6625
6626 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00006627
Chris Lattnerecd79c62009-06-14 00:45:47 +00006628 // Read the base type.
6629 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00006630 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006631 case 'v':
6632 assert(HowLong == 0 && !Signed && !Unsigned &&
6633 "Bad modifiers used with 'v'!");
6634 Type = Context.VoidTy;
6635 break;
6636 case 'f':
6637 assert(HowLong == 0 && !Signed && !Unsigned &&
6638 "Bad modifiers used with 'f'!");
6639 Type = Context.FloatTy;
6640 break;
6641 case 'd':
6642 assert(HowLong < 2 && !Signed && !Unsigned &&
6643 "Bad modifiers used with 'd'!");
6644 if (HowLong)
6645 Type = Context.LongDoubleTy;
6646 else
6647 Type = Context.DoubleTy;
6648 break;
6649 case 's':
6650 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6651 if (Unsigned)
6652 Type = Context.UnsignedShortTy;
6653 else
6654 Type = Context.ShortTy;
6655 break;
6656 case 'i':
6657 if (HowLong == 3)
6658 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6659 else if (HowLong == 2)
6660 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6661 else if (HowLong == 1)
6662 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6663 else
6664 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6665 break;
6666 case 'c':
6667 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6668 if (Signed)
6669 Type = Context.SignedCharTy;
6670 else if (Unsigned)
6671 Type = Context.UnsignedCharTy;
6672 else
6673 Type = Context.CharTy;
6674 break;
6675 case 'b': // boolean
6676 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6677 Type = Context.BoolTy;
6678 break;
6679 case 'z': // size_t.
6680 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6681 Type = Context.getSizeType();
6682 break;
6683 case 'F':
6684 Type = Context.getCFConstantStringType();
6685 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00006686 case 'G':
6687 Type = Context.getObjCIdType();
6688 break;
6689 case 'H':
6690 Type = Context.getObjCSelType();
6691 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006692 case 'a':
6693 Type = Context.getBuiltinVaListType();
6694 assert(!Type.isNull() && "builtin va list type not initialized!");
6695 break;
6696 case 'A':
6697 // This is a "reference" to a va_list; however, what exactly
6698 // this means depends on how va_list is defined. There are two
6699 // different kinds of va_list: ones passed by value, and ones
6700 // passed by reference. An example of a by-value va_list is
6701 // x86, where va_list is a char*. An example of by-ref va_list
6702 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6703 // we want this argument to be a char*&; for x86-64, we want
6704 // it to be a __va_list_tag*.
6705 Type = Context.getBuiltinVaListType();
6706 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006707 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00006708 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006709 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00006710 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006711 break;
6712 case 'V': {
6713 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006714 unsigned NumElements = strtoul(Str, &End, 10);
6715 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006716 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00006717
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006718 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6719 RequiresICE, false);
6720 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00006721
6722 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00006723 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00006724 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006725 break;
6726 }
Douglas Gregorfed66992012-06-07 18:08:25 +00006727 case 'E': {
6728 char *End;
6729
6730 unsigned NumElements = strtoul(Str, &End, 10);
6731 assert(End != Str && "Missing vector size");
6732
6733 Str = End;
6734
6735 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6736 false);
6737 Type = Context.getExtVectorType(ElementType, NumElements);
6738 break;
6739 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006740 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006741 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6742 false);
6743 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006744 Type = Context.getComplexType(ElementType);
6745 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00006746 }
6747 case 'Y' : {
6748 Type = Context.getPointerDiffType();
6749 break;
6750 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00006751 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00006752 Type = Context.getFILEType();
6753 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006754 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006755 return QualType();
6756 }
Mike Stump2adb4da2009-07-28 23:47:15 +00006757 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00006758 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00006759 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00006760 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00006761 else
6762 Type = Context.getjmp_bufType();
6763
Mike Stump2adb4da2009-07-28 23:47:15 +00006764 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006765 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00006766 return QualType();
6767 }
6768 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00006769 case 'K':
6770 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
6771 Type = Context.getucontext_tType();
6772
6773 if (Type.isNull()) {
6774 Error = ASTContext::GE_Missing_ucontext;
6775 return QualType();
6776 }
6777 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00006778 }
Mike Stump11289f42009-09-09 15:08:12 +00006779
Chris Lattnerdc226c22010-10-01 22:42:38 +00006780 // If there are modifiers and if we're allowed to parse them, go for it.
6781 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006782 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00006783 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006784 default: Done = true; --Str; break;
6785 case '*':
6786 case '&': {
6787 // Both pointers and references can have their pointee types
6788 // qualified with an address space.
6789 char *End;
6790 unsigned AddrSpace = strtoul(Str, &End, 10);
6791 if (End != Str && AddrSpace != 0) {
6792 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6793 Str = End;
6794 }
6795 if (c == '*')
6796 Type = Context.getPointerType(Type);
6797 else
6798 Type = Context.getLValueReferenceType(Type);
6799 break;
6800 }
6801 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6802 case 'C':
6803 Type = Type.withConst();
6804 break;
6805 case 'D':
6806 Type = Context.getVolatileType(Type);
6807 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00006808 case 'R':
6809 Type = Type.withRestrict();
6810 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006811 }
6812 }
Chris Lattner84733392010-10-01 07:13:18 +00006813
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006814 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00006815 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00006816
Chris Lattnerecd79c62009-06-14 00:45:47 +00006817 return Type;
6818}
6819
6820/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00006821QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006822 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00006823 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006824 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00006825
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006826 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00006827
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006828 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006829 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006830 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6831 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006832 if (Error != GE_None)
6833 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006834
6835 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6836
Chris Lattnerecd79c62009-06-14 00:45:47 +00006837 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006838 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006839 if (Error != GE_None)
6840 return QualType();
6841
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006842 // If this argument is required to be an IntegerConstantExpression and the
6843 // caller cares, fill in the bitmask we return.
6844 if (RequiresICE && IntegerConstantArgs)
6845 *IntegerConstantArgs |= 1 << ArgTypes.size();
6846
Chris Lattnerecd79c62009-06-14 00:45:47 +00006847 // Do array -> pointer decay. The builtin should use the decayed type.
6848 if (Ty->isArrayType())
6849 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00006850
Chris Lattnerecd79c62009-06-14 00:45:47 +00006851 ArgTypes.push_back(Ty);
6852 }
6853
6854 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6855 "'.' should only occur at end of builtin type list!");
6856
John McCall991eb4b2010-12-21 00:44:39 +00006857 FunctionType::ExtInfo EI;
6858 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6859
6860 bool Variadic = (TypeStr[0] == '.');
6861
6862 // We really shouldn't be making a no-proto type here, especially in C++.
6863 if (ArgTypes.empty() && Variadic)
6864 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00006865
John McCalldb40c7f2010-12-14 08:05:40 +00006866 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00006867 EPI.ExtInfo = EI;
6868 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00006869
6870 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006871}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00006872
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006873GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6874 GVALinkage External = GVA_StrongExternal;
6875
6876 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006877 switch (L) {
6878 case NoLinkage:
6879 case InternalLinkage:
6880 case UniqueExternalLinkage:
6881 return GVA_Internal;
6882
6883 case ExternalLinkage:
6884 switch (FD->getTemplateSpecializationKind()) {
6885 case TSK_Undeclared:
6886 case TSK_ExplicitSpecialization:
6887 External = GVA_StrongExternal;
6888 break;
6889
6890 case TSK_ExplicitInstantiationDefinition:
6891 return GVA_ExplicitTemplateInstantiation;
6892
6893 case TSK_ExplicitInstantiationDeclaration:
6894 case TSK_ImplicitInstantiation:
6895 External = GVA_TemplateInstantiation;
6896 break;
6897 }
6898 }
6899
6900 if (!FD->isInlined())
6901 return External;
6902
David Blaikiebbafb8a2012-03-11 07:00:24 +00006903 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006904 // GNU or C99 inline semantics. Determine whether this symbol should be
6905 // externally visible.
6906 if (FD->isInlineDefinitionExternallyVisible())
6907 return External;
6908
6909 // C99 inline semantics, where the symbol is not externally visible.
6910 return GVA_C99Inline;
6911 }
6912
6913 // C++0x [temp.explicit]p9:
6914 // [ Note: The intent is that an inline function that is the subject of
6915 // an explicit instantiation declaration will still be implicitly
6916 // instantiated when used so that the body can be considered for
6917 // inlining, but that no out-of-line copy of the inline function would be
6918 // generated in the translation unit. -- end note ]
6919 if (FD->getTemplateSpecializationKind()
6920 == TSK_ExplicitInstantiationDeclaration)
6921 return GVA_C99Inline;
6922
6923 return GVA_CXXInline;
6924}
6925
6926GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6927 // If this is a static data member, compute the kind of template
6928 // specialization. Otherwise, this variable is not part of a
6929 // template.
6930 TemplateSpecializationKind TSK = TSK_Undeclared;
6931 if (VD->isStaticDataMember())
6932 TSK = VD->getTemplateSpecializationKind();
6933
6934 Linkage L = VD->getLinkage();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006935 if (L == ExternalLinkage && getLangOpts().CPlusPlus &&
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006936 VD->getType()->getLinkage() == UniqueExternalLinkage)
6937 L = UniqueExternalLinkage;
6938
6939 switch (L) {
6940 case NoLinkage:
6941 case InternalLinkage:
6942 case UniqueExternalLinkage:
6943 return GVA_Internal;
6944
6945 case ExternalLinkage:
6946 switch (TSK) {
6947 case TSK_Undeclared:
6948 case TSK_ExplicitSpecialization:
6949 return GVA_StrongExternal;
6950
6951 case TSK_ExplicitInstantiationDeclaration:
6952 llvm_unreachable("Variable should not be instantiated");
6953 // Fall through to treat this like any other instantiation.
6954
6955 case TSK_ExplicitInstantiationDefinition:
6956 return GVA_ExplicitTemplateInstantiation;
6957
6958 case TSK_ImplicitInstantiation:
6959 return GVA_TemplateInstantiation;
6960 }
6961 }
6962
David Blaikie8a40f702012-01-17 06:56:22 +00006963 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006964}
6965
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00006966bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006967 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6968 if (!VD->isFileVarDecl())
6969 return false;
Argyrios Kyrtzidisa98e8612011-09-13 21:35:00 +00006970 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006971 return false;
6972
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006973 // Weak references don't produce any output by themselves.
6974 if (D->hasAttr<WeakRefAttr>())
6975 return false;
6976
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006977 // Aliases and used decls are required.
6978 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6979 return true;
6980
6981 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6982 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00006983 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00006984 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006985
6986 // Constructors and destructors are required.
6987 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6988 return true;
6989
6990 // The key function for a class is required.
6991 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6992 const CXXRecordDecl *RD = MD->getParent();
6993 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6994 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6995 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6996 return true;
6997 }
6998 }
6999
7000 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7001
7002 // static, static inline, always_inline, and extern inline functions can
7003 // always be deferred. Normal inline functions can be deferred in C99/C++.
7004 // Implicit template instantiations can also be deferred in C++.
7005 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007006 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007007 return false;
7008 return true;
7009 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007010
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007011 const VarDecl *VD = cast<VarDecl>(D);
7012 assert(VD->isFileVarDecl() && "Expected file scoped var");
7013
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007014 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7015 return false;
7016
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007017 // Structs that have non-trivial constructors or destructors are required.
7018
7019 // FIXME: Handle references.
Alexis Huntf479f1b2011-05-09 18:22:59 +00007020 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007021 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
7022 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Alexis Huntf479f1b2011-05-09 18:22:59 +00007023 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
7024 RD->hasTrivialCopyConstructor() &&
7025 RD->hasTrivialMoveConstructor() &&
7026 RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007027 return true;
7028 }
7029 }
7030
7031 GVALinkage L = GetGVALinkageForVariable(VD);
7032 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
7033 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
7034 return false;
7035 }
7036
7037 return true;
7038}
Charles Davis53c59df2010-08-16 03:33:14 +00007039
Charles Davis99202b32010-11-09 18:04:24 +00007040CallingConv ASTContext::getDefaultMethodCallConv() {
7041 // Pass through to the C++ ABI object
7042 return ABI->getDefaultMethodCallConv();
7043}
7044
Jay Foad39c79802011-01-12 09:06:06 +00007045bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007046 // Pass through to the C++ ABI object
7047 return ABI->isNearlyEmpty(RD);
7048}
7049
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007050MangleContext *ASTContext::createMangleContext() {
Douglas Gregore8bbc122011-09-02 00:18:52 +00007051 switch (Target->getCXXABI()) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007052 case CXXABI_ARM:
7053 case CXXABI_Itanium:
7054 return createItaniumMangleContext(*this, getDiagnostics());
7055 case CXXABI_Microsoft:
7056 return createMicrosoftMangleContext(*this, getDiagnostics());
7057 }
David Blaikie83d382b2011-09-23 05:06:16 +00007058 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007059}
7060
Charles Davis53c59df2010-08-16 03:33:14 +00007061CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007062
7063size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00007064 return ASTRecordLayouts.getMemorySize()
7065 + llvm::capacity_in_bytes(ObjCLayouts)
7066 + llvm::capacity_in_bytes(KeyFunctions)
7067 + llvm::capacity_in_bytes(ObjCImpls)
7068 + llvm::capacity_in_bytes(BlockVarCopyInits)
7069 + llvm::capacity_in_bytes(DeclAttrs)
7070 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7071 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7072 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7073 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7074 + llvm::capacity_in_bytes(OverriddenMethods)
7075 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007076 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00007077 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007078}
Ted Kremenek540017e2011-10-06 05:00:56 +00007079
Douglas Gregor63798542012-02-20 19:44:39 +00007080unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7081 CXXRecordDecl *Lambda = CallOperator->getParent();
7082 return LambdaMangleContexts[Lambda->getDeclContext()]
7083 .getManglingNumber(CallOperator);
7084}
7085
7086
Ted Kremenek540017e2011-10-06 05:00:56 +00007087void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7088 ParamIndices[D] = index;
7089}
7090
7091unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7092 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7093 assert(I != ParamIndices.end() &&
7094 "ParmIndices lacks entry set by ParmVarDecl");
7095 return I->second;
7096}