blob: 66096f34e23ac653e875655b781b0a4c5a9da93f [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000022#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +000023#include "clang/AST/ASTMutationListener.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000024#include "clang/AST/RecordLayout.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000025#include "clang/AST/Mangle.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000027#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000028#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000029#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000030#include "llvm/ADT/StringExtras.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000031#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000032#include "llvm/Support/raw_ostream.h"
Ted Kremenek7d39c9a2011-07-27 18:41:12 +000033#include "llvm/Support/Capacity.h"
Charles Davis53c59df2010-08-16 03:33:14 +000034#include "CXXABI.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000035#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000036
Chris Lattnerddc135e2006-11-10 06:34:16 +000037using namespace clang;
38
Douglas Gregor9672f922010-07-03 00:47:00 +000039unsigned ASTContext::NumImplicitDefaultConstructors;
40unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000041unsigned ASTContext::NumImplicitCopyConstructors;
42unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000043unsigned ASTContext::NumImplicitMoveConstructors;
44unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000045unsigned ASTContext::NumImplicitCopyAssignmentOperators;
46unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000047unsigned ASTContext::NumImplicitMoveAssignmentOperators;
48unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000049unsigned ASTContext::NumImplicitDestructors;
50unsigned ASTContext::NumImplicitDestructorsDeclared;
51
Steve Naroff0af91202007-04-27 21:51:21 +000052enum FloatingRank {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000053 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Steve Naroff0af91202007-04-27 21:51:21 +000054};
55
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000056const RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
57 if (!CommentsLoaded && ExternalSource) {
58 ExternalSource->ReadComments();
59 CommentsLoaded = true;
60 }
61
62 assert(D);
63
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000064 // User can not attach documentation to implicit declarations.
65 if (D->isImplicit())
66 return NULL;
67
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000068 // TODO: handle comments for function parameters properly.
69 if (isa<ParmVarDecl>(D))
70 return NULL;
71
72 ArrayRef<RawComment> RawComments = Comments.getComments();
73
74 // If there are no comments anywhere, we won't find anything.
75 if (RawComments.empty())
76 return NULL;
77
78 // If the declaration doesn't map directly to a location in a file, we
79 // can't find the comment.
80 SourceLocation DeclLoc = D->getLocation();
81 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
82 return NULL;
83
84 // Find the comment that occurs just after this declaration.
85 ArrayRef<RawComment>::iterator Comment
86 = std::lower_bound(RawComments.begin(),
87 RawComments.end(),
Dmitri Gribenkofecc2e02012-06-21 21:02:45 +000088 RawComment(SourceMgr, SourceRange(DeclLoc)),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000089 BeforeThanCompare<RawComment>(SourceMgr));
90
91 // Decompose the location for the declaration and find the beginning of the
92 // file buffer.
93 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
94
95 // First check whether we have a trailing comment.
96 if (Comment != RawComments.end() &&
Dmitri Gribenko5188c4b2012-06-26 20:39:18 +000097 Comment->isDocumentation() && Comment->isTrailingComment() &&
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000098 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D)) {
99 std::pair<FileID, unsigned> CommentBeginDecomp
100 = SourceMgr.getDecomposedLoc(Comment->getSourceRange().getBegin());
101 // Check that Doxygen trailing comment comes after the declaration, starts
102 // on the same line and in the same file as the declaration.
103 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
104 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
105 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
106 CommentBeginDecomp.second)) {
107 return &*Comment;
108 }
109 }
110
111 // The comment just after the declaration was not a trailing comment.
112 // Let's look at the previous comment.
113 if (Comment == RawComments.begin())
114 return NULL;
115 --Comment;
116
117 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko5188c4b2012-06-26 20:39:18 +0000118 if (!Comment->isDocumentation() || Comment->isTrailingComment())
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000119 return NULL;
120
121 // Decompose the end of the comment.
122 std::pair<FileID, unsigned> CommentEndDecomp
123 = SourceMgr.getDecomposedLoc(Comment->getSourceRange().getEnd());
124
125 // If the comment and the declaration aren't in the same file, then they
126 // aren't related.
127 if (DeclLocDecomp.first != CommentEndDecomp.first)
128 return NULL;
129
130 // Get the corresponding buffer.
131 bool Invalid = false;
132 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
133 &Invalid).data();
134 if (Invalid)
135 return NULL;
136
137 // Extract text between the comment and declaration.
138 StringRef Text(Buffer + CommentEndDecomp.second,
139 DeclLocDecomp.second - CommentEndDecomp.second);
140
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000141 // There should be no other declarations or preprocessor directives between
142 // comment and declaration.
143 if (Text.find_first_of(",;{}#") != StringRef::npos)
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000144 return NULL;
145
146 return &*Comment;
147}
148
149const RawComment *ASTContext::getRawCommentForDecl(const Decl *D) const {
150 // Check whether we have cached a comment string for this declaration
151 // already.
152 llvm::DenseMap<const Decl *, const RawComment *>::iterator Pos
153 = DeclComments.find(D);
154 if (Pos != DeclComments.end())
155 return Pos->second;
156
157 const RawComment *RC = getRawCommentForDeclNoCache(D);
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000158 // If we found a comment, it should be a documentation comment.
159 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000160 DeclComments[D] = RC;
161 return RC;
162}
163
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000164void
165ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
166 TemplateTemplateParmDecl *Parm) {
167 ID.AddInteger(Parm->getDepth());
168 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000169 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000170
171 TemplateParameterList *Params = Parm->getTemplateParameters();
172 ID.AddInteger(Params->size());
173 for (TemplateParameterList::const_iterator P = Params->begin(),
174 PEnd = Params->end();
175 P != PEnd; ++P) {
176 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
177 ID.AddInteger(0);
178 ID.AddBoolean(TTP->isParameterPack());
179 continue;
180 }
181
182 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
183 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000184 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000185 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000186 if (NTTP->isExpandedParameterPack()) {
187 ID.AddBoolean(true);
188 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000189 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
190 QualType T = NTTP->getExpansionType(I);
191 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
192 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000193 } else
194 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000195 continue;
196 }
197
198 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
199 ID.AddInteger(2);
200 Profile(ID, TTP);
201 }
202}
203
204TemplateTemplateParmDecl *
205ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000206 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000207 // Check if we already have a canonical template template parameter.
208 llvm::FoldingSetNodeID ID;
209 CanonicalTemplateTemplateParm::Profile(ID, TTP);
210 void *InsertPos = 0;
211 CanonicalTemplateTemplateParm *Canonical
212 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
213 if (Canonical)
214 return Canonical->getParam();
215
216 // Build a canonical template parameter list.
217 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000218 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000219 CanonParams.reserve(Params->size());
220 for (TemplateParameterList::const_iterator P = Params->begin(),
221 PEnd = Params->end();
222 P != PEnd; ++P) {
223 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
224 CanonParams.push_back(
225 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000226 SourceLocation(),
227 SourceLocation(),
228 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000229 TTP->getIndex(), 0, false,
230 TTP->isParameterPack()));
231 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000232 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
233 QualType T = getCanonicalType(NTTP->getType());
234 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
235 NonTypeTemplateParmDecl *Param;
236 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000237 SmallVector<QualType, 2> ExpandedTypes;
238 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000239 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
240 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
241 ExpandedTInfos.push_back(
242 getTrivialTypeSourceInfo(ExpandedTypes.back()));
243 }
244
245 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000246 SourceLocation(),
247 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000248 NTTP->getDepth(),
249 NTTP->getPosition(), 0,
250 T,
251 TInfo,
252 ExpandedTypes.data(),
253 ExpandedTypes.size(),
254 ExpandedTInfos.data());
255 } else {
256 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000257 SourceLocation(),
258 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000259 NTTP->getDepth(),
260 NTTP->getPosition(), 0,
261 T,
262 NTTP->isParameterPack(),
263 TInfo);
264 }
265 CanonParams.push_back(Param);
266
267 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000268 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
269 cast<TemplateTemplateParmDecl>(*P)));
270 }
271
272 TemplateTemplateParmDecl *CanonTTP
273 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
274 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000275 TTP->getPosition(),
276 TTP->isParameterPack(),
277 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000278 TemplateParameterList::Create(*this, SourceLocation(),
279 SourceLocation(),
280 CanonParams.data(),
281 CanonParams.size(),
282 SourceLocation()));
283
284 // Get the new insert position for the node we care about.
285 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
286 assert(Canonical == 0 && "Shouldn't be in the map!");
287 (void)Canonical;
288
289 // Create the canonical template template parameter entry.
290 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
291 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
292 return CanonTTP;
293}
294
Charles Davis53c59df2010-08-16 03:33:14 +0000295CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000296 if (!LangOpts.CPlusPlus) return 0;
297
Charles Davis6bcb07a2010-08-19 02:18:14 +0000298 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000299 case CXXABI_ARM:
300 return CreateARMCXXABI(*this);
301 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000302 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000303 case CXXABI_Microsoft:
304 return CreateMicrosoftCXXABI(*this);
305 }
David Blaikie8a40f702012-01-17 06:56:22 +0000306 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000307}
308
Douglas Gregore8bbc122011-09-02 00:18:52 +0000309static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000310 const LangOptions &LOpts) {
311 if (LOpts.FakeAddressSpaceMap) {
312 // The fake address space map must have a distinct entry for each
313 // language-specific address space.
314 static const unsigned FakeAddrSpaceMap[] = {
315 1, // opencl_global
316 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000317 3, // opencl_constant
318 4, // cuda_device
319 5, // cuda_constant
320 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000321 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000322 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000323 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000324 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000325 }
326}
327
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000328ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000329 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000330 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000331 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000332 unsigned size_reserve,
333 bool DelayInitialization)
334 : FunctionProtoTypes(this_()),
335 TemplateSpecializationTypes(this_()),
336 DependentTemplateSpecializationTypes(this_()),
337 SubstTemplateTemplateParmPacks(this_()),
338 GlobalNestedNameSpecifier(0),
339 Int128Decl(0), UInt128Decl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000340 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000341 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000342 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000343 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000344 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
345 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
346 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000347 NullTypeSourceInfo(QualType()),
348 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000349 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000350 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000351 Idents(idents), Selectors(sels),
352 BuiltinInfo(builtins),
353 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000354 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000355 Comments(SM), CommentsLoaded(false),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000356 LastSDM(0, 0),
357 UniqueBlockByRefTypeID(0)
358{
Mike Stump11289f42009-09-09 15:08:12 +0000359 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000360 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000361
362 if (!DelayInitialization) {
363 assert(t && "No target supplied for ASTContext initialization");
364 InitBuiltinTypes(*t);
365 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000366}
367
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000368ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000369 // Release the DenseMaps associated with DeclContext objects.
370 // FIXME: Is this the ideal solution?
371 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000372
Douglas Gregor5b11d492010-07-25 17:53:33 +0000373 // Call all of the deallocation functions.
374 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
375 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000376
Ted Kremenek076baeb2010-06-08 23:00:58 +0000377 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000378 // because they can contain DenseMaps.
379 for (llvm::DenseMap<const ObjCContainerDecl*,
380 const ASTRecordLayout*>::iterator
381 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
382 // Increment in loop to prevent using deallocated memory.
383 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
384 R->Destroy(*this);
385
Ted Kremenek076baeb2010-06-08 23:00:58 +0000386 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
387 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
388 // Increment in loop to prevent using deallocated memory.
389 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
390 R->Destroy(*this);
391 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000392
393 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
394 AEnd = DeclAttrs.end();
395 A != AEnd; ++A)
396 A->second->~AttrVec();
397}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000398
Douglas Gregor1a809332010-05-23 18:26:36 +0000399void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
400 Deallocations.push_back(std::make_pair(Callback, Data));
401}
402
Mike Stump11289f42009-09-09 15:08:12 +0000403void
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000404ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000405 ExternalSource.reset(Source.take());
406}
407
Chris Lattner4eb445d2007-01-26 01:27:23 +0000408void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000409 llvm::errs() << "\n*** AST Context Stats:\n";
410 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000411
Douglas Gregora30d0462009-05-26 14:40:08 +0000412 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000413#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000414#define ABSTRACT_TYPE(Name, Parent)
415#include "clang/AST/TypeNodes.def"
416 0 // Extra
417 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000418
Chris Lattner4eb445d2007-01-26 01:27:23 +0000419 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
420 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000421 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000422 }
423
Douglas Gregora30d0462009-05-26 14:40:08 +0000424 unsigned Idx = 0;
425 unsigned TotalBytes = 0;
426#define TYPE(Name, Parent) \
427 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000428 llvm::errs() << " " << counts[Idx] << " " << #Name \
429 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000430 TotalBytes += counts[Idx] * sizeof(Name##Type); \
431 ++Idx;
432#define ABSTRACT_TYPE(Name, Parent)
433#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000434
Chandler Carruth3c147a72011-07-04 05:32:14 +0000435 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
436
Douglas Gregor7454c562010-07-02 20:37:36 +0000437 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000438 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
439 << NumImplicitDefaultConstructors
440 << " implicit default constructors created\n";
441 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
442 << NumImplicitCopyConstructors
443 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000444 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000445 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
446 << NumImplicitMoveConstructors
447 << " implicit move constructors created\n";
448 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
449 << NumImplicitCopyAssignmentOperators
450 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000451 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000452 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
453 << NumImplicitMoveAssignmentOperators
454 << " implicit move assignment operators created\n";
455 llvm::errs() << NumImplicitDestructorsDeclared << "/"
456 << NumImplicitDestructors
457 << " implicit destructors created\n";
458
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000459 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000460 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000461 ExternalSource->PrintStats();
462 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000463
Douglas Gregor5b11d492010-07-25 17:53:33 +0000464 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000465}
466
Douglas Gregor801c99d2011-08-12 06:49:56 +0000467TypedefDecl *ASTContext::getInt128Decl() const {
468 if (!Int128Decl) {
469 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
470 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
471 getTranslationUnitDecl(),
472 SourceLocation(),
473 SourceLocation(),
474 &Idents.get("__int128_t"),
475 TInfo);
476 }
477
478 return Int128Decl;
479}
480
481TypedefDecl *ASTContext::getUInt128Decl() const {
482 if (!UInt128Decl) {
483 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
484 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
485 getTranslationUnitDecl(),
486 SourceLocation(),
487 SourceLocation(),
488 &Idents.get("__uint128_t"),
489 TInfo);
490 }
491
492 return UInt128Decl;
493}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000494
John McCall48f2d582009-10-23 23:03:21 +0000495void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000496 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000497 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000498 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000499}
500
Douglas Gregore8bbc122011-09-02 00:18:52 +0000501void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
502 assert((!this->Target || this->Target == &Target) &&
503 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000504 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000505
Douglas Gregore8bbc122011-09-02 00:18:52 +0000506 this->Target = &Target;
507
508 ABI.reset(createCXXABI(Target));
509 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
510
Chris Lattner970e54e2006-11-12 00:37:36 +0000511 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000512 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000513
Chris Lattner970e54e2006-11-12 00:37:36 +0000514 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000515 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000516 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000517 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000518 InitBuiltinType(CharTy, BuiltinType::Char_S);
519 else
520 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000521 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000522 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
523 InitBuiltinType(ShortTy, BuiltinType::Short);
524 InitBuiltinType(IntTy, BuiltinType::Int);
525 InitBuiltinType(LongTy, BuiltinType::Long);
526 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000527
Chris Lattner970e54e2006-11-12 00:37:36 +0000528 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000529 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
530 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
531 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
532 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
533 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000534
Chris Lattner970e54e2006-11-12 00:37:36 +0000535 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000536 InitBuiltinType(FloatTy, BuiltinType::Float);
537 InitBuiltinType(DoubleTy, BuiltinType::Double);
538 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000539
Chris Lattnerf122cef2009-04-30 02:43:43 +0000540 // GNU extension, 128-bit integers.
541 InitBuiltinType(Int128Ty, BuiltinType::Int128);
542 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
543
Chris Lattnerad3467e2010-12-25 23:25:43 +0000544 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedman786d0872011-04-30 19:24:24 +0000545 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000546 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
547 else // -fshort-wchar makes wchar_t be unsigned.
548 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
549 } else // C99
Chris Lattner007cb022009-02-26 23:43:47 +0000550 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000551
James Molloy36365542012-05-04 10:55:22 +0000552 WIntTy = getFromTargetType(Target.getWIntType());
553
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000554 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
555 InitBuiltinType(Char16Ty, BuiltinType::Char16);
556 else // C99
557 Char16Ty = getFromTargetType(Target.getChar16Type());
558
559 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
560 InitBuiltinType(Char32Ty, BuiltinType::Char32);
561 else // C99
562 Char32Ty = getFromTargetType(Target.getChar32Type());
563
Douglas Gregor4619e432008-12-05 23:32:09 +0000564 // Placeholder type for type-dependent expressions whose type is
565 // completely unknown. No code should ever check a type against
566 // DependentTy and users should never see it; however, it is here to
567 // help diagnose failures to properly check for type-dependent
568 // expressions.
569 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000570
John McCall36e7fe32010-10-12 00:20:44 +0000571 // Placeholder type for functions.
572 InitBuiltinType(OverloadTy, BuiltinType::Overload);
573
John McCall0009fcc2011-04-26 20:42:42 +0000574 // Placeholder type for bound members.
575 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
576
John McCall526ab472011-10-25 17:37:35 +0000577 // Placeholder type for pseudo-objects.
578 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
579
John McCall31996342011-04-07 08:22:57 +0000580 // "any" type; useful for debugger-like clients.
581 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
582
John McCall8a6b59a2011-10-17 18:09:15 +0000583 // Placeholder type for unbridged ARC casts.
584 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
585
Chris Lattner970e54e2006-11-12 00:37:36 +0000586 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000587 FloatComplexTy = getComplexType(FloatTy);
588 DoubleComplexTy = getComplexType(DoubleTy);
589 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000590
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000591 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000592 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
593 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000594 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000595
596 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +0000597 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
598 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000599
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000600 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000601
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000602 // void * type
603 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000604
605 // nullptr type (C++0x 2.14.7)
606 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000607
608 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
609 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +0000610
611 // Builtin type used to help define __builtin_va_list.
612 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +0000613}
614
David Blaikie9c902b52011-09-25 23:23:43 +0000615DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000616 return SourceMgr.getDiagnostics();
617}
618
Douglas Gregor561eceb2010-08-30 16:49:28 +0000619AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
620 AttrVec *&Result = DeclAttrs[D];
621 if (!Result) {
622 void *Mem = Allocate(sizeof(AttrVec));
623 Result = new (Mem) AttrVec;
624 }
625
626 return *Result;
627}
628
629/// \brief Erase the attributes corresponding to the given declaration.
630void ASTContext::eraseDeclAttrs(const Decl *D) {
631 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
632 if (Pos != DeclAttrs.end()) {
633 Pos->second->~AttrVec();
634 DeclAttrs.erase(Pos);
635 }
636}
637
Douglas Gregor86d142a2009-10-08 07:24:58 +0000638MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000639ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000640 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000641 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000642 = InstantiatedFromStaticDataMember.find(Var);
643 if (Pos == InstantiatedFromStaticDataMember.end())
644 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000645
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000646 return Pos->second;
647}
648
Mike Stump11289f42009-09-09 15:08:12 +0000649void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000650ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000651 TemplateSpecializationKind TSK,
652 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000653 assert(Inst->isStaticDataMember() && "Not a static data member");
654 assert(Tmpl->isStaticDataMember() && "Not a static data member");
655 assert(!InstantiatedFromStaticDataMember[Inst] &&
656 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000657 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000658 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000659}
660
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000661FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
662 const FunctionDecl *FD){
663 assert(FD && "Specialization is 0");
664 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +0000665 = ClassScopeSpecializationPattern.find(FD);
666 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000667 return 0;
668
669 return Pos->second;
670}
671
672void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
673 FunctionDecl *Pattern) {
674 assert(FD && "Specialization is 0");
675 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +0000676 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000677}
678
John McCalle61f2ba2009-11-18 02:36:19 +0000679NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000680ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000681 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000682 = InstantiatedFromUsingDecl.find(UUD);
683 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000684 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000685
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000686 return Pos->second;
687}
688
689void
John McCallb96ec562009-12-04 22:46:56 +0000690ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
691 assert((isa<UsingDecl>(Pattern) ||
692 isa<UnresolvedUsingValueDecl>(Pattern) ||
693 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
694 "pattern decl is not a using decl");
695 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
696 InstantiatedFromUsingDecl[Inst] = Pattern;
697}
698
699UsingShadowDecl *
700ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
701 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
702 = InstantiatedFromUsingShadowDecl.find(Inst);
703 if (Pos == InstantiatedFromUsingShadowDecl.end())
704 return 0;
705
706 return Pos->second;
707}
708
709void
710ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
711 UsingShadowDecl *Pattern) {
712 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
713 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000714}
715
Anders Carlsson5da84842009-09-01 04:26:58 +0000716FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
717 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
718 = InstantiatedFromUnnamedFieldDecl.find(Field);
719 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
720 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000721
Anders Carlsson5da84842009-09-01 04:26:58 +0000722 return Pos->second;
723}
724
725void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
726 FieldDecl *Tmpl) {
727 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
728 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
729 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
730 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000731
Anders Carlsson5da84842009-09-01 04:26:58 +0000732 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
733}
734
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000735bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
736 const FieldDecl *LastFD) const {
737 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000738 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000739}
740
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000741bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
742 const FieldDecl *LastFD) const {
743 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000744 FD->getBitWidthValue(*this) == 0 &&
745 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000746}
747
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000748bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
749 const FieldDecl *LastFD) const {
750 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000751 FD->getBitWidthValue(*this) &&
752 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000753}
754
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000755bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000756 const FieldDecl *LastFD) const {
757 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000758 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000759}
760
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000761bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000762 const FieldDecl *LastFD) const {
763 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000764 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000765}
766
Douglas Gregor832940b2010-03-02 23:58:15 +0000767ASTContext::overridden_cxx_method_iterator
768ASTContext::overridden_methods_begin(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.begin();
775}
776
777ASTContext::overridden_cxx_method_iterator
778ASTContext::overridden_methods_end(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.end();
785}
786
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000787unsigned
788ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
789 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
790 = OverriddenMethods.find(Method);
791 if (Pos == OverriddenMethods.end())
792 return 0;
793
794 return Pos->second.size();
795}
796
Douglas Gregor832940b2010-03-02 23:58:15 +0000797void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
798 const CXXMethodDecl *Overridden) {
799 OverriddenMethods[Method].push_back(Overridden);
800}
801
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000802void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
803 assert(!Import->NextLocalImport && "Import declaration already in the chain");
804 assert(!Import->isFromASTFile() && "Non-local import declaration");
805 if (!FirstLocalImport) {
806 FirstLocalImport = Import;
807 LastLocalImport = Import;
808 return;
809 }
810
811 LastLocalImport->NextLocalImport = Import;
812 LastLocalImport = Import;
813}
814
Chris Lattner53cfe802007-07-18 17:52:12 +0000815//===----------------------------------------------------------------------===//
816// Type Sizing and Analysis
817//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000818
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000819/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
820/// scalar floating point type.
821const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000822 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000823 assert(BT && "Not a floating point type!");
824 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +0000825 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000826 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +0000827 case BuiltinType::Float: return Target->getFloatFormat();
828 case BuiltinType::Double: return Target->getDoubleFormat();
829 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000830 }
831}
832
Ken Dyck160146e2010-01-27 17:10:57 +0000833/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000834/// specified decl. Note that bitfields do not have a valid alignment, so
835/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000836/// If @p RefAsPointee, references are treated like their underlying type
837/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000838CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000839 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +0000840
John McCall94268702010-10-08 18:24:19 +0000841 bool UseAlignAttrOnly = false;
842 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
843 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000844
John McCall94268702010-10-08 18:24:19 +0000845 // __attribute__((aligned)) can increase or decrease alignment
846 // *except* on a struct or struct member, where it only increases
847 // alignment unless 'packed' is also specified.
848 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +0000849 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +0000850 // ignore that possibility; Sema should diagnose it.
851 if (isa<FieldDecl>(D)) {
852 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
853 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
854 } else {
855 UseAlignAttrOnly = true;
856 }
857 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +0000858 else if (isa<FieldDecl>(D))
859 UseAlignAttrOnly =
860 D->hasAttr<PackedAttr>() ||
861 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +0000862
John McCall4e819612011-01-20 07:57:12 +0000863 // If we're using the align attribute only, just ignore everything
864 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +0000865 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +0000866 // do nothing
867
John McCall94268702010-10-08 18:24:19 +0000868 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000869 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000870 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000871 if (RefAsPointee)
872 T = RT->getPointeeType();
873 else
874 T = getPointerType(RT->getPointeeType());
875 }
876 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +0000877 // Adjust alignments of declarations with array type by the
878 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +0000879 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +0000880 const ArrayType *arrayType;
881 if (MinWidth && (arrayType = getAsArrayType(T))) {
882 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000883 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +0000884 else if (isa<ConstantArrayType>(arrayType) &&
885 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000886 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +0000887
John McCall33ddac02011-01-19 10:06:00 +0000888 // Walk through any array types while we're at it.
889 T = getBaseElementType(arrayType);
890 }
Chad Rosier99ee7822011-07-26 07:03:04 +0000891 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +0000892 }
John McCall4e819612011-01-20 07:57:12 +0000893
894 // Fields can be subject to extra alignment constraints, like if
895 // the field is packed, the struct is packed, or the struct has a
896 // a max-field-alignment constraint (#pragma pack). So calculate
897 // the actual alignment of the field within the struct, and then
898 // (as we're expected to) constrain that by the alignment of the type.
899 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
900 // So calculate the alignment of the field.
901 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
902
903 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +0000904 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +0000905
906 // Use the GCD of that and the offset within the record.
907 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
908 if (offset > 0) {
909 // Alignment is always a power of 2, so the GCD will be a power of 2,
910 // which means we get to do this crazy thing instead of Euclid's.
911 uint64_t lowBitOfOffset = offset & (~offset + 1);
912 if (lowBitOfOffset < fieldAlign)
913 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
914 }
915
916 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +0000917 }
Chris Lattner68061312009-01-24 21:53:27 +0000918 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000919
Ken Dyckcc56c542011-01-15 18:38:59 +0000920 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +0000921}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000922
John McCall87fe5d52010-05-20 01:18:31 +0000923std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000924ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000925 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +0000926 return std::make_pair(toCharUnitsFromBits(Info.first),
927 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +0000928}
929
930std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000931ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000932 return getTypeInfoInChars(T.getTypePtr());
933}
934
Daniel Dunbarc6475872012-03-09 04:12:54 +0000935std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
936 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
937 if (it != MemoizedTypeInfo.end())
938 return it->second;
939
940 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
941 MemoizedTypeInfo.insert(std::make_pair(T, Info));
942 return Info;
943}
944
945/// getTypeInfoImpl - Return the size of the specified type, in bits. This
946/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000947///
948/// FIXME: Pointers into different addr spaces could have different sizes and
949/// alignment requirements: getPointerInfo should take an AddrSpace, this
950/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000951std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +0000952ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000953 uint64_t Width=0;
954 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000955 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000956#define TYPE(Class, Base)
957#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000958#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000959#define DEPENDENT_TYPE(Class, Base) case Type::Class:
960#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +0000961 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000962
Chris Lattner355332d2007-07-13 22:27:08 +0000963 case Type::FunctionNoProto:
964 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000965 // GCC extension: alignof(function) = 32 bits
966 Width = 0;
967 Align = 32;
968 break;
969
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000970 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000971 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000972 Width = 0;
973 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
974 break;
975
Steve Naroff5c131802007-08-30 01:06:46 +0000976 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000977 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000978
Chris Lattner37e05872008-03-05 18:54:05 +0000979 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +0000980 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +0000981 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
982 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +0000983 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000984 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +0000985 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000986 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000987 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000988 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000989 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000990 const VectorType *VT = cast<VectorType>(T);
991 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
992 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000993 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000994 // If the alignment is not a power of 2, round up to the next power of 2.
995 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000996 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000997 Align = llvm::NextPowerOf2(Align);
998 Width = llvm::RoundUpToAlignment(Width, Align);
999 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001000 break;
1001 }
Chris Lattner647fb222007-07-18 18:26:58 +00001002
Chris Lattner7570e9c2008-03-08 08:52:55 +00001003 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001004 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001005 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001006 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001007 // GCC extension: alignof(void) = 8 bits.
1008 Width = 0;
1009 Align = 8;
1010 break;
1011
Chris Lattner6a4f7452007-12-19 19:23:28 +00001012 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001013 Width = Target->getBoolWidth();
1014 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001015 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001016 case BuiltinType::Char_S:
1017 case BuiltinType::Char_U:
1018 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001019 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001020 Width = Target->getCharWidth();
1021 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001022 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001023 case BuiltinType::WChar_S:
1024 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001025 Width = Target->getWCharWidth();
1026 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001027 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001028 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001029 Width = Target->getChar16Width();
1030 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001031 break;
1032 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001033 Width = Target->getChar32Width();
1034 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001035 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001036 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001037 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001038 Width = Target->getShortWidth();
1039 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001040 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001041 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001042 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001043 Width = Target->getIntWidth();
1044 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001045 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001046 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001047 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001048 Width = Target->getLongWidth();
1049 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001050 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001051 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001052 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001053 Width = Target->getLongLongWidth();
1054 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001055 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001056 case BuiltinType::Int128:
1057 case BuiltinType::UInt128:
1058 Width = 128;
1059 Align = 128; // int128_t is 128-bit aligned on all targets.
1060 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001061 case BuiltinType::Half:
1062 Width = Target->getHalfWidth();
1063 Align = Target->getHalfAlign();
1064 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001065 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001066 Width = Target->getFloatWidth();
1067 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001068 break;
1069 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001070 Width = Target->getDoubleWidth();
1071 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001072 break;
1073 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001074 Width = Target->getLongDoubleWidth();
1075 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001076 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001077 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001078 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1079 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001080 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001081 case BuiltinType::ObjCId:
1082 case BuiltinType::ObjCClass:
1083 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001084 Width = Target->getPointerWidth(0);
1085 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001086 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001087 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001088 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001089 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001090 Width = Target->getPointerWidth(0);
1091 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001092 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001093 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001094 unsigned AS = getTargetAddressSpace(
1095 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001096 Width = Target->getPointerWidth(AS);
1097 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001098 break;
1099 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001100 case Type::LValueReference:
1101 case Type::RValueReference: {
1102 // alignof and sizeof should never enter this code path here, so we go
1103 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001104 unsigned AS = getTargetAddressSpace(
1105 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001106 Width = Target->getPointerWidth(AS);
1107 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001108 break;
1109 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001110 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001111 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001112 Width = Target->getPointerWidth(AS);
1113 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001114 break;
1115 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001116 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001117 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001118 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +00001119 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +00001120 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001121 Align = PtrDiffInfo.second;
1122 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001123 }
Chris Lattner647fb222007-07-18 18:26:58 +00001124 case Type::Complex: {
1125 // Complex types have the same alignment as their elements, but twice the
1126 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001127 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001128 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001129 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001130 Align = EltInfo.second;
1131 break;
1132 }
John McCall8b07ec22010-05-15 11:32:37 +00001133 case Type::ObjCObject:
1134 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001135 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001136 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001137 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001138 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001139 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001140 break;
1141 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001142 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001143 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001144 const TagType *TT = cast<TagType>(T);
1145
1146 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001147 Width = 8;
1148 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001149 break;
1150 }
Mike Stump11289f42009-09-09 15:08:12 +00001151
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001152 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001153 return getTypeInfo(ET->getDecl()->getIntegerType());
1154
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001155 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001156 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001157 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001158 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001159 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001160 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001161
Chris Lattner63d2b362009-10-22 05:17:15 +00001162 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001163 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1164 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001165
Richard Smith30482bc2011-02-20 03:19:35 +00001166 case Type::Auto: {
1167 const AutoType *A = cast<AutoType>(T);
1168 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001169 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001170 }
1171
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001172 case Type::Paren:
1173 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1174
Douglas Gregoref462e62009-04-30 17:32:17 +00001175 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001176 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001177 std::pair<uint64_t, unsigned> Info
1178 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001179 // If the typedef has an aligned attribute on it, it overrides any computed
1180 // alignment we have. This violates the GCC documentation (which says that
1181 // attribute(aligned) can only round up) but matches its implementation.
1182 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1183 Align = AttrAlign;
1184 else
1185 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001186 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001187 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001188 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001189
1190 case Type::TypeOfExpr:
1191 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1192 .getTypePtr());
1193
1194 case Type::TypeOf:
1195 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1196
Anders Carlsson81df7b82009-06-24 19:06:50 +00001197 case Type::Decltype:
1198 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1199 .getTypePtr());
1200
Alexis Hunte852b102011-05-24 22:41:36 +00001201 case Type::UnaryTransform:
1202 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1203
Abramo Bagnara6150c882010-05-11 21:36:43 +00001204 case Type::Elaborated:
1205 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001206
John McCall81904512011-01-06 01:58:22 +00001207 case Type::Attributed:
1208 return getTypeInfo(
1209 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1210
Richard Smith3f1b5d02011-05-05 21:57:07 +00001211 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001212 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001213 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001214 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1215 // A type alias template specialization may refer to a typedef with the
1216 // aligned attribute on it.
1217 if (TST->isTypeAlias())
1218 return getTypeInfo(TST->getAliasedType().getTypePtr());
1219 else
1220 return getTypeInfo(getCanonicalType(T));
1221 }
1222
Eli Friedman0dfb8892011-10-06 23:00:33 +00001223 case Type::Atomic: {
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001224 std::pair<uint64_t, unsigned> Info
1225 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1226 Width = Info.first;
1227 Align = Info.second;
1228 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1229 llvm::isPowerOf2_64(Width)) {
1230 // We can potentially perform lock-free atomic operations for this
1231 // type; promote the alignment appropriately.
1232 // FIXME: We could potentially promote the width here as well...
1233 // is that worthwhile? (Non-struct atomic types generally have
1234 // power-of-two size anyway, but structs might not. Requires a bit
1235 // of implementation work to make sure we zero out the extra bits.)
1236 Align = static_cast<unsigned>(Width);
1237 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001238 }
1239
Douglas Gregoref462e62009-04-30 17:32:17 +00001240 }
Mike Stump11289f42009-09-09 15:08:12 +00001241
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001242 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001243 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001244}
1245
Ken Dyckcc56c542011-01-15 18:38:59 +00001246/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1247CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1248 return CharUnits::fromQuantity(BitSize / getCharWidth());
1249}
1250
Ken Dyckb0fcc592011-02-11 01:54:29 +00001251/// toBits - Convert a size in characters to a size in characters.
1252int64_t ASTContext::toBits(CharUnits CharSize) const {
1253 return CharSize.getQuantity() * getCharWidth();
1254}
1255
Ken Dyck8c89d592009-12-22 14:23:30 +00001256/// getTypeSizeInChars - Return the size of the specified type, in characters.
1257/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001258CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001259 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001260}
Jay Foad39c79802011-01-12 09:06:06 +00001261CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001262 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001263}
1264
Ken Dycka6046ab2010-01-26 17:25:18 +00001265/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001266/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001267CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001268 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001269}
Jay Foad39c79802011-01-12 09:06:06 +00001270CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001271 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001272}
1273
Chris Lattnera3402cd2009-01-27 18:08:34 +00001274/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1275/// type for the current target in bits. This can be different than the ABI
1276/// alignment in cases where it is beneficial for performance to overalign
1277/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001278unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001279 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001280
1281 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001282 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001283 T = CT->getElementType().getTypePtr();
1284 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001285 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1286 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001287 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1288
Chris Lattnera3402cd2009-01-27 18:08:34 +00001289 return ABIAlign;
1290}
1291
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001292/// DeepCollectObjCIvars -
1293/// This routine first collects all declared, but not synthesized, ivars in
1294/// super class and then collects all ivars, including those synthesized for
1295/// current class. This routine is used for implementation of current class
1296/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001297///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001298void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1299 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001300 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001301 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1302 DeepCollectObjCIvars(SuperClass, false, Ivars);
1303 if (!leafClass) {
1304 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1305 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001306 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001307 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001308 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001309 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001310 Iv= Iv->getNextIvar())
1311 Ivars.push_back(Iv);
1312 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001313}
1314
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001315/// CollectInheritedProtocols - Collect all protocols in current class and
1316/// those inherited by it.
1317void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001318 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001319 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001320 // We can use protocol_iterator here instead of
1321 // all_referenced_protocol_iterator since we are walking all categories.
1322 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1323 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001324 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001325 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001326 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001327 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001328 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001329 CollectInheritedProtocols(*P, Protocols);
1330 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001331 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001332
1333 // Categories of this Interface.
1334 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1335 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1336 CollectInheritedProtocols(CDeclChain, Protocols);
1337 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1338 while (SD) {
1339 CollectInheritedProtocols(SD, Protocols);
1340 SD = SD->getSuperClass();
1341 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001342 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001343 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001344 PE = OC->protocol_end(); P != PE; ++P) {
1345 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001346 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001347 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1348 PE = Proto->protocol_end(); P != PE; ++P)
1349 CollectInheritedProtocols(*P, Protocols);
1350 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001351 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001352 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1353 PE = OP->protocol_end(); P != PE; ++P) {
1354 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001355 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001356 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1357 PE = Proto->protocol_end(); P != PE; ++P)
1358 CollectInheritedProtocols(*P, Protocols);
1359 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001360 }
1361}
1362
Jay Foad39c79802011-01-12 09:06:06 +00001363unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001364 unsigned count = 0;
1365 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001366 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1367 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001368 count += CDecl->ivar_size();
1369
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001370 // Count ivar defined in this class's implementation. This
1371 // includes synthesized ivars.
1372 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001373 count += ImplDecl->ivar_size();
1374
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001375 return count;
1376}
1377
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001378bool ASTContext::isSentinelNullExpr(const Expr *E) {
1379 if (!E)
1380 return false;
1381
1382 // nullptr_t is always treated as null.
1383 if (E->getType()->isNullPtrType()) return true;
1384
1385 if (E->getType()->isAnyPointerType() &&
1386 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1387 Expr::NPC_ValueDependentIsNull))
1388 return true;
1389
1390 // Unfortunately, __null has type 'int'.
1391 if (isa<GNUNullExpr>(E)) return true;
1392
1393 return false;
1394}
1395
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001396/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1397ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1398 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1399 I = ObjCImpls.find(D);
1400 if (I != ObjCImpls.end())
1401 return cast<ObjCImplementationDecl>(I->second);
1402 return 0;
1403}
1404/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1405ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1406 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1407 I = ObjCImpls.find(D);
1408 if (I != ObjCImpls.end())
1409 return cast<ObjCCategoryImplDecl>(I->second);
1410 return 0;
1411}
1412
1413/// \brief Set the implementation of ObjCInterfaceDecl.
1414void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1415 ObjCImplementationDecl *ImplD) {
1416 assert(IFaceD && ImplD && "Passed null params");
1417 ObjCImpls[IFaceD] = ImplD;
1418}
1419/// \brief Set the implementation of ObjCCategoryDecl.
1420void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1421 ObjCCategoryImplDecl *ImplD) {
1422 assert(CatD && ImplD && "Passed null params");
1423 ObjCImpls[CatD] = ImplD;
1424}
1425
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001426ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1427 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1428 return ID;
1429 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1430 return CD->getClassInterface();
1431 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1432 return IMD->getClassInterface();
1433
1434 return 0;
1435}
1436
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001437/// \brief Get the copy initialization expression of VarDecl,or NULL if
1438/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001439Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001440 assert(VD && "Passed null params");
1441 assert(VD->hasAttr<BlocksAttr>() &&
1442 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001443 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001444 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001445 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1446}
1447
1448/// \brief Set the copy inialization expression of a block var decl.
1449void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1450 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001451 assert(VD->hasAttr<BlocksAttr>() &&
1452 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001453 BlockVarCopyInits[VD] = Init;
1454}
1455
John McCallbcd03502009-12-07 02:54:59 +00001456TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001457 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001458 if (!DataSize)
1459 DataSize = TypeLoc::getFullDataSizeForType(T);
1460 else
1461 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001462 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001463
John McCallbcd03502009-12-07 02:54:59 +00001464 TypeSourceInfo *TInfo =
1465 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1466 new (TInfo) TypeSourceInfo(T);
1467 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001468}
1469
John McCallbcd03502009-12-07 02:54:59 +00001470TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001471 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001472 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001473 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001474 return DI;
1475}
1476
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001477const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001478ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001479 return getObjCLayout(D, 0);
1480}
1481
1482const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001483ASTContext::getASTObjCImplementationLayout(
1484 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001485 return getObjCLayout(D->getClassInterface(), D);
1486}
1487
Chris Lattner983a8bb2007-07-13 22:13:22 +00001488//===----------------------------------------------------------------------===//
1489// Type creation/memoization methods
1490//===----------------------------------------------------------------------===//
1491
Jay Foad39c79802011-01-12 09:06:06 +00001492QualType
John McCall33ddac02011-01-19 10:06:00 +00001493ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1494 unsigned fastQuals = quals.getFastQualifiers();
1495 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001496
1497 // Check if we've already instantiated this type.
1498 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001499 ExtQuals::Profile(ID, baseType, quals);
1500 void *insertPos = 0;
1501 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1502 assert(eq->getQualifiers() == quals);
1503 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001504 }
1505
John McCall33ddac02011-01-19 10:06:00 +00001506 // If the base type is not canonical, make the appropriate canonical type.
1507 QualType canon;
1508 if (!baseType->isCanonicalUnqualified()) {
1509 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00001510 canonSplit.Quals.addConsistentQualifiers(quals);
1511 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001512
1513 // Re-find the insert position.
1514 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1515 }
1516
1517 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1518 ExtQualNodes.InsertNode(eq, insertPos);
1519 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001520}
1521
Jay Foad39c79802011-01-12 09:06:06 +00001522QualType
1523ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001524 QualType CanT = getCanonicalType(T);
1525 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001526 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001527
John McCall8ccfcb52009-09-24 19:53:00 +00001528 // If we are composing extended qualifiers together, merge together
1529 // into one ExtQuals node.
1530 QualifierCollector Quals;
1531 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001532
John McCall8ccfcb52009-09-24 19:53:00 +00001533 // If this type already has an address space specified, it cannot get
1534 // another one.
1535 assert(!Quals.hasAddressSpace() &&
1536 "Type cannot be in multiple addr spaces!");
1537 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001538
John McCall8ccfcb52009-09-24 19:53:00 +00001539 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001540}
1541
Chris Lattnerd60183d2009-02-18 22:53:11 +00001542QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001543 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001544 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001545 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001546 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001547
John McCall53fa7142010-12-24 02:08:15 +00001548 if (const PointerType *ptr = T->getAs<PointerType>()) {
1549 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001550 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001551 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1552 return getPointerType(ResultType);
1553 }
1554 }
Mike Stump11289f42009-09-09 15:08:12 +00001555
John McCall8ccfcb52009-09-24 19:53:00 +00001556 // If we are composing extended qualifiers together, merge together
1557 // into one ExtQuals node.
1558 QualifierCollector Quals;
1559 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001560
John McCall8ccfcb52009-09-24 19:53:00 +00001561 // If this type already has an ObjCGC specified, it cannot get
1562 // another one.
1563 assert(!Quals.hasObjCGCAttr() &&
1564 "Type cannot have multiple ObjCGCs!");
1565 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001566
John McCall8ccfcb52009-09-24 19:53:00 +00001567 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001568}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001569
John McCall4f5019e2010-12-19 02:44:49 +00001570const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1571 FunctionType::ExtInfo Info) {
1572 if (T->getExtInfo() == Info)
1573 return T;
1574
1575 QualType Result;
1576 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1577 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1578 } else {
1579 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1580 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1581 EPI.ExtInfo = Info;
1582 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1583 FPT->getNumArgs(), EPI);
1584 }
1585
1586 return cast<FunctionType>(Result.getTypePtr());
1587}
1588
Chris Lattnerc6395932007-06-22 20:56:16 +00001589/// getComplexType - Return the uniqued reference to the type for a complex
1590/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001591QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001592 // Unique pointers, to guarantee there is only one pointer of a particular
1593 // structure.
1594 llvm::FoldingSetNodeID ID;
1595 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001596
Chris Lattnerc6395932007-06-22 20:56:16 +00001597 void *InsertPos = 0;
1598 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1599 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001600
Chris Lattnerc6395932007-06-22 20:56:16 +00001601 // If the pointee type isn't canonical, this won't be a canonical type either,
1602 // so fill in the canonical type field.
1603 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001604 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001605 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001606
Chris Lattnerc6395932007-06-22 20:56:16 +00001607 // Get the new insert position for the node we care about.
1608 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001609 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001610 }
John McCall90d1c2d2009-09-24 23:30:46 +00001611 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001612 Types.push_back(New);
1613 ComplexTypes.InsertNode(New, InsertPos);
1614 return QualType(New, 0);
1615}
1616
Chris Lattner970e54e2006-11-12 00:37:36 +00001617/// getPointerType - Return the uniqued reference to the type for a pointer to
1618/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001619QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001620 // Unique pointers, to guarantee there is only one pointer of a particular
1621 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001622 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001623 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001624
Chris Lattner67521df2007-01-27 01:29:36 +00001625 void *InsertPos = 0;
1626 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001627 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001628
Chris Lattner7ccecb92006-11-12 08:50:50 +00001629 // If the pointee type isn't canonical, this won't be a canonical type either,
1630 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001631 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001632 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001633 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001634
Chris Lattner67521df2007-01-27 01:29:36 +00001635 // Get the new insert position for the node we care about.
1636 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001637 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001638 }
John McCall90d1c2d2009-09-24 23:30:46 +00001639 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001640 Types.push_back(New);
1641 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001642 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001643}
1644
Mike Stump11289f42009-09-09 15:08:12 +00001645/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001646/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001647QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001648 assert(T->isFunctionType() && "block of function types only");
1649 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001650 // structure.
1651 llvm::FoldingSetNodeID ID;
1652 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001653
Steve Naroffec33ed92008-08-27 16:04:49 +00001654 void *InsertPos = 0;
1655 if (BlockPointerType *PT =
1656 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1657 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001658
1659 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001660 // type either so fill in the canonical type field.
1661 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001662 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001663 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001664
Steve Naroffec33ed92008-08-27 16:04:49 +00001665 // Get the new insert position for the node we care about.
1666 BlockPointerType *NewIP =
1667 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001668 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001669 }
John McCall90d1c2d2009-09-24 23:30:46 +00001670 BlockPointerType *New
1671 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001672 Types.push_back(New);
1673 BlockPointerTypes.InsertNode(New, InsertPos);
1674 return QualType(New, 0);
1675}
1676
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001677/// getLValueReferenceType - Return the uniqued reference to the type for an
1678/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001679QualType
1680ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00001681 assert(getCanonicalType(T) != OverloadTy &&
1682 "Unresolved overloaded function type");
1683
Bill Wendling3708c182007-05-27 10:15:43 +00001684 // Unique pointers, to guarantee there is only one pointer of a particular
1685 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001686 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001687 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001688
1689 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001690 if (LValueReferenceType *RT =
1691 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001692 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001693
John McCallfc93cf92009-10-22 22:37:11 +00001694 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1695
Bill Wendling3708c182007-05-27 10:15:43 +00001696 // If the referencee type isn't canonical, this won't be a canonical type
1697 // either, so fill in the canonical type field.
1698 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001699 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1700 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1701 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001702
Bill Wendling3708c182007-05-27 10:15:43 +00001703 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001704 LValueReferenceType *NewIP =
1705 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001706 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001707 }
1708
John McCall90d1c2d2009-09-24 23:30:46 +00001709 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001710 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1711 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001712 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001713 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001714
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001715 return QualType(New, 0);
1716}
1717
1718/// getRValueReferenceType - Return the uniqued reference to the type for an
1719/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001720QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001721 // Unique pointers, to guarantee there is only one pointer of a particular
1722 // structure.
1723 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001724 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001725
1726 void *InsertPos = 0;
1727 if (RValueReferenceType *RT =
1728 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1729 return QualType(RT, 0);
1730
John McCallfc93cf92009-10-22 22:37:11 +00001731 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1732
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001733 // If the referencee type isn't canonical, this won't be a canonical type
1734 // either, so fill in the canonical type field.
1735 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001736 if (InnerRef || !T.isCanonical()) {
1737 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1738 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001739
1740 // Get the new insert position for the node we care about.
1741 RValueReferenceType *NewIP =
1742 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001743 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001744 }
1745
John McCall90d1c2d2009-09-24 23:30:46 +00001746 RValueReferenceType *New
1747 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001748 Types.push_back(New);
1749 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001750 return QualType(New, 0);
1751}
1752
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001753/// getMemberPointerType - Return the uniqued reference to the type for a
1754/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001755QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001756 // Unique pointers, to guarantee there is only one pointer of a particular
1757 // structure.
1758 llvm::FoldingSetNodeID ID;
1759 MemberPointerType::Profile(ID, T, Cls);
1760
1761 void *InsertPos = 0;
1762 if (MemberPointerType *PT =
1763 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1764 return QualType(PT, 0);
1765
1766 // If the pointee or class type isn't canonical, this won't be a canonical
1767 // type either, so fill in the canonical type field.
1768 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001769 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001770 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1771
1772 // Get the new insert position for the node we care about.
1773 MemberPointerType *NewIP =
1774 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001775 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001776 }
John McCall90d1c2d2009-09-24 23:30:46 +00001777 MemberPointerType *New
1778 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001779 Types.push_back(New);
1780 MemberPointerTypes.InsertNode(New, InsertPos);
1781 return QualType(New, 0);
1782}
1783
Mike Stump11289f42009-09-09 15:08:12 +00001784/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001785/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001786QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001787 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001788 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001789 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001790 assert((EltTy->isDependentType() ||
1791 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001792 "Constant array of VLAs is illegal!");
1793
Chris Lattnere2df3f92009-05-13 04:12:56 +00001794 // Convert the array size into a canonical width matching the pointer size for
1795 // the target.
1796 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001797 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001798 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00001799
Chris Lattner23b7eb62007-06-15 23:05:46 +00001800 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001801 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001802
Chris Lattner36f8e652007-01-27 08:31:04 +00001803 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001804 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001805 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001806 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001807
John McCall33ddac02011-01-19 10:06:00 +00001808 // If the element type isn't canonical or has qualifiers, this won't
1809 // be a canonical type either, so fill in the canonical type field.
1810 QualType Canon;
1811 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1812 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00001813 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001814 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00001815 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001816
Chris Lattner36f8e652007-01-27 08:31:04 +00001817 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001818 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001819 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001820 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001821 }
Mike Stump11289f42009-09-09 15:08:12 +00001822
John McCall90d1c2d2009-09-24 23:30:46 +00001823 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001824 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001825 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001826 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001827 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001828}
1829
John McCall06549462011-01-18 08:40:38 +00001830/// getVariableArrayDecayedType - Turns the given type, which may be
1831/// variably-modified, into the corresponding type with all the known
1832/// sizes replaced with [*].
1833QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1834 // Vastly most common case.
1835 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001836
John McCall06549462011-01-18 08:40:38 +00001837 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001838
John McCall06549462011-01-18 08:40:38 +00001839 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00001840 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00001841 switch (ty->getTypeClass()) {
1842#define TYPE(Class, Base)
1843#define ABSTRACT_TYPE(Class, Base)
1844#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1845#include "clang/AST/TypeNodes.def"
1846 llvm_unreachable("didn't desugar past all non-canonical types?");
1847
1848 // These types should never be variably-modified.
1849 case Type::Builtin:
1850 case Type::Complex:
1851 case Type::Vector:
1852 case Type::ExtVector:
1853 case Type::DependentSizedExtVector:
1854 case Type::ObjCObject:
1855 case Type::ObjCInterface:
1856 case Type::ObjCObjectPointer:
1857 case Type::Record:
1858 case Type::Enum:
1859 case Type::UnresolvedUsing:
1860 case Type::TypeOfExpr:
1861 case Type::TypeOf:
1862 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00001863 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00001864 case Type::DependentName:
1865 case Type::InjectedClassName:
1866 case Type::TemplateSpecialization:
1867 case Type::DependentTemplateSpecialization:
1868 case Type::TemplateTypeParm:
1869 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00001870 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00001871 case Type::PackExpansion:
1872 llvm_unreachable("type should never be variably-modified");
1873
1874 // These types can be variably-modified but should never need to
1875 // further decay.
1876 case Type::FunctionNoProto:
1877 case Type::FunctionProto:
1878 case Type::BlockPointer:
1879 case Type::MemberPointer:
1880 return type;
1881
1882 // These types can be variably-modified. All these modifications
1883 // preserve structure except as noted by comments.
1884 // TODO: if we ever care about optimizing VLAs, there are no-op
1885 // optimizations available here.
1886 case Type::Pointer:
1887 result = getPointerType(getVariableArrayDecayedType(
1888 cast<PointerType>(ty)->getPointeeType()));
1889 break;
1890
1891 case Type::LValueReference: {
1892 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1893 result = getLValueReferenceType(
1894 getVariableArrayDecayedType(lv->getPointeeType()),
1895 lv->isSpelledAsLValue());
1896 break;
1897 }
1898
1899 case Type::RValueReference: {
1900 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1901 result = getRValueReferenceType(
1902 getVariableArrayDecayedType(lv->getPointeeType()));
1903 break;
1904 }
1905
Eli Friedman0dfb8892011-10-06 23:00:33 +00001906 case Type::Atomic: {
1907 const AtomicType *at = cast<AtomicType>(ty);
1908 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1909 break;
1910 }
1911
John McCall06549462011-01-18 08:40:38 +00001912 case Type::ConstantArray: {
1913 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1914 result = getConstantArrayType(
1915 getVariableArrayDecayedType(cat->getElementType()),
1916 cat->getSize(),
1917 cat->getSizeModifier(),
1918 cat->getIndexTypeCVRQualifiers());
1919 break;
1920 }
1921
1922 case Type::DependentSizedArray: {
1923 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1924 result = getDependentSizedArrayType(
1925 getVariableArrayDecayedType(dat->getElementType()),
1926 dat->getSizeExpr(),
1927 dat->getSizeModifier(),
1928 dat->getIndexTypeCVRQualifiers(),
1929 dat->getBracketsRange());
1930 break;
1931 }
1932
1933 // Turn incomplete types into [*] types.
1934 case Type::IncompleteArray: {
1935 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1936 result = getVariableArrayType(
1937 getVariableArrayDecayedType(iat->getElementType()),
1938 /*size*/ 0,
1939 ArrayType::Normal,
1940 iat->getIndexTypeCVRQualifiers(),
1941 SourceRange());
1942 break;
1943 }
1944
1945 // Turn VLA types into [*] types.
1946 case Type::VariableArray: {
1947 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1948 result = getVariableArrayType(
1949 getVariableArrayDecayedType(vat->getElementType()),
1950 /*size*/ 0,
1951 ArrayType::Star,
1952 vat->getIndexTypeCVRQualifiers(),
1953 vat->getBracketsRange());
1954 break;
1955 }
1956 }
1957
1958 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00001959 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00001960}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001961
Steve Naroffcadebd02007-08-30 18:14:25 +00001962/// getVariableArrayType - Returns a non-unique reference to the type for a
1963/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001964QualType ASTContext::getVariableArrayType(QualType EltTy,
1965 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001966 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001967 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001968 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001969 // Since we don't unique expressions, it isn't possible to unique VLA's
1970 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00001971 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001972
John McCall33ddac02011-01-19 10:06:00 +00001973 // Be sure to pull qualifiers off the element type.
1974 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1975 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00001976 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001977 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00001978 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001979 }
1980
John McCall90d1c2d2009-09-24 23:30:46 +00001981 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001982 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001983
1984 VariableArrayTypes.push_back(New);
1985 Types.push_back(New);
1986 return QualType(New, 0);
1987}
1988
Douglas Gregor4619e432008-12-05 23:32:09 +00001989/// getDependentSizedArrayType - Returns a non-unique reference to
1990/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001991/// type.
John McCall33ddac02011-01-19 10:06:00 +00001992QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1993 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00001994 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001995 unsigned elementTypeQuals,
1996 SourceRange brackets) const {
1997 assert((!numElements || numElements->isTypeDependent() ||
1998 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001999 "Size must be type- or value-dependent!");
2000
John McCall33ddac02011-01-19 10:06:00 +00002001 // Dependently-sized array types that do not have a specified number
2002 // of elements will have their sizes deduced from a dependent
2003 // initializer. We do no canonicalization here at all, which is okay
2004 // because they can't be used in most locations.
2005 if (!numElements) {
2006 DependentSizedArrayType *newType
2007 = new (*this, TypeAlignment)
2008 DependentSizedArrayType(*this, elementType, QualType(),
2009 numElements, ASM, elementTypeQuals,
2010 brackets);
2011 Types.push_back(newType);
2012 return QualType(newType, 0);
2013 }
2014
2015 // Otherwise, we actually build a new type every time, but we
2016 // also build a canonical type.
2017
2018 SplitQualType canonElementType = getCanonicalType(elementType).split();
2019
2020 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002021 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002022 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002023 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002024 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002025
John McCall33ddac02011-01-19 10:06:00 +00002026 // Look for an existing type with these properties.
2027 DependentSizedArrayType *canonTy =
2028 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002029
John McCall33ddac02011-01-19 10:06:00 +00002030 // If we don't have one, build one.
2031 if (!canonTy) {
2032 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002033 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002034 QualType(), numElements, ASM, elementTypeQuals,
2035 brackets);
2036 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2037 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002038 }
2039
John McCall33ddac02011-01-19 10:06:00 +00002040 // Apply qualifiers from the element type to the array.
2041 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002042 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002043
John McCall33ddac02011-01-19 10:06:00 +00002044 // If we didn't need extra canonicalization for the element type,
2045 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002046 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002047 return canon;
2048
2049 // Otherwise, we need to build a type which follows the spelling
2050 // of the element type.
2051 DependentSizedArrayType *sugaredType
2052 = new (*this, TypeAlignment)
2053 DependentSizedArrayType(*this, elementType, canon, numElements,
2054 ASM, elementTypeQuals, brackets);
2055 Types.push_back(sugaredType);
2056 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002057}
2058
John McCall33ddac02011-01-19 10:06:00 +00002059QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002060 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002061 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002062 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002063 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002064
John McCall33ddac02011-01-19 10:06:00 +00002065 void *insertPos = 0;
2066 if (IncompleteArrayType *iat =
2067 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2068 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002069
2070 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002071 // either, so fill in the canonical type field. We also have to pull
2072 // qualifiers off the element type.
2073 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002074
John McCall33ddac02011-01-19 10:06:00 +00002075 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2076 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002077 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002078 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002079 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002080
2081 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002082 IncompleteArrayType *existing =
2083 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2084 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002085 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002086
John McCall33ddac02011-01-19 10:06:00 +00002087 IncompleteArrayType *newType = new (*this, TypeAlignment)
2088 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002089
John McCall33ddac02011-01-19 10:06:00 +00002090 IncompleteArrayTypes.InsertNode(newType, insertPos);
2091 Types.push_back(newType);
2092 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002093}
2094
Steve Naroff91fcddb2007-07-18 18:00:27 +00002095/// getVectorType - Return the unique reference to a vector type of
2096/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002097QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002098 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002099 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002100
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002101 // Check if we've already instantiated a vector of this type.
2102 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002103 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002104
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002105 void *InsertPos = 0;
2106 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2107 return QualType(VTP, 0);
2108
2109 // If the element type isn't canonical, this won't be a canonical type either,
2110 // so fill in the canonical type field.
2111 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002112 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002113 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002114
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002115 // Get the new insert position for the node we care about.
2116 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002117 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002118 }
John McCall90d1c2d2009-09-24 23:30:46 +00002119 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002120 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002121 VectorTypes.InsertNode(New, InsertPos);
2122 Types.push_back(New);
2123 return QualType(New, 0);
2124}
2125
Nate Begemance4d7fc2008-04-18 23:10:10 +00002126/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002127/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002128QualType
2129ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002130 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002131
Steve Naroff91fcddb2007-07-18 18:00:27 +00002132 // Check if we've already instantiated a vector of this type.
2133 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002134 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002135 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002136 void *InsertPos = 0;
2137 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2138 return QualType(VTP, 0);
2139
2140 // If the element type isn't canonical, this won't be a canonical type either,
2141 // so fill in the canonical type field.
2142 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002143 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002144 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002145
Steve Naroff91fcddb2007-07-18 18:00:27 +00002146 // Get the new insert position for the node we care about.
2147 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002148 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002149 }
John McCall90d1c2d2009-09-24 23:30:46 +00002150 ExtVectorType *New = new (*this, TypeAlignment)
2151 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002152 VectorTypes.InsertNode(New, InsertPos);
2153 Types.push_back(New);
2154 return QualType(New, 0);
2155}
2156
Jay Foad39c79802011-01-12 09:06:06 +00002157QualType
2158ASTContext::getDependentSizedExtVectorType(QualType vecType,
2159 Expr *SizeExpr,
2160 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002161 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002162 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002163 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002164
Douglas Gregor352169a2009-07-31 03:54:25 +00002165 void *InsertPos = 0;
2166 DependentSizedExtVectorType *Canon
2167 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2168 DependentSizedExtVectorType *New;
2169 if (Canon) {
2170 // We already have a canonical version of this array type; use it as
2171 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002172 New = new (*this, TypeAlignment)
2173 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2174 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002175 } else {
2176 QualType CanonVecTy = getCanonicalType(vecType);
2177 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002178 New = new (*this, TypeAlignment)
2179 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2180 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002181
2182 DependentSizedExtVectorType *CanonCheck
2183 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2184 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2185 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002186 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2187 } else {
2188 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2189 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002190 New = new (*this, TypeAlignment)
2191 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002192 }
2193 }
Mike Stump11289f42009-09-09 15:08:12 +00002194
Douglas Gregor758a8692009-06-17 21:51:59 +00002195 Types.push_back(New);
2196 return QualType(New, 0);
2197}
2198
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002199/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002200///
Jay Foad39c79802011-01-12 09:06:06 +00002201QualType
2202ASTContext::getFunctionNoProtoType(QualType ResultTy,
2203 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002204 const CallingConv DefaultCC = Info.getCC();
2205 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2206 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002207 // Unique functions, to guarantee there is only one function of a particular
2208 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002209 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002210 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002211
Chris Lattner47955de2007-01-27 08:37:20 +00002212 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002213 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002214 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002215 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002216
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002217 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002218 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002219 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002220 Canonical =
2221 getFunctionNoProtoType(getCanonicalType(ResultTy),
2222 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002223
Chris Lattner47955de2007-01-27 08:37:20 +00002224 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002225 FunctionNoProtoType *NewIP =
2226 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002227 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002228 }
Mike Stump11289f42009-09-09 15:08:12 +00002229
Roman Divacky65b88cd2011-03-01 17:40:53 +00002230 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002231 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002232 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002233 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002234 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002235 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002236}
2237
2238/// getFunctionType - Return a normal function type with a typed argument
2239/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002240QualType
2241ASTContext::getFunctionType(QualType ResultTy,
2242 const QualType *ArgArray, unsigned NumArgs,
2243 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002244 // Unique functions, to guarantee there is only one function of a particular
2245 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002246 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002247 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002248
2249 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002250 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002251 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002252 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002253
2254 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002255 bool isCanonical =
2256 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2257 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002258 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002259 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002260 isCanonical = false;
2261
Roman Divacky65b88cd2011-03-01 17:40:53 +00002262 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2263 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2264 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002265
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002266 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002267 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002268 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002269 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002270 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002271 CanonicalArgs.reserve(NumArgs);
2272 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002273 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002274
John McCalldb40c7f2010-12-14 08:05:40 +00002275 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002276 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002277 CanonicalEPI.ExceptionSpecType = EST_None;
2278 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002279 CanonicalEPI.ExtInfo
2280 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2281
Chris Lattner76a00cf2008-04-06 22:59:24 +00002282 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002283 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002284 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002285
Chris Lattnerfd4de792007-01-27 01:15:32 +00002286 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002287 FunctionProtoType *NewIP =
2288 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002289 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002290 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002291
John McCall31168b02011-06-15 23:02:42 +00002292 // FunctionProtoType objects are allocated with extra bytes after
2293 // them for three variable size arrays at the end:
2294 // - parameter types
2295 // - exception types
2296 // - consumed-arguments flags
2297 // Instead of the exception types, there could be a noexcept
2298 // expression.
John McCalldb40c7f2010-12-14 08:05:40 +00002299 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002300 NumArgs * sizeof(QualType);
2301 if (EPI.ExceptionSpecType == EST_Dynamic)
2302 Size += EPI.NumExceptions * sizeof(QualType);
2303 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002304 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002305 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002306 Size += 2 * sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002307 }
John McCall31168b02011-06-15 23:02:42 +00002308 if (EPI.ConsumedArguments)
2309 Size += NumArgs * sizeof(bool);
2310
John McCalldb40c7f2010-12-14 08:05:40 +00002311 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002312 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2313 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002314 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002315 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002316 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002317 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002318}
Chris Lattneref51c202006-11-10 07:17:23 +00002319
John McCalle78aac42010-03-10 03:28:59 +00002320#ifndef NDEBUG
2321static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2322 if (!isa<CXXRecordDecl>(D)) return false;
2323 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2324 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2325 return true;
2326 if (RD->getDescribedClassTemplate() &&
2327 !isa<ClassTemplateSpecializationDecl>(RD))
2328 return true;
2329 return false;
2330}
2331#endif
2332
2333/// getInjectedClassNameType - Return the unique reference to the
2334/// injected class name type for the specified templated declaration.
2335QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002336 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002337 assert(NeedsInjectedClassNameType(Decl));
2338 if (Decl->TypeForDecl) {
2339 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002340 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002341 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2342 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2343 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2344 } else {
John McCall424cec92011-01-19 06:33:43 +00002345 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002346 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002347 Decl->TypeForDecl = newType;
2348 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002349 }
2350 return QualType(Decl->TypeForDecl, 0);
2351}
2352
Douglas Gregor83a586e2008-04-13 21:07:44 +00002353/// getTypeDeclType - Return the unique reference to the type for the
2354/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002355QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002356 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002357 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002358
Richard Smithdda56e42011-04-15 14:24:37 +00002359 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002360 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002361
John McCall96f0b5f2010-03-10 06:48:02 +00002362 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2363 "Template type parameter types are always available.");
2364
John McCall81e38502010-02-16 03:57:14 +00002365 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002366 assert(!Record->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002367 "struct/union has previous declaration");
2368 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002369 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002370 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002371 assert(!Enum->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002372 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002373 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002374 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002375 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002376 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2377 Decl->TypeForDecl = newType;
2378 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002379 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002380 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002381
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002382 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002383}
2384
Chris Lattner32d920b2007-01-26 02:01:53 +00002385/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002386/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002387QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002388ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2389 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002390 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002391
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002392 if (Canonical.isNull())
2393 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002394 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002395 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002396 Decl->TypeForDecl = newType;
2397 Types.push_back(newType);
2398 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002399}
2400
Jay Foad39c79802011-01-12 09:06:06 +00002401QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002402 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2403
Douglas Gregorec9fd132012-01-14 16:38:05 +00002404 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002405 if (PrevDecl->TypeForDecl)
2406 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2407
John McCall424cec92011-01-19 06:33:43 +00002408 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2409 Decl->TypeForDecl = newType;
2410 Types.push_back(newType);
2411 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002412}
2413
Jay Foad39c79802011-01-12 09:06:06 +00002414QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002415 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2416
Douglas Gregorec9fd132012-01-14 16:38:05 +00002417 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002418 if (PrevDecl->TypeForDecl)
2419 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2420
John McCall424cec92011-01-19 06:33:43 +00002421 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2422 Decl->TypeForDecl = newType;
2423 Types.push_back(newType);
2424 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002425}
2426
John McCall81904512011-01-06 01:58:22 +00002427QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2428 QualType modifiedType,
2429 QualType equivalentType) {
2430 llvm::FoldingSetNodeID id;
2431 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2432
2433 void *insertPos = 0;
2434 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2435 if (type) return QualType(type, 0);
2436
2437 QualType canon = getCanonicalType(equivalentType);
2438 type = new (*this, TypeAlignment)
2439 AttributedType(canon, attrKind, modifiedType, equivalentType);
2440
2441 Types.push_back(type);
2442 AttributedTypes.InsertNode(type, insertPos);
2443
2444 return QualType(type, 0);
2445}
2446
2447
John McCallcebee162009-10-18 09:09:24 +00002448/// \brief Retrieve a substitution-result type.
2449QualType
2450ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002451 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002452 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002453 && "replacement types must always be canonical");
2454
2455 llvm::FoldingSetNodeID ID;
2456 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2457 void *InsertPos = 0;
2458 SubstTemplateTypeParmType *SubstParm
2459 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2460
2461 if (!SubstParm) {
2462 SubstParm = new (*this, TypeAlignment)
2463 SubstTemplateTypeParmType(Parm, Replacement);
2464 Types.push_back(SubstParm);
2465 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2466 }
2467
2468 return QualType(SubstParm, 0);
2469}
2470
Douglas Gregorada4b792011-01-14 02:55:32 +00002471/// \brief Retrieve a
2472QualType ASTContext::getSubstTemplateTypeParmPackType(
2473 const TemplateTypeParmType *Parm,
2474 const TemplateArgument &ArgPack) {
2475#ifndef NDEBUG
2476 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2477 PEnd = ArgPack.pack_end();
2478 P != PEnd; ++P) {
2479 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2480 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2481 }
2482#endif
2483
2484 llvm::FoldingSetNodeID ID;
2485 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2486 void *InsertPos = 0;
2487 if (SubstTemplateTypeParmPackType *SubstParm
2488 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2489 return QualType(SubstParm, 0);
2490
2491 QualType Canon;
2492 if (!Parm->isCanonicalUnqualified()) {
2493 Canon = getCanonicalType(QualType(Parm, 0));
2494 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2495 ArgPack);
2496 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2497 }
2498
2499 SubstTemplateTypeParmPackType *SubstParm
2500 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2501 ArgPack);
2502 Types.push_back(SubstParm);
2503 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2504 return QualType(SubstParm, 0);
2505}
2506
Douglas Gregoreff93e02009-02-05 23:33:38 +00002507/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002508/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002509/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002510QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002511 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002512 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002513 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002514 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002515 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002516 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002517 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2518
2519 if (TypeParm)
2520 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002521
Chandler Carruth08836322011-05-01 00:51:33 +00002522 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002523 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002524 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002525
2526 TemplateTypeParmType *TypeCheck
2527 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2528 assert(!TypeCheck && "Template type parameter canonical type broken");
2529 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002530 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002531 TypeParm = new (*this, TypeAlignment)
2532 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002533
2534 Types.push_back(TypeParm);
2535 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2536
2537 return QualType(TypeParm, 0);
2538}
2539
John McCalle78aac42010-03-10 03:28:59 +00002540TypeSourceInfo *
2541ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2542 SourceLocation NameLoc,
2543 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002544 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002545 assert(!Name.getAsDependentTemplateName() &&
2546 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002547 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002548
2549 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2550 TemplateSpecializationTypeLoc TL
2551 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002552 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00002553 TL.setTemplateNameLoc(NameLoc);
2554 TL.setLAngleLoc(Args.getLAngleLoc());
2555 TL.setRAngleLoc(Args.getRAngleLoc());
2556 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2557 TL.setArgLocInfo(i, Args[i].getLocInfo());
2558 return DI;
2559}
2560
Mike Stump11289f42009-09-09 15:08:12 +00002561QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002562ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002563 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002564 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002565 assert(!Template.getAsDependentTemplateName() &&
2566 "No dependent template names here!");
2567
John McCall6b51f282009-11-23 01:53:49 +00002568 unsigned NumArgs = Args.size();
2569
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002570 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002571 ArgVec.reserve(NumArgs);
2572 for (unsigned i = 0; i != NumArgs; ++i)
2573 ArgVec.push_back(Args[i].getArgument());
2574
John McCall2408e322010-04-27 00:57:59 +00002575 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002576 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002577}
2578
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002579#ifndef NDEBUG
2580static bool hasAnyPackExpansions(const TemplateArgument *Args,
2581 unsigned NumArgs) {
2582 for (unsigned I = 0; I != NumArgs; ++I)
2583 if (Args[I].isPackExpansion())
2584 return true;
2585
2586 return true;
2587}
2588#endif
2589
John McCall0ad16662009-10-29 08:12:44 +00002590QualType
2591ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002592 const TemplateArgument *Args,
2593 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002594 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002595 assert(!Template.getAsDependentTemplateName() &&
2596 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002597 // Look through qualified template names.
2598 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2599 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002600
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002601 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00002602 Template.getAsTemplateDecl() &&
2603 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00002604 QualType CanonType;
2605 if (!Underlying.isNull())
2606 CanonType = getCanonicalType(Underlying);
2607 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002608 // We can get here with an alias template when the specialization contains
2609 // a pack expansion that does not match up with a parameter pack.
2610 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2611 "Caller must compute aliased type");
2612 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00002613 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2614 NumArgs);
2615 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002616
Douglas Gregora8e02e72009-07-28 23:00:59 +00002617 // Allocate the (non-canonical) template specialization type, but don't
2618 // try to unique it: these types typically have location information that
2619 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002620 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2621 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002622 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002623 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002624 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002625 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2626 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002627
Douglas Gregor8bf42052009-02-09 18:46:07 +00002628 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002629 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002630}
2631
Mike Stump11289f42009-09-09 15:08:12 +00002632QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002633ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2634 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002635 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002636 assert(!Template.getAsDependentTemplateName() &&
2637 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002638
Douglas Gregore29139c2011-03-03 17:04:51 +00002639 // Look through qualified template names.
2640 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2641 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002642
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002643 // Build the canonical template specialization type.
2644 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002645 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002646 CanonArgs.reserve(NumArgs);
2647 for (unsigned I = 0; I != NumArgs; ++I)
2648 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2649
2650 // Determine whether this canonical template specialization type already
2651 // exists.
2652 llvm::FoldingSetNodeID ID;
2653 TemplateSpecializationType::Profile(ID, CanonTemplate,
2654 CanonArgs.data(), NumArgs, *this);
2655
2656 void *InsertPos = 0;
2657 TemplateSpecializationType *Spec
2658 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2659
2660 if (!Spec) {
2661 // Allocate a new canonical template specialization type.
2662 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2663 sizeof(TemplateArgument) * NumArgs),
2664 TypeAlignment);
2665 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2666 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002667 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002668 Types.push_back(Spec);
2669 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2670 }
2671
2672 assert(Spec->isDependentType() &&
2673 "Non-dependent template-id type must have a canonical type");
2674 return QualType(Spec, 0);
2675}
2676
2677QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002678ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2679 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002680 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002681 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002682 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002683
2684 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002685 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002686 if (T)
2687 return QualType(T, 0);
2688
Douglas Gregorc42075a2010-02-04 18:10:26 +00002689 QualType Canon = NamedType;
2690 if (!Canon.isCanonical()) {
2691 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002692 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2693 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002694 (void)CheckT;
2695 }
2696
Abramo Bagnara6150c882010-05-11 21:36:43 +00002697 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002698 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002699 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002700 return QualType(T, 0);
2701}
2702
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002703QualType
Jay Foad39c79802011-01-12 09:06:06 +00002704ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002705 llvm::FoldingSetNodeID ID;
2706 ParenType::Profile(ID, InnerType);
2707
2708 void *InsertPos = 0;
2709 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2710 if (T)
2711 return QualType(T, 0);
2712
2713 QualType Canon = InnerType;
2714 if (!Canon.isCanonical()) {
2715 Canon = getCanonicalType(InnerType);
2716 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2717 assert(!CheckT && "Paren canonical type broken");
2718 (void)CheckT;
2719 }
2720
2721 T = new (*this) ParenType(InnerType, Canon);
2722 Types.push_back(T);
2723 ParenTypes.InsertNode(T, InsertPos);
2724 return QualType(T, 0);
2725}
2726
Douglas Gregor02085352010-03-31 20:19:30 +00002727QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2728 NestedNameSpecifier *NNS,
2729 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002730 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002731 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2732
2733 if (Canon.isNull()) {
2734 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002735 ElaboratedTypeKeyword CanonKeyword = Keyword;
2736 if (Keyword == ETK_None)
2737 CanonKeyword = ETK_Typename;
2738
2739 if (CanonNNS != NNS || CanonKeyword != Keyword)
2740 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002741 }
2742
2743 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002744 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002745
2746 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002747 DependentNameType *T
2748 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002749 if (T)
2750 return QualType(T, 0);
2751
Douglas Gregor02085352010-03-31 20:19:30 +00002752 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002753 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002754 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002755 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002756}
2757
Mike Stump11289f42009-09-09 15:08:12 +00002758QualType
John McCallc392f372010-06-11 00:33:02 +00002759ASTContext::getDependentTemplateSpecializationType(
2760 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002761 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002762 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002763 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002764 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002765 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00002766 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2767 ArgCopy.push_back(Args[I].getArgument());
2768 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2769 ArgCopy.size(),
2770 ArgCopy.data());
2771}
2772
2773QualType
2774ASTContext::getDependentTemplateSpecializationType(
2775 ElaboratedTypeKeyword Keyword,
2776 NestedNameSpecifier *NNS,
2777 const IdentifierInfo *Name,
2778 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002779 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00002780 assert((!NNS || NNS->isDependent()) &&
2781 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00002782
Douglas Gregorc42075a2010-02-04 18:10:26 +00002783 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002784 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2785 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002786
2787 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002788 DependentTemplateSpecializationType *T
2789 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002790 if (T)
2791 return QualType(T, 0);
2792
John McCallc392f372010-06-11 00:33:02 +00002793 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002794
John McCallc392f372010-06-11 00:33:02 +00002795 ElaboratedTypeKeyword CanonKeyword = Keyword;
2796 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2797
2798 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002799 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00002800 for (unsigned I = 0; I != NumArgs; ++I) {
2801 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2802 if (!CanonArgs[I].structurallyEquals(Args[I]))
2803 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002804 }
2805
John McCallc392f372010-06-11 00:33:02 +00002806 QualType Canon;
2807 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2808 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2809 Name, NumArgs,
2810 CanonArgs.data());
2811
2812 // Find the insert position again.
2813 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2814 }
2815
2816 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2817 sizeof(TemplateArgument) * NumArgs),
2818 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002819 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002820 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002821 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002822 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002823 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002824}
2825
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002826QualType ASTContext::getPackExpansionType(QualType Pattern,
2827 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002828 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002829 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002830
2831 assert(Pattern->containsUnexpandedParameterPack() &&
2832 "Pack expansions must expand one or more parameter packs");
2833 void *InsertPos = 0;
2834 PackExpansionType *T
2835 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2836 if (T)
2837 return QualType(T, 0);
2838
2839 QualType Canon;
2840 if (!Pattern.isCanonical()) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002841 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002842
2843 // Find the insert position again.
2844 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2845 }
2846
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002847 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002848 Types.push_back(T);
2849 PackExpansionTypes.InsertNode(T, InsertPos);
2850 return QualType(T, 0);
2851}
2852
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002853/// CmpProtocolNames - Comparison predicate for sorting protocols
2854/// alphabetically.
2855static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2856 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002857 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002858}
2859
John McCall8b07ec22010-05-15 11:32:37 +00002860static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002861 unsigned NumProtocols) {
2862 if (NumProtocols == 0) return true;
2863
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002864 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
2865 return false;
2866
John McCallfc93cf92009-10-22 22:37:11 +00002867 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002868 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
2869 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00002870 return false;
2871 return true;
2872}
2873
2874static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002875 unsigned &NumProtocols) {
2876 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002877
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002878 // Sort protocols, keyed by name.
2879 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2880
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002881 // Canonicalize.
2882 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
2883 Protocols[I] = Protocols[I]->getCanonicalDecl();
2884
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002885 // Remove duplicates.
2886 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2887 NumProtocols = ProtocolsEnd-Protocols;
2888}
2889
John McCall8b07ec22010-05-15 11:32:37 +00002890QualType ASTContext::getObjCObjectType(QualType BaseType,
2891 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002892 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002893 // If the base type is an interface and there aren't any protocols
2894 // to add, then the interface type will do just fine.
2895 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2896 return BaseType;
2897
2898 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002899 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002900 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002901 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002902 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2903 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002904
John McCall8b07ec22010-05-15 11:32:37 +00002905 // Build the canonical type, which has the canonical base type and
2906 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002907 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002908 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2909 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2910 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002911 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002912 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002913 unsigned UniqueCount = NumProtocols;
2914
John McCallfc93cf92009-10-22 22:37:11 +00002915 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002916 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2917 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002918 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002919 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2920 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002921 }
2922
2923 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002924 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2925 }
2926
2927 unsigned Size = sizeof(ObjCObjectTypeImpl);
2928 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2929 void *Mem = Allocate(Size, TypeAlignment);
2930 ObjCObjectTypeImpl *T =
2931 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2932
2933 Types.push_back(T);
2934 ObjCObjectTypes.InsertNode(T, InsertPos);
2935 return QualType(T, 0);
2936}
2937
2938/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2939/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00002940QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00002941 llvm::FoldingSetNodeID ID;
2942 ObjCObjectPointerType::Profile(ID, ObjectT);
2943
2944 void *InsertPos = 0;
2945 if (ObjCObjectPointerType *QT =
2946 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2947 return QualType(QT, 0);
2948
2949 // Find the canonical object type.
2950 QualType Canonical;
2951 if (!ObjectT.isCanonical()) {
2952 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2953
2954 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002955 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2956 }
2957
Douglas Gregorf85bee62010-02-08 22:59:26 +00002958 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002959 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2960 ObjCObjectPointerType *QType =
2961 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002962
Steve Narofffb4330f2009-06-17 22:40:22 +00002963 Types.push_back(QType);
2964 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002965 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002966}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002967
Douglas Gregor1c283312010-08-11 12:19:30 +00002968/// getObjCInterfaceType - Return the unique reference to the type for the
2969/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00002970QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
2971 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00002972 if (Decl->TypeForDecl)
2973 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002974
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00002975 if (PrevDecl) {
2976 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
2977 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2978 return QualType(PrevDecl->TypeForDecl, 0);
2979 }
2980
Douglas Gregor7671e532011-12-16 16:34:57 +00002981 // Prefer the definition, if there is one.
2982 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
2983 Decl = Def;
2984
Douglas Gregor1c283312010-08-11 12:19:30 +00002985 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2986 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2987 Decl->TypeForDecl = T;
2988 Types.push_back(T);
2989 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002990}
2991
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002992/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2993/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002994/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002995/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002996/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002997QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002998 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002999 if (tofExpr->isTypeDependent()) {
3000 llvm::FoldingSetNodeID ID;
3001 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003002
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003003 void *InsertPos = 0;
3004 DependentTypeOfExprType *Canon
3005 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3006 if (Canon) {
3007 // We already have a "canonical" version of an identical, dependent
3008 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003009 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003010 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003011 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003012 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003013 Canon
3014 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003015 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3016 toe = Canon;
3017 }
3018 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003019 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003020 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003021 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003022 Types.push_back(toe);
3023 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003024}
3025
Steve Naroffa773cd52007-08-01 18:02:17 +00003026/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3027/// TypeOfType AST's. The only motivation to unique these nodes would be
3028/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003029/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003030/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003031QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003032 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003033 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003034 Types.push_back(tot);
3035 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003036}
3037
Anders Carlssonad6bd352009-06-24 21:24:56 +00003038
Anders Carlsson81df7b82009-06-24 19:06:50 +00003039/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3040/// DecltypeType AST's. The only motivation to unique these nodes would be
3041/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003042/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003043/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003044QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003045 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003046
3047 // C++0x [temp.type]p2:
3048 // If an expression e involves a template parameter, decltype(e) denotes a
3049 // unique dependent type. Two such decltype-specifiers refer to the same
3050 // type only if their expressions are equivalent (14.5.6.1).
3051 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003052 llvm::FoldingSetNodeID ID;
3053 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003054
Douglas Gregora21f6c32009-07-30 23:36:40 +00003055 void *InsertPos = 0;
3056 DependentDecltypeType *Canon
3057 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3058 if (Canon) {
3059 // We already have a "canonical" version of an equivalent, dependent
3060 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003061 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003062 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003063 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003064 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003065 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003066 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3067 dt = Canon;
3068 }
3069 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003070 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3071 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003072 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003073 Types.push_back(dt);
3074 return QualType(dt, 0);
3075}
3076
Alexis Hunte852b102011-05-24 22:41:36 +00003077/// getUnaryTransformationType - We don't unique these, since the memory
3078/// savings are minimal and these are rare.
3079QualType ASTContext::getUnaryTransformType(QualType BaseType,
3080 QualType UnderlyingType,
3081 UnaryTransformType::UTTKind Kind)
3082 const {
3083 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003084 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3085 Kind,
3086 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003087 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003088 Types.push_back(Ty);
3089 return QualType(Ty, 0);
3090}
3091
Richard Smithb2bc2e62011-02-21 20:05:19 +00003092/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003093QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00003094 void *InsertPos = 0;
3095 if (!DeducedType.isNull()) {
3096 // Look in the folding set for an existing type.
3097 llvm::FoldingSetNodeID ID;
3098 AutoType::Profile(ID, DeducedType);
3099 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3100 return QualType(AT, 0);
3101 }
3102
3103 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3104 Types.push_back(AT);
3105 if (InsertPos)
3106 AutoTypes.InsertNode(AT, InsertPos);
3107 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003108}
3109
Eli Friedman0dfb8892011-10-06 23:00:33 +00003110/// getAtomicType - Return the uniqued reference to the atomic type for
3111/// the given value type.
3112QualType ASTContext::getAtomicType(QualType T) const {
3113 // Unique pointers, to guarantee there is only one pointer of a particular
3114 // structure.
3115 llvm::FoldingSetNodeID ID;
3116 AtomicType::Profile(ID, T);
3117
3118 void *InsertPos = 0;
3119 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3120 return QualType(AT, 0);
3121
3122 // If the atomic value type isn't canonical, this won't be a canonical type
3123 // either, so fill in the canonical type field.
3124 QualType Canonical;
3125 if (!T.isCanonical()) {
3126 Canonical = getAtomicType(getCanonicalType(T));
3127
3128 // Get the new insert position for the node we care about.
3129 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3130 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3131 }
3132 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3133 Types.push_back(New);
3134 AtomicTypes.InsertNode(New, InsertPos);
3135 return QualType(New, 0);
3136}
3137
Richard Smith02e85f32011-04-14 22:09:26 +00003138/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3139QualType ASTContext::getAutoDeductType() const {
3140 if (AutoDeductTy.isNull())
3141 AutoDeductTy = getAutoType(QualType());
3142 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3143 return AutoDeductTy;
3144}
3145
3146/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3147QualType ASTContext::getAutoRRefDeductType() const {
3148 if (AutoRRefDeductTy.isNull())
3149 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3150 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3151 return AutoRRefDeductTy;
3152}
3153
Chris Lattnerfb072462007-01-23 05:45:31 +00003154/// getTagDeclType - Return the unique reference to the type for the
3155/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003156QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003157 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003158 // FIXME: What is the design on getTagDeclType when it requires casting
3159 // away const? mutable?
3160 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003161}
3162
Mike Stump11289f42009-09-09 15:08:12 +00003163/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3164/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3165/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003166CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003167 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003168}
Chris Lattnerfb072462007-01-23 05:45:31 +00003169
Hans Wennborg27541db2011-10-27 08:29:09 +00003170/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3171CanQualType ASTContext::getIntMaxType() const {
3172 return getFromTargetType(Target->getIntMaxType());
3173}
3174
3175/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3176CanQualType ASTContext::getUIntMaxType() const {
3177 return getFromTargetType(Target->getUIntMaxType());
3178}
3179
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003180/// getSignedWCharType - Return the type of "signed wchar_t".
3181/// Used when in C++, as a GCC extension.
3182QualType ASTContext::getSignedWCharType() const {
3183 // FIXME: derive from "Target" ?
3184 return WCharTy;
3185}
3186
3187/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3188/// Used when in C++, as a GCC extension.
3189QualType ASTContext::getUnsignedWCharType() const {
3190 // FIXME: derive from "Target" ?
3191 return UnsignedIntTy;
3192}
3193
Hans Wennborg27541db2011-10-27 08:29:09 +00003194/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003195/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3196QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003197 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003198}
3199
Chris Lattnera21ad802008-04-02 05:18:44 +00003200//===----------------------------------------------------------------------===//
3201// Type Operators
3202//===----------------------------------------------------------------------===//
3203
Jay Foad39c79802011-01-12 09:06:06 +00003204CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003205 // Push qualifiers into arrays, and then discard any remaining
3206 // qualifiers.
3207 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003208 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003209 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003210 QualType Result;
3211 if (isa<ArrayType>(Ty)) {
3212 Result = getArrayDecayedType(QualType(Ty,0));
3213 } else if (isa<FunctionType>(Ty)) {
3214 Result = getPointerType(QualType(Ty, 0));
3215 } else {
3216 Result = QualType(Ty, 0);
3217 }
3218
3219 return CanQualType::CreateUnsafe(Result);
3220}
3221
John McCall6c9dd522011-01-18 07:41:22 +00003222QualType ASTContext::getUnqualifiedArrayType(QualType type,
3223 Qualifiers &quals) {
3224 SplitQualType splitType = type.getSplitUnqualifiedType();
3225
3226 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3227 // the unqualified desugared type and then drops it on the floor.
3228 // We then have to strip that sugar back off with
3229 // getUnqualifiedDesugaredType(), which is silly.
3230 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003231 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003232
3233 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003234 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003235 quals = splitType.Quals;
3236 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003237 }
3238
John McCall6c9dd522011-01-18 07:41:22 +00003239 // Otherwise, recurse on the array's element type.
3240 QualType elementType = AT->getElementType();
3241 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3242
3243 // If that didn't change the element type, AT has no qualifiers, so we
3244 // can just use the results in splitType.
3245 if (elementType == unqualElementType) {
3246 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003247 quals = splitType.Quals;
3248 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003249 }
3250
3251 // Otherwise, add in the qualifiers from the outermost type, then
3252 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003253 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003254
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003255 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003256 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003257 CAT->getSizeModifier(), 0);
3258 }
3259
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003260 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003261 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003262 }
3263
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003264 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003265 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003266 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003267 VAT->getSizeModifier(),
3268 VAT->getIndexTypeCVRQualifiers(),
3269 VAT->getBracketsRange());
3270 }
3271
3272 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003273 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003274 DSAT->getSizeModifier(), 0,
3275 SourceRange());
3276}
3277
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003278/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3279/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3280/// they point to and return true. If T1 and T2 aren't pointer types
3281/// or pointer-to-member types, or if they are not similar at this
3282/// level, returns false and leaves T1 and T2 unchanged. Top-level
3283/// qualifiers on T1 and T2 are ignored. This function will typically
3284/// be called in a loop that successively "unwraps" pointer and
3285/// pointer-to-member types to compare them at each level.
3286bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3287 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3288 *T2PtrType = T2->getAs<PointerType>();
3289 if (T1PtrType && T2PtrType) {
3290 T1 = T1PtrType->getPointeeType();
3291 T2 = T2PtrType->getPointeeType();
3292 return true;
3293 }
3294
3295 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3296 *T2MPType = T2->getAs<MemberPointerType>();
3297 if (T1MPType && T2MPType &&
3298 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3299 QualType(T2MPType->getClass(), 0))) {
3300 T1 = T1MPType->getPointeeType();
3301 T2 = T2MPType->getPointeeType();
3302 return true;
3303 }
3304
David Blaikiebbafb8a2012-03-11 07:00:24 +00003305 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003306 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3307 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3308 if (T1OPType && T2OPType) {
3309 T1 = T1OPType->getPointeeType();
3310 T2 = T2OPType->getPointeeType();
3311 return true;
3312 }
3313 }
3314
3315 // FIXME: Block pointers, too?
3316
3317 return false;
3318}
3319
Jay Foad39c79802011-01-12 09:06:06 +00003320DeclarationNameInfo
3321ASTContext::getNameForTemplate(TemplateName Name,
3322 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003323 switch (Name.getKind()) {
3324 case TemplateName::QualifiedTemplate:
3325 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003326 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003327 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3328 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003329
John McCalld9dfe3a2011-06-30 08:33:18 +00003330 case TemplateName::OverloadedTemplate: {
3331 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3332 // DNInfo work in progress: CHECKME: what about DNLoc?
3333 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3334 }
3335
3336 case TemplateName::DependentTemplate: {
3337 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003338 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003339 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003340 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3341 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003342 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003343 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3344 // DNInfo work in progress: FIXME: source locations?
3345 DeclarationNameLoc DNLoc;
3346 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3347 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3348 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003349 }
3350 }
3351
John McCalld9dfe3a2011-06-30 08:33:18 +00003352 case TemplateName::SubstTemplateTemplateParm: {
3353 SubstTemplateTemplateParmStorage *subst
3354 = Name.getAsSubstTemplateTemplateParm();
3355 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3356 NameLoc);
3357 }
3358
3359 case TemplateName::SubstTemplateTemplateParmPack: {
3360 SubstTemplateTemplateParmPackStorage *subst
3361 = Name.getAsSubstTemplateTemplateParmPack();
3362 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3363 NameLoc);
3364 }
3365 }
3366
3367 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003368}
3369
Jay Foad39c79802011-01-12 09:06:06 +00003370TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003371 switch (Name.getKind()) {
3372 case TemplateName::QualifiedTemplate:
3373 case TemplateName::Template: {
3374 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003375 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003376 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003377 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3378
3379 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003380 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003381 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003382
John McCalld9dfe3a2011-06-30 08:33:18 +00003383 case TemplateName::OverloadedTemplate:
3384 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003385
John McCalld9dfe3a2011-06-30 08:33:18 +00003386 case TemplateName::DependentTemplate: {
3387 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3388 assert(DTN && "Non-dependent template names must refer to template decls.");
3389 return DTN->CanonicalTemplateName;
3390 }
3391
3392 case TemplateName::SubstTemplateTemplateParm: {
3393 SubstTemplateTemplateParmStorage *subst
3394 = Name.getAsSubstTemplateTemplateParm();
3395 return getCanonicalTemplateName(subst->getReplacement());
3396 }
3397
3398 case TemplateName::SubstTemplateTemplateParmPack: {
3399 SubstTemplateTemplateParmPackStorage *subst
3400 = Name.getAsSubstTemplateTemplateParmPack();
3401 TemplateTemplateParmDecl *canonParameter
3402 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3403 TemplateArgument canonArgPack
3404 = getCanonicalTemplateArgument(subst->getArgumentPack());
3405 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3406 }
3407 }
3408
3409 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003410}
3411
Douglas Gregoradee3e32009-11-11 23:06:43 +00003412bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3413 X = getCanonicalTemplateName(X);
3414 Y = getCanonicalTemplateName(Y);
3415 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3416}
3417
Mike Stump11289f42009-09-09 15:08:12 +00003418TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003419ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003420 switch (Arg.getKind()) {
3421 case TemplateArgument::Null:
3422 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003423
Douglas Gregora8e02e72009-07-28 23:00:59 +00003424 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003425 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003426
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003427 case TemplateArgument::Declaration: {
3428 if (Decl *D = Arg.getAsDecl())
3429 return TemplateArgument(D->getCanonicalDecl());
3430 return TemplateArgument((Decl*)0);
3431 }
Mike Stump11289f42009-09-09 15:08:12 +00003432
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003433 case TemplateArgument::Template:
3434 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003435
3436 case TemplateArgument::TemplateExpansion:
3437 return TemplateArgument(getCanonicalTemplateName(
3438 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003439 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003440
Douglas Gregora8e02e72009-07-28 23:00:59 +00003441 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00003442 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003443
Douglas Gregora8e02e72009-07-28 23:00:59 +00003444 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003445 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003446
Douglas Gregora8e02e72009-07-28 23:00:59 +00003447 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003448 if (Arg.pack_size() == 0)
3449 return Arg;
3450
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003451 TemplateArgument *CanonArgs
3452 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003453 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003454 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003455 AEnd = Arg.pack_end();
3456 A != AEnd; (void)++A, ++Idx)
3457 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003458
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003459 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003460 }
3461 }
3462
3463 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003464 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003465}
3466
Douglas Gregor333489b2009-03-27 23:10:48 +00003467NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003468ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003469 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003470 return 0;
3471
3472 switch (NNS->getKind()) {
3473 case NestedNameSpecifier::Identifier:
3474 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003475 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003476 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3477 NNS->getAsIdentifier());
3478
3479 case NestedNameSpecifier::Namespace:
3480 // A namespace is canonical; build a nested-name-specifier with
3481 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003482 return NestedNameSpecifier::Create(*this, 0,
3483 NNS->getAsNamespace()->getOriginalNamespace());
3484
3485 case NestedNameSpecifier::NamespaceAlias:
3486 // A namespace is canonical; build a nested-name-specifier with
3487 // this namespace and no prefix.
3488 return NestedNameSpecifier::Create(*this, 0,
3489 NNS->getAsNamespaceAlias()->getNamespace()
3490 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003491
3492 case NestedNameSpecifier::TypeSpec:
3493 case NestedNameSpecifier::TypeSpecWithTemplate: {
3494 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003495
3496 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3497 // break it apart into its prefix and identifier, then reconsititute those
3498 // as the canonical nested-name-specifier. This is required to canonicalize
3499 // a dependent nested-name-specifier involving typedefs of dependent-name
3500 // types, e.g.,
3501 // typedef typename T::type T1;
3502 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00003503 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3504 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00003505 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003506
Eli Friedman5358a0a2012-03-03 04:09:56 +00003507 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3508 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3509 // first place?
John McCall33ddac02011-01-19 10:06:00 +00003510 return NestedNameSpecifier::Create(*this, 0, false,
3511 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003512 }
3513
3514 case NestedNameSpecifier::Global:
3515 // The global specifier is canonical and unique.
3516 return NNS;
3517 }
3518
David Blaikie8a40f702012-01-17 06:56:22 +00003519 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00003520}
3521
Chris Lattner7adf0762008-08-04 07:31:14 +00003522
Jay Foad39c79802011-01-12 09:06:06 +00003523const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003524 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003525 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003526 // Handle the common positive case fast.
3527 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3528 return AT;
3529 }
Mike Stump11289f42009-09-09 15:08:12 +00003530
John McCall8ccfcb52009-09-24 19:53:00 +00003531 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003532 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003533 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003534
John McCall8ccfcb52009-09-24 19:53:00 +00003535 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003536 // implements C99 6.7.3p8: "If the specification of an array type includes
3537 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003538
Chris Lattner7adf0762008-08-04 07:31:14 +00003539 // If we get here, we either have type qualifiers on the type, or we have
3540 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003541 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003542
John McCall33ddac02011-01-19 10:06:00 +00003543 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003544 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00003545
Chris Lattner7adf0762008-08-04 07:31:14 +00003546 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00003547 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00003548 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003549 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003550
Chris Lattner7adf0762008-08-04 07:31:14 +00003551 // Otherwise, we have an array and we have qualifiers on it. Push the
3552 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003553 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003554
Chris Lattner7adf0762008-08-04 07:31:14 +00003555 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3556 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3557 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003558 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003559 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3560 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3561 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003562 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003563
Mike Stump11289f42009-09-09 15:08:12 +00003564 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003565 = dyn_cast<DependentSizedArrayType>(ATy))
3566 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003567 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003568 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003569 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003570 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003571 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003572
Chris Lattner7adf0762008-08-04 07:31:14 +00003573 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003574 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003575 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003576 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003577 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003578 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003579}
3580
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003581QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003582 // C99 6.7.5.3p7:
3583 // A declaration of a parameter as "array of type" shall be
3584 // adjusted to "qualified pointer to type", where the type
3585 // qualifiers (if any) are those specified within the [ and ] of
3586 // the array type derivation.
3587 if (T->isArrayType())
3588 return getArrayDecayedType(T);
3589
3590 // C99 6.7.5.3p8:
3591 // A declaration of a parameter as "function returning type"
3592 // shall be adjusted to "pointer to function returning type", as
3593 // in 6.3.2.1.
3594 if (T->isFunctionType())
3595 return getPointerType(T);
3596
3597 return T;
3598}
3599
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003600QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003601 T = getVariableArrayDecayedType(T);
3602 T = getAdjustedParameterType(T);
3603 return T.getUnqualifiedType();
3604}
3605
Chris Lattnera21ad802008-04-02 05:18:44 +00003606/// getArrayDecayedType - Return the properly qualified result of decaying the
3607/// specified array type to a pointer. This operation is non-trivial when
3608/// handling typedefs etc. The canonical type of "T" must be an array type,
3609/// this returns a pointer to a properly qualified element of the array.
3610///
3611/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003612QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003613 // Get the element type with 'getAsArrayType' so that we don't lose any
3614 // typedefs in the element type of the array. This also handles propagation
3615 // of type qualifiers from the array type into the element type if present
3616 // (C99 6.7.3p8).
3617 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3618 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003619
Chris Lattner7adf0762008-08-04 07:31:14 +00003620 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003621
3622 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003623 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003624}
3625
John McCall33ddac02011-01-19 10:06:00 +00003626QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3627 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003628}
3629
John McCall33ddac02011-01-19 10:06:00 +00003630QualType ASTContext::getBaseElementType(QualType type) const {
3631 Qualifiers qs;
3632 while (true) {
3633 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003634 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00003635 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003636
John McCall33ddac02011-01-19 10:06:00 +00003637 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00003638 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003639 }
Mike Stump11289f42009-09-09 15:08:12 +00003640
John McCall33ddac02011-01-19 10:06:00 +00003641 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003642}
3643
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003644/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003645uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003646ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3647 uint64_t ElementCount = 1;
3648 do {
3649 ElementCount *= CA->getSize().getZExtValue();
3650 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3651 } while (CA);
3652 return ElementCount;
3653}
3654
Steve Naroff0af91202007-04-27 21:51:21 +00003655/// getFloatingRank - Return a relative rank for floating point types.
3656/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003657static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003658 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003659 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003660
John McCall9dd450b2009-09-21 23:43:11 +00003661 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3662 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003663 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003664 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00003665 case BuiltinType::Float: return FloatRank;
3666 case BuiltinType::Double: return DoubleRank;
3667 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003668 }
3669}
3670
Mike Stump11289f42009-09-09 15:08:12 +00003671/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3672/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003673/// 'typeDomain' is a real floating point or complex type.
3674/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003675QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3676 QualType Domain) const {
3677 FloatingRank EltRank = getFloatingRank(Size);
3678 if (Domain->isComplexType()) {
3679 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003680 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00003681 case FloatRank: return FloatComplexTy;
3682 case DoubleRank: return DoubleComplexTy;
3683 case LongDoubleRank: return LongDoubleComplexTy;
3684 }
Steve Naroff0af91202007-04-27 21:51:21 +00003685 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003686
3687 assert(Domain->isRealFloatingType() && "Unknown domain!");
3688 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003689 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003690 case FloatRank: return FloatTy;
3691 case DoubleRank: return DoubleTy;
3692 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003693 }
David Blaikief47fa302012-01-17 02:30:50 +00003694 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00003695}
3696
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003697/// getFloatingTypeOrder - Compare the rank of the two specified floating
3698/// point types, ignoring the domain of the type (i.e. 'double' ==
3699/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003700/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003701int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003702 FloatingRank LHSR = getFloatingRank(LHS);
3703 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003704
Chris Lattnerb90739d2008-04-06 23:38:49 +00003705 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003706 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003707 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003708 return 1;
3709 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003710}
3711
Chris Lattner76a00cf2008-04-06 22:59:24 +00003712/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3713/// routine will assert if passed a built-in type that isn't an integer or enum,
3714/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003715unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003716 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003717
Chris Lattner76a00cf2008-04-06 22:59:24 +00003718 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003719 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003720 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003721 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003722 case BuiltinType::Char_S:
3723 case BuiltinType::Char_U:
3724 case BuiltinType::SChar:
3725 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003726 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003727 case BuiltinType::Short:
3728 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003729 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003730 case BuiltinType::Int:
3731 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003732 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003733 case BuiltinType::Long:
3734 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003735 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003736 case BuiltinType::LongLong:
3737 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003738 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003739 case BuiltinType::Int128:
3740 case BuiltinType::UInt128:
3741 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003742 }
3743}
3744
Eli Friedman629ffb92009-08-20 04:21:42 +00003745/// \brief Whether this is a promotable bitfield reference according
3746/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3747///
3748/// \returns the type this bit-field will promote to, or NULL if no
3749/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003750QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003751 if (E->isTypeDependent() || E->isValueDependent())
3752 return QualType();
3753
Eli Friedman629ffb92009-08-20 04:21:42 +00003754 FieldDecl *Field = E->getBitField();
3755 if (!Field)
3756 return QualType();
3757
3758 QualType FT = Field->getType();
3759
Richard Smithcaf33902011-10-10 18:28:20 +00003760 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00003761 uint64_t IntSize = getTypeSize(IntTy);
3762 // GCC extension compatibility: if the bit-field size is less than or equal
3763 // to the size of int, it gets promoted no matter what its type is.
3764 // For instance, unsigned long bf : 4 gets promoted to signed int.
3765 if (BitWidth < IntSize)
3766 return IntTy;
3767
3768 if (BitWidth == IntSize)
3769 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3770
3771 // Types bigger than int are not subject to promotions, and therefore act
3772 // like the base type.
3773 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3774 // is ridiculous.
3775 return QualType();
3776}
3777
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003778/// getPromotedIntegerType - Returns the type that Promotable will
3779/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3780/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003781QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003782 assert(!Promotable.isNull());
3783 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003784 if (const EnumType *ET = Promotable->getAs<EnumType>())
3785 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00003786
3787 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3788 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3789 // (3.9.1) can be converted to a prvalue of the first of the following
3790 // types that can represent all the values of its underlying type:
3791 // int, unsigned int, long int, unsigned long int, long long int, or
3792 // unsigned long long int [...]
3793 // FIXME: Is there some better way to compute this?
3794 if (BT->getKind() == BuiltinType::WChar_S ||
3795 BT->getKind() == BuiltinType::WChar_U ||
3796 BT->getKind() == BuiltinType::Char16 ||
3797 BT->getKind() == BuiltinType::Char32) {
3798 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3799 uint64_t FromSize = getTypeSize(BT);
3800 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3801 LongLongTy, UnsignedLongLongTy };
3802 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3803 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3804 if (FromSize < ToSize ||
3805 (FromSize == ToSize &&
3806 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3807 return PromoteTypes[Idx];
3808 }
3809 llvm_unreachable("char type should fit into long long");
3810 }
3811 }
3812
3813 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003814 if (Promotable->isSignedIntegerType())
3815 return IntTy;
3816 uint64_t PromotableSize = getTypeSize(Promotable);
3817 uint64_t IntSize = getTypeSize(IntTy);
3818 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3819 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3820}
3821
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003822/// \brief Recurses in pointer/array types until it finds an objc retainable
3823/// type and returns its ownership.
3824Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3825 while (!T.isNull()) {
3826 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3827 return T.getObjCLifetime();
3828 if (T->isArrayType())
3829 T = getBaseElementType(T);
3830 else if (const PointerType *PT = T->getAs<PointerType>())
3831 T = PT->getPointeeType();
3832 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00003833 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003834 else
3835 break;
3836 }
3837
3838 return Qualifiers::OCL_None;
3839}
3840
Mike Stump11289f42009-09-09 15:08:12 +00003841/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003842/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003843/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003844int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00003845 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3846 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003847 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003848
Chris Lattner76a00cf2008-04-06 22:59:24 +00003849 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3850 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003851
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003852 unsigned LHSRank = getIntegerRank(LHSC);
3853 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003854
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003855 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3856 if (LHSRank == RHSRank) return 0;
3857 return LHSRank > RHSRank ? 1 : -1;
3858 }
Mike Stump11289f42009-09-09 15:08:12 +00003859
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003860 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3861 if (LHSUnsigned) {
3862 // If the unsigned [LHS] type is larger, return it.
3863 if (LHSRank >= RHSRank)
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;
3870 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003871
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003872 // If the unsigned [RHS] type is larger, return it.
3873 if (RHSRank >= LHSRank)
3874 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003875
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003876 // If the signed type can represent all values of the unsigned type, it
3877 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003878 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003879 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003880}
Anders Carlsson98f07902007-08-17 05:31:46 +00003881
Anders Carlsson6d417272009-11-14 21:45:58 +00003882static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003883CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3884 DeclContext *DC, IdentifierInfo *Id) {
3885 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003886 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003887 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003888 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003889 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003890}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003891
Mike Stump11289f42009-09-09 15:08:12 +00003892// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003893QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003894 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003895 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003896 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003897 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003898 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003899
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003900 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003901
Anders Carlsson98f07902007-08-17 05:31:46 +00003902 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003903 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003904 // int flags;
3905 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003906 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003907 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003908 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003909 FieldTypes[3] = LongTy;
3910
Anders Carlsson98f07902007-08-17 05:31:46 +00003911 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003912 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003913 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003914 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00003915 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003916 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003917 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003918 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003919 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00003920 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003921 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003922 }
3923
Douglas Gregord5058122010-02-11 01:19:42 +00003924 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003925 }
Mike Stump11289f42009-09-09 15:08:12 +00003926
Anders Carlsson98f07902007-08-17 05:31:46 +00003927 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003928}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003929
Douglas Gregor512b0772009-04-23 22:29:11 +00003930void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003931 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003932 assert(Rec && "Invalid CFConstantStringType");
3933 CFConstantStringTypeDecl = Rec->getDecl();
3934}
3935
Jay Foad39c79802011-01-12 09:06:06 +00003936QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003937 if (BlockDescriptorType)
3938 return getTagDeclType(BlockDescriptorType);
3939
3940 RecordDecl *T;
3941 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003942 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003943 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003944 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003945
3946 QualType FieldTypes[] = {
3947 UnsignedLongTy,
3948 UnsignedLongTy,
3949 };
3950
3951 const char *FieldNames[] = {
3952 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003953 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003954 };
3955
3956 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003957 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003958 SourceLocation(),
3959 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003960 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003961 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003962 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003963 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00003964 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003965 T->addDecl(Field);
3966 }
3967
Douglas Gregord5058122010-02-11 01:19:42 +00003968 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003969
3970 BlockDescriptorType = T;
3971
3972 return getTagDeclType(BlockDescriptorType);
3973}
3974
Jay Foad39c79802011-01-12 09:06:06 +00003975QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003976 if (BlockDescriptorExtendedType)
3977 return getTagDeclType(BlockDescriptorExtendedType);
3978
3979 RecordDecl *T;
3980 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003981 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003982 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003983 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003984
3985 QualType FieldTypes[] = {
3986 UnsignedLongTy,
3987 UnsignedLongTy,
3988 getPointerType(VoidPtrTy),
3989 getPointerType(VoidPtrTy)
3990 };
3991
3992 const char *FieldNames[] = {
3993 "reserved",
3994 "Size",
3995 "CopyFuncPtr",
3996 "DestroyFuncPtr"
3997 };
3998
3999 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004000 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004001 SourceLocation(),
4002 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004003 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004004 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004005 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004006 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004007 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004008 T->addDecl(Field);
4009 }
4010
Douglas Gregord5058122010-02-11 01:19:42 +00004011 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004012
4013 BlockDescriptorExtendedType = T;
4014
4015 return getTagDeclType(BlockDescriptorExtendedType);
4016}
4017
Jay Foad39c79802011-01-12 09:06:06 +00004018bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCall31168b02011-06-15 23:02:42 +00004019 if (Ty->isObjCRetainableType())
Mike Stump94967902009-10-21 18:16:27 +00004020 return true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004021 if (getLangOpts().CPlusPlus) {
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004022 if (const RecordType *RT = Ty->getAs<RecordType>()) {
4023 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntfcaeae42011-05-25 20:50:04 +00004024 return RD->hasConstCopyConstructor();
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004025
4026 }
4027 }
Mike Stump94967902009-10-21 18:16:27 +00004028 return false;
4029}
4030
Jay Foad39c79802011-01-12 09:06:06 +00004031QualType
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004032ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00004033 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00004034 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00004035 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00004036 // unsigned int __flags;
4037 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00004038 // void *__copy_helper; // as needed
4039 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00004040 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00004041 // } *
4042
Mike Stump94967902009-10-21 18:16:27 +00004043 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
4044
4045 // FIXME: Move up
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004046 SmallString<36> Name;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00004047 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
4048 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00004049 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004050 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00004051 T->startDefinition();
4052 QualType Int32Ty = IntTy;
4053 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
4054 QualType FieldTypes[] = {
4055 getPointerType(VoidPtrTy),
4056 getPointerType(getTagDeclType(T)),
4057 Int32Ty,
4058 Int32Ty,
4059 getPointerType(VoidPtrTy),
4060 getPointerType(VoidPtrTy),
4061 Ty
4062 };
4063
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004064 StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00004065 "__isa",
4066 "__forwarding",
4067 "__flags",
4068 "__size",
4069 "__copy_helper",
4070 "__destroy_helper",
4071 DeclName,
4072 };
4073
4074 for (size_t i = 0; i < 7; ++i) {
4075 if (!HasCopyAndDispose && i >=4 && i <= 5)
4076 continue;
4077 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00004078 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00004079 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004080 FieldTypes[i], /*TInfo=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004081 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004082 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004083 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00004084 T->addDecl(Field);
4085 }
4086
Douglas Gregord5058122010-02-11 01:19:42 +00004087 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00004088
4089 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00004090}
4091
Douglas Gregorbab8a962011-09-08 01:46:34 +00004092TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4093 if (!ObjCInstanceTypeDecl)
4094 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4095 getTranslationUnitDecl(),
4096 SourceLocation(),
4097 SourceLocation(),
4098 &Idents.get("instancetype"),
4099 getTrivialTypeSourceInfo(getObjCIdType()));
4100 return ObjCInstanceTypeDecl;
4101}
4102
Anders Carlsson18acd442007-10-29 06:33:42 +00004103// This returns true if a type has been typedefed to BOOL:
4104// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004105static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004106 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004107 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4108 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004109
Anders Carlssond8499822007-10-29 05:01:08 +00004110 return false;
4111}
4112
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004113/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004114/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004115CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004116 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4117 return CharUnits::Zero();
4118
Ken Dyck40775002010-01-11 17:06:35 +00004119 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004120
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004121 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004122 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004123 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004124 // Treat arrays as pointers, since that's how they're passed in.
4125 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004126 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004127 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004128}
4129
4130static inline
4131std::string charUnitsToString(const CharUnits &CU) {
4132 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004133}
4134
John McCall351762c2011-02-07 10:33:21 +00004135/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004136/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004137std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4138 std::string S;
4139
David Chisnall950a9512009-11-17 19:33:30 +00004140 const BlockDecl *Decl = Expr->getBlockDecl();
4141 QualType BlockTy =
4142 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4143 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00004144 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004145 // Compute size of all parameters.
4146 // Start with computing size of a pointer in number of bytes.
4147 // FIXME: There might(should) be a better way of doing this computation!
4148 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004149 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4150 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004151 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004152 E = Decl->param_end(); PI != E; ++PI) {
4153 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004154 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004155 if (sz.isZero())
4156 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004157 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004158 ParmOffset += sz;
4159 }
4160 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004161 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004162 // Block pointer and offset.
4163 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004164
4165 // Argument types.
4166 ParmOffset = PtrSize;
4167 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4168 Decl->param_end(); PI != E; ++PI) {
4169 ParmVarDecl *PVDecl = *PI;
4170 QualType PType = PVDecl->getOriginalType();
4171 if (const ArrayType *AT =
4172 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4173 // Use array's original type only if it has known number of
4174 // elements.
4175 if (!isa<ConstantArrayType>(AT))
4176 PType = PVDecl->getType();
4177 } else if (PType->isFunctionType())
4178 PType = PVDecl->getType();
4179 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004180 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004181 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004182 }
John McCall351762c2011-02-07 10:33:21 +00004183
4184 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004185}
4186
Douglas Gregora9d84932011-05-27 01:19:52 +00004187bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004188 std::string& S) {
4189 // Encode result type.
4190 getObjCEncodingForType(Decl->getResultType(), S);
4191 CharUnits ParmOffset;
4192 // Compute size of all parameters.
4193 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4194 E = Decl->param_end(); PI != E; ++PI) {
4195 QualType PType = (*PI)->getType();
4196 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004197 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004198 continue;
4199
David Chisnall50e4eba2010-12-30 14:05:53 +00004200 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004201 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004202 ParmOffset += sz;
4203 }
4204 S += charUnitsToString(ParmOffset);
4205 ParmOffset = CharUnits::Zero();
4206
4207 // Argument types.
4208 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4209 E = Decl->param_end(); PI != E; ++PI) {
4210 ParmVarDecl *PVDecl = *PI;
4211 QualType PType = PVDecl->getOriginalType();
4212 if (const ArrayType *AT =
4213 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4214 // Use array's original type only if it has known number of
4215 // elements.
4216 if (!isa<ConstantArrayType>(AT))
4217 PType = PVDecl->getType();
4218 } else if (PType->isFunctionType())
4219 PType = PVDecl->getType();
4220 getObjCEncodingForType(PType, S);
4221 S += charUnitsToString(ParmOffset);
4222 ParmOffset += getObjCEncodingTypeSize(PType);
4223 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004224
4225 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004226}
4227
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004228/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4229/// method parameter or return type. If Extended, include class names and
4230/// block object types.
4231void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4232 QualType T, std::string& S,
4233 bool Extended) const {
4234 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4235 getObjCEncodingForTypeQualifier(QT, S);
4236 // Encode parameter type.
4237 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4238 true /*OutermostType*/,
4239 false /*EncodingProperty*/,
4240 false /*StructField*/,
4241 Extended /*EncodeBlockParameters*/,
4242 Extended /*EncodeClassNames*/);
4243}
4244
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004245/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004246/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004247bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004248 std::string& S,
4249 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004250 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004251 // Encode return type.
4252 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4253 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004254 // Compute size of all parameters.
4255 // Start with computing size of a pointer in number of bytes.
4256 // FIXME: There might(should) be a better way of doing this computation!
4257 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004258 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004259 // The first two arguments (self and _cmd) are pointers; account for
4260 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004261 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004262 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004263 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004264 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004265 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004266 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004267 continue;
4268
Ken Dyck40775002010-01-11 17:06:35 +00004269 assert (sz.isPositive() &&
4270 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004271 ParmOffset += sz;
4272 }
Ken Dyck40775002010-01-11 17:06:35 +00004273 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004274 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004275 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004276
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004277 // Argument types.
4278 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004279 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004280 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004281 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004282 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004283 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004284 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4285 // Use array's original type only if it has known number of
4286 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004287 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004288 PType = PVDecl->getType();
4289 } else if (PType->isFunctionType())
4290 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004291 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4292 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004293 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004294 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004295 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004296
4297 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004298}
4299
Daniel Dunbar4932b362008-08-28 04:38:10 +00004300/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004301/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004302/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4303/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004304/// Property attributes are stored as a comma-delimited C string. The simple
4305/// attributes readonly and bycopy are encoded as single characters. The
4306/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4307/// encoded as single characters, followed by an identifier. Property types
4308/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004309/// these attributes are defined by the following enumeration:
4310/// @code
4311/// enum PropertyAttributes {
4312/// kPropertyReadOnly = 'R', // property is read-only.
4313/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4314/// kPropertyByref = '&', // property is a reference to the value last assigned
4315/// kPropertyDynamic = 'D', // property is dynamic
4316/// kPropertyGetter = 'G', // followed by getter selector name
4317/// kPropertySetter = 'S', // followed by setter selector name
4318/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004319/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004320/// kPropertyWeak = 'W' // 'weak' property
4321/// kPropertyStrong = 'P' // property GC'able
4322/// kPropertyNonAtomic = 'N' // property non-atomic
4323/// };
4324/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004325void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004326 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004327 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004328 // Collect information from the property implementation decl(s).
4329 bool Dynamic = false;
4330 ObjCPropertyImplDecl *SynthesizePID = 0;
4331
4332 // FIXME: Duplicated code due to poor abstraction.
4333 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004334 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004335 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4336 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004337 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004338 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004339 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004340 if (PID->getPropertyDecl() == PD) {
4341 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4342 Dynamic = true;
4343 } else {
4344 SynthesizePID = PID;
4345 }
4346 }
4347 }
4348 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004349 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004350 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004351 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004352 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004353 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004354 if (PID->getPropertyDecl() == PD) {
4355 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4356 Dynamic = true;
4357 } else {
4358 SynthesizePID = PID;
4359 }
4360 }
Mike Stump11289f42009-09-09 15:08:12 +00004361 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004362 }
4363 }
4364
4365 // FIXME: This is not very efficient.
4366 S = "T";
4367
4368 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004369 // GCC has some special rules regarding encoding of properties which
4370 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004371 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004372 true /* outermost type */,
4373 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004374
4375 if (PD->isReadOnly()) {
4376 S += ",R";
4377 } else {
4378 switch (PD->getSetterKind()) {
4379 case ObjCPropertyDecl::Assign: break;
4380 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004381 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004382 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004383 }
4384 }
4385
4386 // It really isn't clear at all what this means, since properties
4387 // are "dynamic by default".
4388 if (Dynamic)
4389 S += ",D";
4390
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004391 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4392 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004393
Daniel Dunbar4932b362008-08-28 04:38:10 +00004394 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4395 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004396 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004397 }
4398
4399 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4400 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004401 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004402 }
4403
4404 if (SynthesizePID) {
4405 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4406 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004407 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004408 }
4409
4410 // FIXME: OBJCGC: weak & strong
4411}
4412
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004413/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004414/// Another legacy compatibility encoding: 32-bit longs are encoded as
4415/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004416/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4417///
4418void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004419 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004420 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004421 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004422 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004423 else
Jay Foad39c79802011-01-12 09:06:06 +00004424 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004425 PointeeTy = IntTy;
4426 }
4427 }
4428}
4429
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004430void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004431 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004432 // We follow the behavior of gcc, expanding structures which are
4433 // directly pointed to, and expanding embedded structures. Note that
4434 // these rules are sufficient to prevent recursive encoding of the
4435 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004436 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004437 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004438}
4439
David Chisnallb190a2c2010-06-04 01:10:52 +00004440static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4441 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004442 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnallb190a2c2010-06-04 01:10:52 +00004443 case BuiltinType::Void: return 'v';
4444 case BuiltinType::Bool: return 'B';
4445 case BuiltinType::Char_U:
4446 case BuiltinType::UChar: return 'C';
4447 case BuiltinType::UShort: return 'S';
4448 case BuiltinType::UInt: return 'I';
4449 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004450 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004451 case BuiltinType::UInt128: return 'T';
4452 case BuiltinType::ULongLong: return 'Q';
4453 case BuiltinType::Char_S:
4454 case BuiltinType::SChar: return 'c';
4455 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004456 case BuiltinType::WChar_S:
4457 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004458 case BuiltinType::Int: return 'i';
4459 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004460 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004461 case BuiltinType::LongLong: return 'q';
4462 case BuiltinType::Int128: return 't';
4463 case BuiltinType::Float: return 'f';
4464 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004465 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004466 }
4467}
4468
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004469static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4470 EnumDecl *Enum = ET->getDecl();
4471
4472 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4473 if (!Enum->isFixed())
4474 return 'i';
4475
4476 // The encoding of a fixed enum type matches its fixed underlying type.
4477 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4478}
4479
Jay Foad39c79802011-01-12 09:06:06 +00004480static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004481 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00004482 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004483 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004484 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4485 // The GNU runtime requires more information; bitfields are encoded as b,
4486 // then the offset (in bits) of the first element, then the type of the
4487 // bitfield, then the size in bits. For example, in this structure:
4488 //
4489 // struct
4490 // {
4491 // int integer;
4492 // int flags:2;
4493 // };
4494 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4495 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4496 // information is not especially sensible, but we're stuck with it for
4497 // compatibility with GCC, although providing it breaks anything that
4498 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00004499 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004500 const RecordDecl *RD = FD->getParent();
4501 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004502 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004503 if (const EnumType *ET = T->getAs<EnumType>())
4504 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnall6f0a7d22010-12-26 20:12:30 +00004505 else
Jay Foad39c79802011-01-12 09:06:06 +00004506 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004507 }
Richard Smithcaf33902011-10-10 18:28:20 +00004508 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004509}
4510
Daniel Dunbar07d07852009-10-18 21:17:35 +00004511// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004512void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4513 bool ExpandPointedToStructures,
4514 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004515 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004516 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004517 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004518 bool StructField,
4519 bool EncodeBlockParameters,
4520 bool EncodeClassNames) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004521 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004522 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004523 return EncodeBitField(this, S, T, FD);
4524 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004525 return;
4526 }
Mike Stump11289f42009-09-09 15:08:12 +00004527
John McCall9dd450b2009-09-21 23:43:11 +00004528 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004529 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004530 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004531 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004532 return;
4533 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004534
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004535 // encoding for pointer or r3eference types.
4536 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004537 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004538 if (PT->isObjCSelType()) {
4539 S += ':';
4540 return;
4541 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004542 PointeeTy = PT->getPointeeType();
4543 }
4544 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4545 PointeeTy = RT->getPointeeType();
4546 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004547 bool isReadOnly = false;
4548 // For historical/compatibility reasons, the read-only qualifier of the
4549 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4550 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004551 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004552 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004553 if (OutermostType && T.isConstQualified()) {
4554 isReadOnly = true;
4555 S += 'r';
4556 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004557 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004558 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004559 while (P->getAs<PointerType>())
4560 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004561 if (P.isConstQualified()) {
4562 isReadOnly = true;
4563 S += 'r';
4564 }
4565 }
4566 if (isReadOnly) {
4567 // Another legacy compatibility encoding. Some ObjC qualifier and type
4568 // combinations need to be rearranged.
4569 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004570 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004571 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004572 }
Mike Stump11289f42009-09-09 15:08:12 +00004573
Anders Carlssond8499822007-10-29 05:01:08 +00004574 if (PointeeTy->isCharType()) {
4575 // char pointer types should be encoded as '*' unless it is a
4576 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004577 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004578 S += '*';
4579 return;
4580 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004581 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004582 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4583 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4584 S += '#';
4585 return;
4586 }
4587 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4588 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4589 S += '@';
4590 return;
4591 }
4592 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004593 }
Anders Carlssond8499822007-10-29 05:01:08 +00004594 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004595 getLegacyIntegralTypeEncoding(PointeeTy);
4596
Mike Stump11289f42009-09-09 15:08:12 +00004597 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004598 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004599 return;
4600 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004601
Chris Lattnere7cabb92009-07-13 00:10:46 +00004602 if (const ArrayType *AT =
4603 // Ignore type qualifiers etc.
4604 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004605 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004606 // Incomplete arrays are encoded as a pointer to the array element.
4607 S += '^';
4608
Mike Stump11289f42009-09-09 15:08:12 +00004609 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004610 false, ExpandStructures, FD);
4611 } else {
4612 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004613
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004614 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4615 if (getTypeSize(CAT->getElementType()) == 0)
4616 S += '0';
4617 else
4618 S += llvm::utostr(CAT->getSize().getZExtValue());
4619 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004620 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004621 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4622 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00004623 S += '0';
4624 }
Mike Stump11289f42009-09-09 15:08:12 +00004625
4626 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004627 false, ExpandStructures, FD);
4628 S += ']';
4629 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004630 return;
4631 }
Mike Stump11289f42009-09-09 15:08:12 +00004632
John McCall9dd450b2009-09-21 23:43:11 +00004633 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004634 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004635 return;
4636 }
Mike Stump11289f42009-09-09 15:08:12 +00004637
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004638 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004639 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004640 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004641 // Anonymous structures print as '?'
4642 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4643 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004644 if (ClassTemplateSpecializationDecl *Spec
4645 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4646 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4647 std::string TemplateArgsStr
4648 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004649 TemplateArgs.data(),
4650 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00004651 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004652
4653 S += TemplateArgsStr;
4654 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004655 } else {
4656 S += '?';
4657 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004658 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004659 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004660 if (!RDecl->isUnion()) {
4661 getObjCEncodingForStructureImpl(RDecl, S, FD);
4662 } else {
4663 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4664 FieldEnd = RDecl->field_end();
4665 Field != FieldEnd; ++Field) {
4666 if (FD) {
4667 S += '"';
4668 S += Field->getNameAsString();
4669 S += '"';
4670 }
Mike Stump11289f42009-09-09 15:08:12 +00004671
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004672 // Special case bit-fields.
4673 if (Field->isBitField()) {
4674 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00004675 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004676 } else {
4677 QualType qt = Field->getType();
4678 getLegacyIntegralTypeEncoding(qt);
4679 getObjCEncodingForTypeImpl(qt, S, false, true,
4680 FD, /*OutermostType*/false,
4681 /*EncodingProperty*/false,
4682 /*StructField*/true);
4683 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004684 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004685 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004686 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004687 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004688 return;
4689 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004690
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004691 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004692 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004693 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004694 else
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004695 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004696 return;
4697 }
Mike Stump11289f42009-09-09 15:08:12 +00004698
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004699 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004700 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004701 if (EncodeBlockParameters) {
4702 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4703
4704 S += '<';
4705 // Block return type
4706 getObjCEncodingForTypeImpl(FT->getResultType(), S,
4707 ExpandPointedToStructures, ExpandStructures,
4708 FD,
4709 false /* OutermostType */,
4710 EncodingProperty,
4711 false /* StructField */,
4712 EncodeBlockParameters,
4713 EncodeClassNames);
4714 // Block self
4715 S += "@?";
4716 // Block parameters
4717 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4718 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4719 E = FPT->arg_type_end(); I && (I != E); ++I) {
4720 getObjCEncodingForTypeImpl(*I, S,
4721 ExpandPointedToStructures,
4722 ExpandStructures,
4723 FD,
4724 false /* OutermostType */,
4725 EncodingProperty,
4726 false /* StructField */,
4727 EncodeBlockParameters,
4728 EncodeClassNames);
4729 }
4730 }
4731 S += '>';
4732 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004733 return;
4734 }
Mike Stump11289f42009-09-09 15:08:12 +00004735
John McCall8b07ec22010-05-15 11:32:37 +00004736 // Ignore protocol qualifiers when mangling at this level.
4737 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4738 T = OT->getBaseType();
4739
John McCall8ccfcb52009-09-24 19:53:00 +00004740 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004741 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004742 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004743 S += '{';
4744 const IdentifierInfo *II = OI->getIdentifier();
4745 S += II->getName();
4746 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00004747 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004748 DeepCollectObjCIvars(OI, true, Ivars);
4749 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004750 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004751 if (Field->isBitField())
4752 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004753 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004754 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004755 }
4756 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004757 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004758 }
Mike Stump11289f42009-09-09 15:08:12 +00004759
John McCall9dd450b2009-09-21 23:43:11 +00004760 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004761 if (OPT->isObjCIdType()) {
4762 S += '@';
4763 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004764 }
Mike Stump11289f42009-09-09 15:08:12 +00004765
Steve Narofff0c86112009-10-28 22:03:49 +00004766 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4767 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4768 // Since this is a binary compatibility issue, need to consult with runtime
4769 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004770 S += '#';
4771 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004772 }
Mike Stump11289f42009-09-09 15:08:12 +00004773
Chris Lattnere7cabb92009-07-13 00:10:46 +00004774 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004775 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004776 ExpandPointedToStructures,
4777 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004778 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004779 // Note that we do extended encoding of protocol qualifer list
4780 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004781 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004782 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4783 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004784 S += '<';
4785 S += (*I)->getNameAsString();
4786 S += '>';
4787 }
4788 S += '"';
4789 }
4790 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004791 }
Mike Stump11289f42009-09-09 15:08:12 +00004792
Chris Lattnere7cabb92009-07-13 00:10:46 +00004793 QualType PointeeTy = OPT->getPointeeType();
4794 if (!EncodingProperty &&
4795 isa<TypedefType>(PointeeTy.getTypePtr())) {
4796 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004797 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004798 // {...};
4799 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004800 getObjCEncodingForTypeImpl(PointeeTy, S,
4801 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004802 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004803 return;
4804 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004805
4806 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004807 if (OPT->getInterfaceDecl() &&
4808 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004809 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004810 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004811 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4812 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004813 S += '<';
4814 S += (*I)->getNameAsString();
4815 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004816 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004817 S += '"';
4818 }
4819 return;
4820 }
Mike Stump11289f42009-09-09 15:08:12 +00004821
John McCalla9e6e8d2010-05-17 23:56:34 +00004822 // gcc just blithely ignores member pointers.
4823 // TODO: maybe there should be a mangling for these
4824 if (T->getAs<MemberPointerType>())
4825 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004826
4827 if (T->isVectorType()) {
4828 // This matches gcc's encoding, even though technically it is
4829 // insufficient.
4830 // FIXME. We should do a better job than gcc.
4831 return;
4832 }
4833
David Blaikie83d382b2011-09-23 05:06:16 +00004834 llvm_unreachable("@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004835}
4836
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004837void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4838 std::string &S,
4839 const FieldDecl *FD,
4840 bool includeVBases) const {
4841 assert(RDecl && "Expected non-null RecordDecl");
4842 assert(!RDecl->isUnion() && "Should not be called for unions");
4843 if (!RDecl->getDefinition())
4844 return;
4845
4846 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4847 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4848 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4849
4850 if (CXXRec) {
4851 for (CXXRecordDecl::base_class_iterator
4852 BI = CXXRec->bases_begin(),
4853 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4854 if (!BI->isVirtual()) {
4855 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004856 if (base->isEmpty())
4857 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00004858 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004859 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4860 std::make_pair(offs, base));
4861 }
4862 }
4863 }
4864
4865 unsigned i = 0;
4866 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4867 FieldEnd = RDecl->field_end();
4868 Field != FieldEnd; ++Field, ++i) {
4869 uint64_t offs = layout.getFieldOffset(i);
4870 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00004871 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004872 }
4873
4874 if (CXXRec && includeVBases) {
4875 for (CXXRecordDecl::base_class_iterator
4876 BI = CXXRec->vbases_begin(),
4877 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4878 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004879 if (base->isEmpty())
4880 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00004881 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00004882 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4883 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4884 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004885 }
4886 }
4887
4888 CharUnits size;
4889 if (CXXRec) {
4890 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4891 } else {
4892 size = layout.getSize();
4893 }
4894
4895 uint64_t CurOffs = 0;
4896 std::multimap<uint64_t, NamedDecl *>::iterator
4897 CurLayObj = FieldOrBaseOffsets.begin();
4898
Douglas Gregorf5d6c742012-04-27 22:30:01 +00004899 if (CXXRec && CXXRec->isDynamicClass() &&
4900 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004901 if (FD) {
4902 S += "\"_vptr$";
4903 std::string recname = CXXRec->getNameAsString();
4904 if (recname.empty()) recname = "?";
4905 S += recname;
4906 S += '"';
4907 }
4908 S += "^^?";
4909 CurOffs += getTypeSize(VoidPtrTy);
4910 }
4911
4912 if (!RDecl->hasFlexibleArrayMember()) {
4913 // Mark the end of the structure.
4914 uint64_t offs = toBits(size);
4915 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4916 std::make_pair(offs, (NamedDecl*)0));
4917 }
4918
4919 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4920 assert(CurOffs <= CurLayObj->first);
4921
4922 if (CurOffs < CurLayObj->first) {
4923 uint64_t padding = CurLayObj->first - CurOffs;
4924 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4925 // packing/alignment of members is different that normal, in which case
4926 // the encoding will be out-of-sync with the real layout.
4927 // If the runtime switches to just consider the size of types without
4928 // taking into account alignment, we could make padding explicit in the
4929 // encoding (e.g. using arrays of chars). The encoding strings would be
4930 // longer then though.
4931 CurOffs += padding;
4932 }
4933
4934 NamedDecl *dcl = CurLayObj->second;
4935 if (dcl == 0)
4936 break; // reached end of structure.
4937
4938 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4939 // We expand the bases without their virtual bases since those are going
4940 // in the initial structure. Note that this differs from gcc which
4941 // expands virtual bases each time one is encountered in the hierarchy,
4942 // making the encoding type bigger than it really is.
4943 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004944 assert(!base->isEmpty());
4945 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004946 } else {
4947 FieldDecl *field = cast<FieldDecl>(dcl);
4948 if (FD) {
4949 S += '"';
4950 S += field->getNameAsString();
4951 S += '"';
4952 }
4953
4954 if (field->isBitField()) {
4955 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00004956 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004957 } else {
4958 QualType qt = field->getType();
4959 getLegacyIntegralTypeEncoding(qt);
4960 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4961 /*OutermostType*/false,
4962 /*EncodingProperty*/false,
4963 /*StructField*/true);
4964 CurOffs += getTypeSize(field->getType());
4965 }
4966 }
4967 }
4968}
4969
Mike Stump11289f42009-09-09 15:08:12 +00004970void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004971 std::string& S) const {
4972 if (QT & Decl::OBJC_TQ_In)
4973 S += 'n';
4974 if (QT & Decl::OBJC_TQ_Inout)
4975 S += 'N';
4976 if (QT & Decl::OBJC_TQ_Out)
4977 S += 'o';
4978 if (QT & Decl::OBJC_TQ_Bycopy)
4979 S += 'O';
4980 if (QT & Decl::OBJC_TQ_Byref)
4981 S += 'R';
4982 if (QT & Decl::OBJC_TQ_Oneway)
4983 S += 'V';
4984}
4985
Douglas Gregor3ea72692011-08-12 05:46:01 +00004986TypedefDecl *ASTContext::getObjCIdDecl() const {
4987 if (!ObjCIdDecl) {
4988 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
4989 T = getObjCObjectPointerType(T);
4990 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
4991 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4992 getTranslationUnitDecl(),
4993 SourceLocation(), SourceLocation(),
4994 &Idents.get("id"), IdInfo);
4995 }
4996
4997 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00004998}
4999
Douglas Gregor52e02802011-08-12 06:17:30 +00005000TypedefDecl *ASTContext::getObjCSelDecl() const {
5001 if (!ObjCSelDecl) {
5002 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5003 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5004 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5005 getTranslationUnitDecl(),
5006 SourceLocation(), SourceLocation(),
5007 &Idents.get("SEL"), SelInfo);
5008 }
5009 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005010}
5011
Douglas Gregor0a586182011-08-12 05:59:41 +00005012TypedefDecl *ASTContext::getObjCClassDecl() const {
5013 if (!ObjCClassDecl) {
5014 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5015 T = getObjCObjectPointerType(T);
5016 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5017 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5018 getTranslationUnitDecl(),
5019 SourceLocation(), SourceLocation(),
5020 &Idents.get("Class"), ClassInfo);
5021 }
5022
5023 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005024}
5025
Douglas Gregord53ae832012-01-17 18:09:05 +00005026ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5027 if (!ObjCProtocolClassDecl) {
5028 ObjCProtocolClassDecl
5029 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5030 SourceLocation(),
5031 &Idents.get("Protocol"),
5032 /*PrevDecl=*/0,
5033 SourceLocation(), true);
5034 }
5035
5036 return ObjCProtocolClassDecl;
5037}
5038
Meador Inge5d3fb222012-06-16 03:34:49 +00005039//===----------------------------------------------------------------------===//
5040// __builtin_va_list Construction Functions
5041//===----------------------------------------------------------------------===//
5042
5043static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5044 // typedef char* __builtin_va_list;
5045 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5046 TypeSourceInfo *TInfo
5047 = Context->getTrivialTypeSourceInfo(CharPtrType);
5048
5049 TypedefDecl *VaListTypeDecl
5050 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5051 Context->getTranslationUnitDecl(),
5052 SourceLocation(), SourceLocation(),
5053 &Context->Idents.get("__builtin_va_list"),
5054 TInfo);
5055 return VaListTypeDecl;
5056}
5057
5058static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5059 // typedef void* __builtin_va_list;
5060 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5061 TypeSourceInfo *TInfo
5062 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5063
5064 TypedefDecl *VaListTypeDecl
5065 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5066 Context->getTranslationUnitDecl(),
5067 SourceLocation(), SourceLocation(),
5068 &Context->Idents.get("__builtin_va_list"),
5069 TInfo);
5070 return VaListTypeDecl;
5071}
5072
5073static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5074 // typedef struct __va_list_tag {
5075 RecordDecl *VaListTagDecl;
5076
5077 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5078 Context->getTranslationUnitDecl(),
5079 &Context->Idents.get("__va_list_tag"));
5080 VaListTagDecl->startDefinition();
5081
5082 const size_t NumFields = 5;
5083 QualType FieldTypes[NumFields];
5084 const char *FieldNames[NumFields];
5085
5086 // unsigned char gpr;
5087 FieldTypes[0] = Context->UnsignedCharTy;
5088 FieldNames[0] = "gpr";
5089
5090 // unsigned char fpr;
5091 FieldTypes[1] = Context->UnsignedCharTy;
5092 FieldNames[1] = "fpr";
5093
5094 // unsigned short reserved;
5095 FieldTypes[2] = Context->UnsignedShortTy;
5096 FieldNames[2] = "reserved";
5097
5098 // void* overflow_arg_area;
5099 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5100 FieldNames[3] = "overflow_arg_area";
5101
5102 // void* reg_save_area;
5103 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5104 FieldNames[4] = "reg_save_area";
5105
5106 // Create fields
5107 for (unsigned i = 0; i < NumFields; ++i) {
5108 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5109 SourceLocation(),
5110 SourceLocation(),
5111 &Context->Idents.get(FieldNames[i]),
5112 FieldTypes[i], /*TInfo=*/0,
5113 /*BitWidth=*/0,
5114 /*Mutable=*/false,
5115 ICIS_NoInit);
5116 Field->setAccess(AS_public);
5117 VaListTagDecl->addDecl(Field);
5118 }
5119 VaListTagDecl->completeDefinition();
5120 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005121 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005122
5123 // } __va_list_tag;
5124 TypedefDecl *VaListTagTypedefDecl
5125 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5126 Context->getTranslationUnitDecl(),
5127 SourceLocation(), SourceLocation(),
5128 &Context->Idents.get("__va_list_tag"),
5129 Context->getTrivialTypeSourceInfo(VaListTagType));
5130 QualType VaListTagTypedefType =
5131 Context->getTypedefType(VaListTagTypedefDecl);
5132
5133 // typedef __va_list_tag __builtin_va_list[1];
5134 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5135 QualType VaListTagArrayType
5136 = Context->getConstantArrayType(VaListTagTypedefType,
5137 Size, ArrayType::Normal, 0);
5138 TypeSourceInfo *TInfo
5139 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5140 TypedefDecl *VaListTypedefDecl
5141 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5142 Context->getTranslationUnitDecl(),
5143 SourceLocation(), SourceLocation(),
5144 &Context->Idents.get("__builtin_va_list"),
5145 TInfo);
5146
5147 return VaListTypedefDecl;
5148}
5149
5150static TypedefDecl *
5151CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5152 // typedef struct __va_list_tag {
5153 RecordDecl *VaListTagDecl;
5154 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5155 Context->getTranslationUnitDecl(),
5156 &Context->Idents.get("__va_list_tag"));
5157 VaListTagDecl->startDefinition();
5158
5159 const size_t NumFields = 4;
5160 QualType FieldTypes[NumFields];
5161 const char *FieldNames[NumFields];
5162
5163 // unsigned gp_offset;
5164 FieldTypes[0] = Context->UnsignedIntTy;
5165 FieldNames[0] = "gp_offset";
5166
5167 // unsigned fp_offset;
5168 FieldTypes[1] = Context->UnsignedIntTy;
5169 FieldNames[1] = "fp_offset";
5170
5171 // void* overflow_arg_area;
5172 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5173 FieldNames[2] = "overflow_arg_area";
5174
5175 // void* reg_save_area;
5176 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5177 FieldNames[3] = "reg_save_area";
5178
5179 // Create fields
5180 for (unsigned i = 0; i < NumFields; ++i) {
5181 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5182 VaListTagDecl,
5183 SourceLocation(),
5184 SourceLocation(),
5185 &Context->Idents.get(FieldNames[i]),
5186 FieldTypes[i], /*TInfo=*/0,
5187 /*BitWidth=*/0,
5188 /*Mutable=*/false,
5189 ICIS_NoInit);
5190 Field->setAccess(AS_public);
5191 VaListTagDecl->addDecl(Field);
5192 }
5193 VaListTagDecl->completeDefinition();
5194 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005195 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005196
5197 // } __va_list_tag;
5198 TypedefDecl *VaListTagTypedefDecl
5199 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5200 Context->getTranslationUnitDecl(),
5201 SourceLocation(), SourceLocation(),
5202 &Context->Idents.get("__va_list_tag"),
5203 Context->getTrivialTypeSourceInfo(VaListTagType));
5204 QualType VaListTagTypedefType =
5205 Context->getTypedefType(VaListTagTypedefDecl);
5206
5207 // typedef __va_list_tag __builtin_va_list[1];
5208 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5209 QualType VaListTagArrayType
5210 = Context->getConstantArrayType(VaListTagTypedefType,
5211 Size, ArrayType::Normal,0);
5212 TypeSourceInfo *TInfo
5213 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5214 TypedefDecl *VaListTypedefDecl
5215 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5216 Context->getTranslationUnitDecl(),
5217 SourceLocation(), SourceLocation(),
5218 &Context->Idents.get("__builtin_va_list"),
5219 TInfo);
5220
5221 return VaListTypedefDecl;
5222}
5223
5224static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5225 // typedef int __builtin_va_list[4];
5226 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5227 QualType IntArrayType
5228 = Context->getConstantArrayType(Context->IntTy,
5229 Size, ArrayType::Normal, 0);
5230 TypedefDecl *VaListTypedefDecl
5231 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5232 Context->getTranslationUnitDecl(),
5233 SourceLocation(), SourceLocation(),
5234 &Context->Idents.get("__builtin_va_list"),
5235 Context->getTrivialTypeSourceInfo(IntArrayType));
5236
5237 return VaListTypedefDecl;
5238}
5239
5240static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5241 TargetInfo::BuiltinVaListKind Kind) {
5242 switch (Kind) {
5243 case TargetInfo::CharPtrBuiltinVaList:
5244 return CreateCharPtrBuiltinVaListDecl(Context);
5245 case TargetInfo::VoidPtrBuiltinVaList:
5246 return CreateVoidPtrBuiltinVaListDecl(Context);
5247 case TargetInfo::PowerABIBuiltinVaList:
5248 return CreatePowerABIBuiltinVaListDecl(Context);
5249 case TargetInfo::X86_64ABIBuiltinVaList:
5250 return CreateX86_64ABIBuiltinVaListDecl(Context);
5251 case TargetInfo::PNaClABIBuiltinVaList:
5252 return CreatePNaClABIBuiltinVaListDecl(Context);
5253 }
5254
5255 llvm_unreachable("Unhandled __builtin_va_list type kind");
5256}
5257
5258TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5259 if (!BuiltinVaListDecl)
5260 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5261
5262 return BuiltinVaListDecl;
5263}
5264
Meador Ingecfb60902012-07-01 15:57:25 +00005265QualType ASTContext::getVaListTagType() const {
5266 // Force the creation of VaListTagTy by building the __builtin_va_list
5267 // declaration.
5268 if (VaListTagTy.isNull())
5269 (void) getBuiltinVaListDecl();
5270
5271 return VaListTagTy;
5272}
5273
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005274void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00005275 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00005276 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00005277
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005278 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00005279}
5280
John McCalld28ae272009-12-02 08:04:21 +00005281/// \brief Retrieve the template name that corresponds to a non-empty
5282/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00005283TemplateName
5284ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5285 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00005286 unsigned size = End - Begin;
5287 assert(size > 1 && "set is not overloaded!");
5288
5289 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5290 size * sizeof(FunctionTemplateDecl*));
5291 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5292
5293 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00005294 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00005295 NamedDecl *D = *I;
5296 assert(isa<FunctionTemplateDecl>(D) ||
5297 (isa<UsingShadowDecl>(D) &&
5298 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5299 *Storage++ = D;
5300 }
5301
5302 return TemplateName(OT);
5303}
5304
Douglas Gregordc572a32009-03-30 22:58:21 +00005305/// \brief Retrieve the template name that represents a qualified
5306/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00005307TemplateName
5308ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5309 bool TemplateKeyword,
5310 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00005311 assert(NNS && "Missing nested-name-specifier in qualified template name");
5312
Douglas Gregorc42075a2010-02-04 18:10:26 +00005313 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00005314 llvm::FoldingSetNodeID ID;
5315 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5316
5317 void *InsertPos = 0;
5318 QualifiedTemplateName *QTN =
5319 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5320 if (!QTN) {
5321 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
5322 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5323 }
5324
5325 return TemplateName(QTN);
5326}
5327
5328/// \brief Retrieve the template name that represents a dependent
5329/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00005330TemplateName
5331ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5332 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00005333 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00005334 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00005335
5336 llvm::FoldingSetNodeID ID;
5337 DependentTemplateName::Profile(ID, NNS, Name);
5338
5339 void *InsertPos = 0;
5340 DependentTemplateName *QTN =
5341 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5342
5343 if (QTN)
5344 return TemplateName(QTN);
5345
5346 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5347 if (CanonNNS == NNS) {
5348 QTN = new (*this,4) DependentTemplateName(NNS, Name);
5349 } else {
5350 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
5351 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005352 DependentTemplateName *CheckQTN =
5353 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5354 assert(!CheckQTN && "Dependent type name canonicalization broken");
5355 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00005356 }
5357
5358 DependentTemplateNames.InsertNode(QTN, InsertPos);
5359 return TemplateName(QTN);
5360}
5361
Douglas Gregor71395fa2009-11-04 00:56:37 +00005362/// \brief Retrieve the template name that represents a dependent
5363/// template name such as \c MetaFun::template operator+.
5364TemplateName
5365ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00005366 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00005367 assert((!NNS || NNS->isDependent()) &&
5368 "Nested name specifier must be dependent");
5369
5370 llvm::FoldingSetNodeID ID;
5371 DependentTemplateName::Profile(ID, NNS, Operator);
5372
5373 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00005374 DependentTemplateName *QTN
5375 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005376
5377 if (QTN)
5378 return TemplateName(QTN);
5379
5380 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5381 if (CanonNNS == NNS) {
5382 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
5383 } else {
5384 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
5385 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005386
5387 DependentTemplateName *CheckQTN
5388 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5389 assert(!CheckQTN && "Dependent template name canonicalization broken");
5390 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00005391 }
5392
5393 DependentTemplateNames.InsertNode(QTN, InsertPos);
5394 return TemplateName(QTN);
5395}
5396
Douglas Gregor5590be02011-01-15 06:45:20 +00005397TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00005398ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5399 TemplateName replacement) const {
5400 llvm::FoldingSetNodeID ID;
5401 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5402
5403 void *insertPos = 0;
5404 SubstTemplateTemplateParmStorage *subst
5405 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5406
5407 if (!subst) {
5408 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5409 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5410 }
5411
5412 return TemplateName(subst);
5413}
5414
5415TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00005416ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5417 const TemplateArgument &ArgPack) const {
5418 ASTContext &Self = const_cast<ASTContext &>(*this);
5419 llvm::FoldingSetNodeID ID;
5420 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5421
5422 void *InsertPos = 0;
5423 SubstTemplateTemplateParmPackStorage *Subst
5424 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5425
5426 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00005427 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00005428 ArgPack.pack_size(),
5429 ArgPack.pack_begin());
5430 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5431 }
5432
5433 return TemplateName(Subst);
5434}
5435
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005436/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00005437/// TargetInfo, produce the corresponding type. The unsigned @p Type
5438/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00005439CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005440 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00005441 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005442 case TargetInfo::SignedShort: return ShortTy;
5443 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5444 case TargetInfo::SignedInt: return IntTy;
5445 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5446 case TargetInfo::SignedLong: return LongTy;
5447 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5448 case TargetInfo::SignedLongLong: return LongLongTy;
5449 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5450 }
5451
David Blaikie83d382b2011-09-23 05:06:16 +00005452 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005453}
Ted Kremenek77c51b22008-07-24 23:58:27 +00005454
5455//===----------------------------------------------------------------------===//
5456// Type Predicates.
5457//===----------------------------------------------------------------------===//
5458
Fariborz Jahanian96207692009-02-18 21:49:28 +00005459/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5460/// garbage collection attribute.
5461///
John McCall553d45a2011-01-12 00:34:59 +00005462Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005463 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00005464 return Qualifiers::GCNone;
5465
David Blaikiebbafb8a2012-03-11 07:00:24 +00005466 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00005467 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5468
5469 // Default behaviour under objective-C's gc is for ObjC pointers
5470 // (or pointers to them) be treated as though they were declared
5471 // as __strong.
5472 if (GCAttrs == Qualifiers::GCNone) {
5473 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5474 return Qualifiers::Strong;
5475 else if (Ty->isPointerType())
5476 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5477 } else {
5478 // It's not valid to set GC attributes on anything that isn't a
5479 // pointer.
5480#ifndef NDEBUG
5481 QualType CT = Ty->getCanonicalTypeInternal();
5482 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5483 CT = AT->getElementType();
5484 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5485#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00005486 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00005487 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00005488}
5489
Chris Lattner49af6a42008-04-07 06:51:04 +00005490//===----------------------------------------------------------------------===//
5491// Type Compatibility Testing
5492//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00005493
Mike Stump11289f42009-09-09 15:08:12 +00005494/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005495/// compatible.
5496static bool areCompatVectorTypes(const VectorType *LHS,
5497 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00005498 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00005499 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00005500 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00005501}
5502
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005503bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5504 QualType SecondVec) {
5505 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5506 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5507
5508 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5509 return true;
5510
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005511 // Treat Neon vector types and most AltiVec vector types as if they are the
5512 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005513 const VectorType *First = FirstVec->getAs<VectorType>();
5514 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005515 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005516 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005517 First->getVectorKind() != VectorType::AltiVecPixel &&
5518 First->getVectorKind() != VectorType::AltiVecBool &&
5519 Second->getVectorKind() != VectorType::AltiVecPixel &&
5520 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005521 return true;
5522
5523 return false;
5524}
5525
Steve Naroff8e6aee52009-07-23 01:01:38 +00005526//===----------------------------------------------------------------------===//
5527// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5528//===----------------------------------------------------------------------===//
5529
5530/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5531/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00005532bool
5533ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5534 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00005535 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005536 return true;
5537 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5538 E = rProto->protocol_end(); PI != E; ++PI)
5539 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5540 return true;
5541 return false;
5542}
5543
Steve Naroff8e6aee52009-07-23 01:01:38 +00005544/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5545/// return true if lhs's protocols conform to rhs's protocol; false
5546/// otherwise.
5547bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5548 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5549 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5550 return false;
5551}
5552
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005553/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5554/// Class<p1, ...>.
5555bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5556 QualType rhs) {
5557 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5558 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5559 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5560
5561 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5562 E = lhsQID->qual_end(); I != E; ++I) {
5563 bool match = false;
5564 ObjCProtocolDecl *lhsProto = *I;
5565 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5566 E = rhsOPT->qual_end(); J != E; ++J) {
5567 ObjCProtocolDecl *rhsProto = *J;
5568 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5569 match = true;
5570 break;
5571 }
5572 }
5573 if (!match)
5574 return false;
5575 }
5576 return true;
5577}
5578
Steve Naroff8e6aee52009-07-23 01:01:38 +00005579/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5580/// ObjCQualifiedIDType.
5581bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5582 bool compare) {
5583 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00005584 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005585 lhs->isObjCIdType() || lhs->isObjCClassType())
5586 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005587 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005588 rhs->isObjCIdType() || rhs->isObjCClassType())
5589 return true;
5590
5591 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00005592 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005593
Steve Naroff8e6aee52009-07-23 01:01:38 +00005594 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00005595
Steve Naroff8e6aee52009-07-23 01:01:38 +00005596 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005597 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005598 // make sure we check the class hierarchy.
5599 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5600 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5601 E = lhsQID->qual_end(); I != E; ++I) {
5602 // when comparing an id<P> on lhs with a static type on rhs,
5603 // see if static class implements all of id's protocols, directly or
5604 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005605 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005606 return false;
5607 }
5608 }
5609 // If there are no qualifiers and no interface, we have an 'id'.
5610 return true;
5611 }
Mike Stump11289f42009-09-09 15:08:12 +00005612 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005613 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5614 E = lhsQID->qual_end(); I != E; ++I) {
5615 ObjCProtocolDecl *lhsProto = *I;
5616 bool match = false;
5617
5618 // when comparing an id<P> on lhs with a static type on rhs,
5619 // see if static class implements all of id's protocols, directly or
5620 // through its super class and categories.
5621 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5622 E = rhsOPT->qual_end(); J != E; ++J) {
5623 ObjCProtocolDecl *rhsProto = *J;
5624 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5625 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5626 match = true;
5627 break;
5628 }
5629 }
Mike Stump11289f42009-09-09 15:08:12 +00005630 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005631 // make sure we check the class hierarchy.
5632 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5633 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5634 E = lhsQID->qual_end(); I != E; ++I) {
5635 // when comparing an id<P> on lhs with a static type on rhs,
5636 // see if static class implements all of id's protocols, directly or
5637 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005638 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005639 match = true;
5640 break;
5641 }
5642 }
5643 }
5644 if (!match)
5645 return false;
5646 }
Mike Stump11289f42009-09-09 15:08:12 +00005647
Steve Naroff8e6aee52009-07-23 01:01:38 +00005648 return true;
5649 }
Mike Stump11289f42009-09-09 15:08:12 +00005650
Steve Naroff8e6aee52009-07-23 01:01:38 +00005651 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5652 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5653
Mike Stump11289f42009-09-09 15:08:12 +00005654 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00005655 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005656 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005657 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5658 E = lhsOPT->qual_end(); I != E; ++I) {
5659 ObjCProtocolDecl *lhsProto = *I;
5660 bool match = false;
5661
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005662 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00005663 // see if static class implements all of id's protocols, directly or
5664 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005665 // First, lhs protocols in the qualifier list must be found, direct
5666 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005667 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5668 E = rhsQID->qual_end(); J != E; ++J) {
5669 ObjCProtocolDecl *rhsProto = *J;
5670 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5671 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5672 match = true;
5673 break;
5674 }
5675 }
5676 if (!match)
5677 return false;
5678 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005679
5680 // Static class's protocols, or its super class or category protocols
5681 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5682 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5683 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5684 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5685 // This is rather dubious but matches gcc's behavior. If lhs has
5686 // no type qualifier and its class has no static protocol(s)
5687 // assume that it is mismatch.
5688 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5689 return false;
5690 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5691 LHSInheritedProtocols.begin(),
5692 E = LHSInheritedProtocols.end(); I != E; ++I) {
5693 bool match = false;
5694 ObjCProtocolDecl *lhsProto = (*I);
5695 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5696 E = rhsQID->qual_end(); J != E; ++J) {
5697 ObjCProtocolDecl *rhsProto = *J;
5698 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5699 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5700 match = true;
5701 break;
5702 }
5703 }
5704 if (!match)
5705 return false;
5706 }
5707 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00005708 return true;
5709 }
5710 return false;
5711}
5712
Eli Friedman47f77112008-08-22 00:56:42 +00005713/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005714/// compatible for assignment from RHS to LHS. This handles validation of any
5715/// protocol qualifiers on the LHS or RHS.
5716///
Steve Naroff7cae42b2009-07-10 23:34:53 +00005717bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5718 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00005719 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5720 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5721
Steve Naroff1329fa02009-07-15 18:40:39 +00005722 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00005723 if (LHS->isObjCUnqualifiedIdOrClass() ||
5724 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00005725 return true;
5726
John McCall8b07ec22010-05-15 11:32:37 +00005727 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00005728 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5729 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00005730 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005731
5732 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5733 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5734 QualType(RHSOPT,0));
5735
John McCall8b07ec22010-05-15 11:32:37 +00005736 // If we have 2 user-defined types, fall into that path.
5737 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00005738 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005739
Steve Naroff8e6aee52009-07-23 01:01:38 +00005740 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005741}
5742
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005743/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00005744/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005745/// arguments in block literals. When passed as arguments, passing 'A*' where
5746/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5747/// not OK. For the return type, the opposite is not OK.
5748bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5749 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005750 const ObjCObjectPointerType *RHSOPT,
5751 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005752 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005753 return true;
5754
5755 if (LHSOPT->isObjCBuiltinType()) {
5756 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5757 }
5758
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005759 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005760 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5761 QualType(RHSOPT,0),
5762 false);
5763
5764 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5765 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5766 if (LHS && RHS) { // We have 2 user-defined types.
5767 if (LHS != RHS) {
5768 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005769 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005770 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005771 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005772 }
5773 else
5774 return true;
5775 }
5776 return false;
5777}
5778
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005779/// getIntersectionOfProtocols - This routine finds the intersection of set
5780/// of protocols inherited from two distinct objective-c pointer objects.
5781/// It is used to build composite qualifier list of the composite type of
5782/// the conditional expression involving two objective-c pointer objects.
5783static
5784void getIntersectionOfProtocols(ASTContext &Context,
5785 const ObjCObjectPointerType *LHSOPT,
5786 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005787 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005788
John McCall8b07ec22010-05-15 11:32:37 +00005789 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5790 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5791 assert(LHS->getInterface() && "LHS must have an interface base");
5792 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005793
5794 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5795 unsigned LHSNumProtocols = LHS->getNumProtocols();
5796 if (LHSNumProtocols > 0)
5797 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5798 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005799 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005800 Context.CollectInheritedProtocols(LHS->getInterface(),
5801 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005802 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5803 LHSInheritedProtocols.end());
5804 }
5805
5806 unsigned RHSNumProtocols = RHS->getNumProtocols();
5807 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00005808 ObjCProtocolDecl **RHSProtocols =
5809 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005810 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5811 if (InheritedProtocolSet.count(RHSProtocols[i]))
5812 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00005813 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005814 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005815 Context.CollectInheritedProtocols(RHS->getInterface(),
5816 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005817 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5818 RHSInheritedProtocols.begin(),
5819 E = RHSInheritedProtocols.end(); I != E; ++I)
5820 if (InheritedProtocolSet.count((*I)))
5821 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005822 }
5823}
5824
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005825/// areCommonBaseCompatible - Returns common base class of the two classes if
5826/// one found. Note that this is O'2 algorithm. But it will be called as the
5827/// last type comparison in a ?-exp of ObjC pointer types before a
5828/// warning is issued. So, its invokation is extremely rare.
5829QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00005830 const ObjCObjectPointerType *Lptr,
5831 const ObjCObjectPointerType *Rptr) {
5832 const ObjCObjectType *LHS = Lptr->getObjectType();
5833 const ObjCObjectType *RHS = Rptr->getObjectType();
5834 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5835 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00005836 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005837 return QualType();
5838
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005839 do {
John McCall8b07ec22010-05-15 11:32:37 +00005840 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005841 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005842 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00005843 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5844
5845 QualType Result = QualType(LHS, 0);
5846 if (!Protocols.empty())
5847 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5848 Result = getObjCObjectPointerType(Result);
5849 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005850 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005851 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005852
5853 return QualType();
5854}
5855
John McCall8b07ec22010-05-15 11:32:37 +00005856bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5857 const ObjCObjectType *RHS) {
5858 assert(LHS->getInterface() && "LHS is not an interface type");
5859 assert(RHS->getInterface() && "RHS is not an interface type");
5860
Chris Lattner49af6a42008-04-07 06:51:04 +00005861 // Verify that the base decls are compatible: the RHS must be a subclass of
5862 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00005863 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00005864 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005865
Chris Lattner49af6a42008-04-07 06:51:04 +00005866 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5867 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00005868 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00005869 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005870
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005871 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5872 // more detailed analysis is required.
5873 if (RHS->getNumProtocols() == 0) {
5874 // OK, if LHS is a superclass of RHS *and*
5875 // this superclass is assignment compatible with LHS.
5876 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005877 bool IsSuperClass =
5878 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5879 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005880 // OK if conversion of LHS to SuperClass results in narrowing of types
5881 // ; i.e., SuperClass may implement at least one of the protocols
5882 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5883 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5884 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005885 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005886 // If super class has no protocols, it is not a match.
5887 if (SuperClassInheritedProtocols.empty())
5888 return false;
5889
5890 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5891 LHSPE = LHS->qual_end();
5892 LHSPI != LHSPE; LHSPI++) {
5893 bool SuperImplementsProtocol = false;
5894 ObjCProtocolDecl *LHSProto = (*LHSPI);
5895
5896 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5897 SuperClassInheritedProtocols.begin(),
5898 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5899 ObjCProtocolDecl *SuperClassProto = (*I);
5900 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5901 SuperImplementsProtocol = true;
5902 break;
5903 }
5904 }
5905 if (!SuperImplementsProtocol)
5906 return false;
5907 }
5908 return true;
5909 }
5910 return false;
5911 }
Mike Stump11289f42009-09-09 15:08:12 +00005912
John McCall8b07ec22010-05-15 11:32:37 +00005913 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5914 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00005915 LHSPI != LHSPE; LHSPI++) {
5916 bool RHSImplementsProtocol = false;
5917
5918 // If the RHS doesn't implement the protocol on the left, the types
5919 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00005920 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5921 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00005922 RHSPI != RHSPE; RHSPI++) {
5923 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00005924 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00005925 break;
5926 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005927 }
5928 // FIXME: For better diagnostics, consider passing back the protocol name.
5929 if (!RHSImplementsProtocol)
5930 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00005931 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005932 // The RHS implements all protocols listed on the LHS.
5933 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00005934}
5935
Steve Naroffb7605152009-02-12 17:52:19 +00005936bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5937 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00005938 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5939 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005940
Steve Naroff7cae42b2009-07-10 23:34:53 +00005941 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00005942 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005943
5944 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5945 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00005946}
5947
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005948bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5949 return canAssignObjCInterfaces(
5950 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5951 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5952}
5953
Mike Stump11289f42009-09-09 15:08:12 +00005954/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00005955/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00005956/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00005957/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005958bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5959 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005960 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00005961 return hasSameType(LHS, RHS);
5962
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005963 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00005964}
5965
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00005966bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00005967 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00005968}
5969
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005970bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5971 return !mergeTypes(LHS, RHS, true).isNull();
5972}
5973
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005974/// mergeTransparentUnionType - if T is a transparent union type and a member
5975/// of T is compatible with SubType, return the merged type, else return
5976/// QualType()
5977QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5978 bool OfBlockPointer,
5979 bool Unqualified) {
5980 if (const RecordType *UT = T->getAsUnionType()) {
5981 RecordDecl *UD = UT->getDecl();
5982 if (UD->hasAttr<TransparentUnionAttr>()) {
5983 for (RecordDecl::field_iterator it = UD->field_begin(),
5984 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00005985 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005986 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5987 if (!MT.isNull())
5988 return MT;
5989 }
5990 }
5991 }
5992
5993 return QualType();
5994}
5995
5996/// mergeFunctionArgumentTypes - merge two types which appear as function
5997/// argument types
5998QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5999 bool OfBlockPointer,
6000 bool Unqualified) {
6001 // GNU extension: two types are compatible if they appear as a function
6002 // argument, one of the types is a transparent union type and the other
6003 // type is compatible with a union member
6004 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6005 Unqualified);
6006 if (!lmerge.isNull())
6007 return lmerge;
6008
6009 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6010 Unqualified);
6011 if (!rmerge.isNull())
6012 return rmerge;
6013
6014 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6015}
6016
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006017QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006018 bool OfBlockPointer,
6019 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006020 const FunctionType *lbase = lhs->getAs<FunctionType>();
6021 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006022 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6023 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006024 bool allLTypes = true;
6025 bool allRTypes = true;
6026
6027 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006028 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006029 if (OfBlockPointer) {
6030 QualType RHS = rbase->getResultType();
6031 QualType LHS = lbase->getResultType();
6032 bool UnqualifiedResult = Unqualified;
6033 if (!UnqualifiedResult)
6034 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006035 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006036 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006037 else
John McCall8c6b56f2010-12-15 01:06:38 +00006038 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6039 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006040 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006041
6042 if (Unqualified)
6043 retType = retType.getUnqualifiedType();
6044
6045 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6046 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6047 if (Unqualified) {
6048 LRetType = LRetType.getUnqualifiedType();
6049 RRetType = RRetType.getUnqualifiedType();
6050 }
6051
6052 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006053 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006054 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006055 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006056
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006057 // FIXME: double check this
6058 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6059 // rbase->getRegParmAttr() != 0 &&
6060 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006061 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6062 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006063
Douglas Gregor8c940862010-01-18 17:14:39 +00006064 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00006065 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00006066 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006067
John McCall8c6b56f2010-12-15 01:06:38 +00006068 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006069 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6070 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006071 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6072 return QualType();
6073
John McCall31168b02011-06-15 23:02:42 +00006074 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6075 return QualType();
6076
Fariborz Jahanian48c69102011-10-05 00:05:34 +00006077 // functypes which return are preferred over those that do not.
6078 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
6079 allLTypes = false;
6080 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
6081 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006082 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6083 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006084
John McCall31168b02011-06-15 23:02:42 +00006085 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006086
Eli Friedman47f77112008-08-22 00:56:42 +00006087 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006088 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6089 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006090 unsigned lproto_nargs = lproto->getNumArgs();
6091 unsigned rproto_nargs = rproto->getNumArgs();
6092
6093 // Compatible functions must have the same number of arguments
6094 if (lproto_nargs != rproto_nargs)
6095 return QualType();
6096
6097 // Variadic and non-variadic functions aren't compatible
6098 if (lproto->isVariadic() != rproto->isVariadic())
6099 return QualType();
6100
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006101 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6102 return QualType();
6103
Fariborz Jahanian97676972011-09-28 21:52:05 +00006104 if (LangOpts.ObjCAutoRefCount &&
6105 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6106 return QualType();
6107
Eli Friedman47f77112008-08-22 00:56:42 +00006108 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006109 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00006110 for (unsigned i = 0; i < lproto_nargs; i++) {
6111 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6112 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006113 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6114 OfBlockPointer,
6115 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006116 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006117
6118 if (Unqualified)
6119 argtype = argtype.getUnqualifiedType();
6120
Eli Friedman47f77112008-08-22 00:56:42 +00006121 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006122 if (Unqualified) {
6123 largtype = largtype.getUnqualifiedType();
6124 rargtype = rargtype.getUnqualifiedType();
6125 }
6126
Chris Lattner465fa322008-10-05 17:34:18 +00006127 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6128 allLTypes = false;
6129 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6130 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006131 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006132
Eli Friedman47f77112008-08-22 00:56:42 +00006133 if (allLTypes) return lhs;
6134 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006135
6136 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6137 EPI.ExtInfo = einfo;
6138 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006139 }
6140
6141 if (lproto) allRTypes = false;
6142 if (rproto) allLTypes = false;
6143
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006144 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006145 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006146 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006147 if (proto->isVariadic()) return QualType();
6148 // Check that the types are compatible with the types that
6149 // would result from default argument promotions (C99 6.7.5.3p15).
6150 // The only types actually affected are promotable integer
6151 // types and floats, which would be passed as a different
6152 // type depending on whether the prototype is visible.
6153 unsigned proto_nargs = proto->getNumArgs();
6154 for (unsigned i = 0; i < proto_nargs; ++i) {
6155 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00006156
6157 // Look at the promotion type of enum types, since that is the type used
6158 // to pass enum values.
6159 if (const EnumType *Enum = argTy->getAs<EnumType>())
6160 argTy = Enum->getDecl()->getPromotionType();
6161
Eli Friedman47f77112008-08-22 00:56:42 +00006162 if (argTy->isPromotableIntegerType() ||
6163 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6164 return QualType();
6165 }
6166
6167 if (allLTypes) return lhs;
6168 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006169
6170 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6171 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00006172 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006173 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006174 }
6175
6176 if (allLTypes) return lhs;
6177 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00006178 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00006179}
6180
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006181QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006182 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006183 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00006184 // C++ [expr]: If an expression initially has the type "reference to T", the
6185 // type is adjusted to "T" prior to any further analysis, the expression
6186 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006187 // expression is an lvalue unless the reference is an rvalue reference and
6188 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00006189 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6190 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006191
6192 if (Unqualified) {
6193 LHS = LHS.getUnqualifiedType();
6194 RHS = RHS.getUnqualifiedType();
6195 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00006196
Eli Friedman47f77112008-08-22 00:56:42 +00006197 QualType LHSCan = getCanonicalType(LHS),
6198 RHSCan = getCanonicalType(RHS);
6199
6200 // If two types are identical, they are compatible.
6201 if (LHSCan == RHSCan)
6202 return LHS;
6203
John McCall8ccfcb52009-09-24 19:53:00 +00006204 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006205 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6206 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00006207 if (LQuals != RQuals) {
6208 // If any of these qualifiers are different, we have a type
6209 // mismatch.
6210 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00006211 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6212 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00006213 return QualType();
6214
6215 // Exactly one GC qualifier difference is allowed: __strong is
6216 // okay if the other type has no GC qualifier but is an Objective
6217 // C object pointer (i.e. implicitly strong by default). We fix
6218 // this by pretending that the unqualified type was actually
6219 // qualified __strong.
6220 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6221 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6222 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6223
6224 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6225 return QualType();
6226
6227 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6228 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6229 }
6230 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6231 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6232 }
Eli Friedman47f77112008-08-22 00:56:42 +00006233 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00006234 }
6235
6236 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00006237
Eli Friedmandcca6332009-06-01 01:22:52 +00006238 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6239 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00006240
Chris Lattnerfd652912008-01-14 05:45:46 +00006241 // We want to consider the two function types to be the same for these
6242 // comparisons, just force one to the other.
6243 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6244 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00006245
6246 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00006247 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6248 LHSClass = Type::ConstantArray;
6249 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6250 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00006251
John McCall8b07ec22010-05-15 11:32:37 +00006252 // ObjCInterfaces are just specialized ObjCObjects.
6253 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6254 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6255
Nate Begemance4d7fc2008-04-18 23:10:10 +00006256 // Canonicalize ExtVector -> Vector.
6257 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6258 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00006259
Chris Lattner95554662008-04-07 05:43:21 +00006260 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006261 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00006262 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00006263 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00006264 // Compatibility is based on the underlying type, not the promotion
6265 // type.
John McCall9dd450b2009-09-21 23:43:11 +00006266 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006267 QualType TINT = ETy->getDecl()->getIntegerType();
6268 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006269 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006270 }
John McCall9dd450b2009-09-21 23:43:11 +00006271 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006272 QualType TINT = ETy->getDecl()->getIntegerType();
6273 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006274 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006275 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006276 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00006277 if (OfBlockPointer && !BlockReturnType) {
6278 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6279 return LHS;
6280 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6281 return RHS;
6282 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006283
Eli Friedman47f77112008-08-22 00:56:42 +00006284 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00006285 }
Eli Friedman47f77112008-08-22 00:56:42 +00006286
Steve Naroffc6edcbd2008-01-09 22:43:08 +00006287 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006288 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006289#define TYPE(Class, Base)
6290#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00006291#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006292#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6293#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6294#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00006295 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006296
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006297 case Type::LValueReference:
6298 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006299 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00006300 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006301
John McCall8b07ec22010-05-15 11:32:37 +00006302 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006303 case Type::IncompleteArray:
6304 case Type::VariableArray:
6305 case Type::FunctionProto:
6306 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00006307 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006308
Chris Lattnerfd652912008-01-14 05:45:46 +00006309 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00006310 {
6311 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006312 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6313 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006314 if (Unqualified) {
6315 LHSPointee = LHSPointee.getUnqualifiedType();
6316 RHSPointee = RHSPointee.getUnqualifiedType();
6317 }
6318 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6319 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006320 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00006321 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006322 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00006323 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006324 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006325 return getPointerType(ResultType);
6326 }
Steve Naroff68e167d2008-12-10 17:49:55 +00006327 case Type::BlockPointer:
6328 {
6329 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006330 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6331 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006332 if (Unqualified) {
6333 LHSPointee = LHSPointee.getUnqualifiedType();
6334 RHSPointee = RHSPointee.getUnqualifiedType();
6335 }
6336 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6337 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00006338 if (ResultType.isNull()) return QualType();
6339 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6340 return LHS;
6341 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6342 return RHS;
6343 return getBlockPointerType(ResultType);
6344 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00006345 case Type::Atomic:
6346 {
6347 // Merge two pointer types, while trying to preserve typedef info
6348 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6349 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6350 if (Unqualified) {
6351 LHSValue = LHSValue.getUnqualifiedType();
6352 RHSValue = RHSValue.getUnqualifiedType();
6353 }
6354 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6355 Unqualified);
6356 if (ResultType.isNull()) return QualType();
6357 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6358 return LHS;
6359 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6360 return RHS;
6361 return getAtomicType(ResultType);
6362 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006363 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00006364 {
6365 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6366 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6367 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6368 return QualType();
6369
6370 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6371 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006372 if (Unqualified) {
6373 LHSElem = LHSElem.getUnqualifiedType();
6374 RHSElem = RHSElem.getUnqualifiedType();
6375 }
6376
6377 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006378 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00006379 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6380 return LHS;
6381 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6382 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00006383 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6384 ArrayType::ArraySizeModifier(), 0);
6385 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6386 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006387 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6388 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00006389 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6390 return LHS;
6391 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6392 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006393 if (LVAT) {
6394 // FIXME: This isn't correct! But tricky to implement because
6395 // the array's size has to be the size of LHS, but the type
6396 // has to be different.
6397 return LHS;
6398 }
6399 if (RVAT) {
6400 // FIXME: This isn't correct! But tricky to implement because
6401 // the array's size has to be the size of RHS, but the type
6402 // has to be different.
6403 return RHS;
6404 }
Eli Friedman3e62c212008-08-22 01:48:21 +00006405 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6406 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00006407 return getIncompleteArrayType(ResultType,
6408 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006409 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006410 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006411 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006412 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006413 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00006414 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00006415 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006416 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00006417 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00006418 case Type::Complex:
6419 // Distinct complex types are incompatible.
6420 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006421 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00006422 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00006423 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6424 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00006425 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00006426 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00006427 case Type::ObjCObject: {
6428 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00006429 // FIXME: This should be type compatibility, e.g. whether
6430 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00006431 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6432 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6433 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00006434 return LHS;
6435
Eli Friedman47f77112008-08-22 00:56:42 +00006436 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00006437 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006438 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006439 if (OfBlockPointer) {
6440 if (canAssignObjCInterfacesInBlockPointer(
6441 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006442 RHS->getAs<ObjCObjectPointerType>(),
6443 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00006444 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006445 return QualType();
6446 }
John McCall9dd450b2009-09-21 23:43:11 +00006447 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6448 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006449 return LHS;
6450
Steve Naroffc68cfcf2008-12-10 22:14:21 +00006451 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00006452 }
Steve Naroff32e44c02007-10-15 20:41:53 +00006453 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006454
David Blaikie8a40f702012-01-17 06:56:22 +00006455 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00006456}
Ted Kremenekfc581a92007-10-31 17:10:13 +00006457
Fariborz Jahanian97676972011-09-28 21:52:05 +00006458bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6459 const FunctionProtoType *FromFunctionType,
6460 const FunctionProtoType *ToFunctionType) {
6461 if (FromFunctionType->hasAnyConsumedArgs() !=
6462 ToFunctionType->hasAnyConsumedArgs())
6463 return false;
6464 FunctionProtoType::ExtProtoInfo FromEPI =
6465 FromFunctionType->getExtProtoInfo();
6466 FunctionProtoType::ExtProtoInfo ToEPI =
6467 ToFunctionType->getExtProtoInfo();
6468 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6469 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6470 ArgIdx != NumArgs; ++ArgIdx) {
6471 if (FromEPI.ConsumedArguments[ArgIdx] !=
6472 ToEPI.ConsumedArguments[ArgIdx])
6473 return false;
6474 }
6475 return true;
6476}
6477
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006478/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6479/// 'RHS' attributes and returns the merged version; including for function
6480/// return types.
6481QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6482 QualType LHSCan = getCanonicalType(LHS),
6483 RHSCan = getCanonicalType(RHS);
6484 // If two types are identical, they are compatible.
6485 if (LHSCan == RHSCan)
6486 return LHS;
6487 if (RHSCan->isFunctionType()) {
6488 if (!LHSCan->isFunctionType())
6489 return QualType();
6490 QualType OldReturnType =
6491 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6492 QualType NewReturnType =
6493 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6494 QualType ResReturnType =
6495 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6496 if (ResReturnType.isNull())
6497 return QualType();
6498 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6499 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6500 // In either case, use OldReturnType to build the new function type.
6501 const FunctionType *F = LHS->getAs<FunctionType>();
6502 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00006503 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6504 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006505 QualType ResultType
6506 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006507 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006508 return ResultType;
6509 }
6510 }
6511 return QualType();
6512 }
6513
6514 // If the qualifiers are different, the types can still be merged.
6515 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6516 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6517 if (LQuals != RQuals) {
6518 // If any of these qualifiers are different, we have a type mismatch.
6519 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6520 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6521 return QualType();
6522
6523 // Exactly one GC qualifier difference is allowed: __strong is
6524 // okay if the other type has no GC qualifier but is an Objective
6525 // C object pointer (i.e. implicitly strong by default). We fix
6526 // this by pretending that the unqualified type was actually
6527 // qualified __strong.
6528 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6529 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6530 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6531
6532 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6533 return QualType();
6534
6535 if (GC_L == Qualifiers::Strong)
6536 return LHS;
6537 if (GC_R == Qualifiers::Strong)
6538 return RHS;
6539 return QualType();
6540 }
6541
6542 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6543 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6544 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6545 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6546 if (ResQT == LHSBaseQT)
6547 return LHS;
6548 if (ResQT == RHSBaseQT)
6549 return RHS;
6550 }
6551 return QualType();
6552}
6553
Chris Lattner4ba0cef2008-04-07 07:01:58 +00006554//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006555// Integer Predicates
6556//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00006557
Jay Foad39c79802011-01-12 09:06:06 +00006558unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00006559 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00006560 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00006561 if (T->isBooleanType())
6562 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00006563 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006564 return (unsigned)getTypeSize(T);
6565}
6566
6567QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006568 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00006569
6570 // Turn <4 x signed int> -> <4 x unsigned int>
6571 if (const VectorType *VTy = T->getAs<VectorType>())
6572 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00006573 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00006574
6575 // For enums, we return the unsigned version of the base type.
6576 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006577 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00006578
6579 const BuiltinType *BTy = T->getAs<BuiltinType>();
6580 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006581 switch (BTy->getKind()) {
6582 case BuiltinType::Char_S:
6583 case BuiltinType::SChar:
6584 return UnsignedCharTy;
6585 case BuiltinType::Short:
6586 return UnsignedShortTy;
6587 case BuiltinType::Int:
6588 return UnsignedIntTy;
6589 case BuiltinType::Long:
6590 return UnsignedLongTy;
6591 case BuiltinType::LongLong:
6592 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00006593 case BuiltinType::Int128:
6594 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006595 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006596 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006597 }
6598}
6599
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00006600ASTMutationListener::~ASTMutationListener() { }
6601
Chris Lattnerecd79c62009-06-14 00:45:47 +00006602
6603//===----------------------------------------------------------------------===//
6604// Builtin Type Computation
6605//===----------------------------------------------------------------------===//
6606
6607/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00006608/// pointer over the consumed characters. This returns the resultant type. If
6609/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6610/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6611/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006612///
6613/// RequiresICE is filled in on return to indicate whether the value is required
6614/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00006615static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00006616 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006617 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00006618 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00006619 // Modifiers.
6620 int HowLong = 0;
6621 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006622 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00006623
Chris Lattnerdc226c22010-10-01 22:42:38 +00006624 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00006625 bool Done = false;
6626 while (!Done) {
6627 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00006628 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00006629 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006630 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00006631 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006632 case 'S':
6633 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6634 assert(!Signed && "Can't use 'S' modifier multiple times!");
6635 Signed = true;
6636 break;
6637 case 'U':
6638 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6639 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6640 Unsigned = true;
6641 break;
6642 case 'L':
6643 assert(HowLong <= 2 && "Can't have LLLL modifier");
6644 ++HowLong;
6645 break;
6646 }
6647 }
6648
6649 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00006650
Chris Lattnerecd79c62009-06-14 00:45:47 +00006651 // Read the base type.
6652 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00006653 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006654 case 'v':
6655 assert(HowLong == 0 && !Signed && !Unsigned &&
6656 "Bad modifiers used with 'v'!");
6657 Type = Context.VoidTy;
6658 break;
6659 case 'f':
6660 assert(HowLong == 0 && !Signed && !Unsigned &&
6661 "Bad modifiers used with 'f'!");
6662 Type = Context.FloatTy;
6663 break;
6664 case 'd':
6665 assert(HowLong < 2 && !Signed && !Unsigned &&
6666 "Bad modifiers used with 'd'!");
6667 if (HowLong)
6668 Type = Context.LongDoubleTy;
6669 else
6670 Type = Context.DoubleTy;
6671 break;
6672 case 's':
6673 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6674 if (Unsigned)
6675 Type = Context.UnsignedShortTy;
6676 else
6677 Type = Context.ShortTy;
6678 break;
6679 case 'i':
6680 if (HowLong == 3)
6681 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6682 else if (HowLong == 2)
6683 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6684 else if (HowLong == 1)
6685 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6686 else
6687 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6688 break;
6689 case 'c':
6690 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6691 if (Signed)
6692 Type = Context.SignedCharTy;
6693 else if (Unsigned)
6694 Type = Context.UnsignedCharTy;
6695 else
6696 Type = Context.CharTy;
6697 break;
6698 case 'b': // boolean
6699 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6700 Type = Context.BoolTy;
6701 break;
6702 case 'z': // size_t.
6703 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6704 Type = Context.getSizeType();
6705 break;
6706 case 'F':
6707 Type = Context.getCFConstantStringType();
6708 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00006709 case 'G':
6710 Type = Context.getObjCIdType();
6711 break;
6712 case 'H':
6713 Type = Context.getObjCSelType();
6714 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006715 case 'a':
6716 Type = Context.getBuiltinVaListType();
6717 assert(!Type.isNull() && "builtin va list type not initialized!");
6718 break;
6719 case 'A':
6720 // This is a "reference" to a va_list; however, what exactly
6721 // this means depends on how va_list is defined. There are two
6722 // different kinds of va_list: ones passed by value, and ones
6723 // passed by reference. An example of a by-value va_list is
6724 // x86, where va_list is a char*. An example of by-ref va_list
6725 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6726 // we want this argument to be a char*&; for x86-64, we want
6727 // it to be a __va_list_tag*.
6728 Type = Context.getBuiltinVaListType();
6729 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006730 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00006731 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006732 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00006733 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006734 break;
6735 case 'V': {
6736 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006737 unsigned NumElements = strtoul(Str, &End, 10);
6738 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006739 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00006740
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006741 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6742 RequiresICE, false);
6743 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00006744
6745 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00006746 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00006747 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006748 break;
6749 }
Douglas Gregorfed66992012-06-07 18:08:25 +00006750 case 'E': {
6751 char *End;
6752
6753 unsigned NumElements = strtoul(Str, &End, 10);
6754 assert(End != Str && "Missing vector size");
6755
6756 Str = End;
6757
6758 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6759 false);
6760 Type = Context.getExtVectorType(ElementType, NumElements);
6761 break;
6762 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006763 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006764 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6765 false);
6766 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006767 Type = Context.getComplexType(ElementType);
6768 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00006769 }
6770 case 'Y' : {
6771 Type = Context.getPointerDiffType();
6772 break;
6773 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00006774 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00006775 Type = Context.getFILEType();
6776 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006777 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006778 return QualType();
6779 }
Mike Stump2adb4da2009-07-28 23:47:15 +00006780 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00006781 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00006782 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00006783 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00006784 else
6785 Type = Context.getjmp_bufType();
6786
Mike Stump2adb4da2009-07-28 23:47:15 +00006787 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006788 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00006789 return QualType();
6790 }
6791 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00006792 case 'K':
6793 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
6794 Type = Context.getucontext_tType();
6795
6796 if (Type.isNull()) {
6797 Error = ASTContext::GE_Missing_ucontext;
6798 return QualType();
6799 }
6800 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00006801 }
Mike Stump11289f42009-09-09 15:08:12 +00006802
Chris Lattnerdc226c22010-10-01 22:42:38 +00006803 // If there are modifiers and if we're allowed to parse them, go for it.
6804 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006805 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00006806 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006807 default: Done = true; --Str; break;
6808 case '*':
6809 case '&': {
6810 // Both pointers and references can have their pointee types
6811 // qualified with an address space.
6812 char *End;
6813 unsigned AddrSpace = strtoul(Str, &End, 10);
6814 if (End != Str && AddrSpace != 0) {
6815 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6816 Str = End;
6817 }
6818 if (c == '*')
6819 Type = Context.getPointerType(Type);
6820 else
6821 Type = Context.getLValueReferenceType(Type);
6822 break;
6823 }
6824 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6825 case 'C':
6826 Type = Type.withConst();
6827 break;
6828 case 'D':
6829 Type = Context.getVolatileType(Type);
6830 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00006831 case 'R':
6832 Type = Type.withRestrict();
6833 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006834 }
6835 }
Chris Lattner84733392010-10-01 07:13:18 +00006836
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006837 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00006838 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00006839
Chris Lattnerecd79c62009-06-14 00:45:47 +00006840 return Type;
6841}
6842
6843/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00006844QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006845 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00006846 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006847 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00006848
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006849 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00006850
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006851 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006852 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006853 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6854 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006855 if (Error != GE_None)
6856 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006857
6858 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6859
Chris Lattnerecd79c62009-06-14 00:45:47 +00006860 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006861 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006862 if (Error != GE_None)
6863 return QualType();
6864
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006865 // If this argument is required to be an IntegerConstantExpression and the
6866 // caller cares, fill in the bitmask we return.
6867 if (RequiresICE && IntegerConstantArgs)
6868 *IntegerConstantArgs |= 1 << ArgTypes.size();
6869
Chris Lattnerecd79c62009-06-14 00:45:47 +00006870 // Do array -> pointer decay. The builtin should use the decayed type.
6871 if (Ty->isArrayType())
6872 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00006873
Chris Lattnerecd79c62009-06-14 00:45:47 +00006874 ArgTypes.push_back(Ty);
6875 }
6876
6877 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6878 "'.' should only occur at end of builtin type list!");
6879
John McCall991eb4b2010-12-21 00:44:39 +00006880 FunctionType::ExtInfo EI;
6881 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6882
6883 bool Variadic = (TypeStr[0] == '.');
6884
6885 // We really shouldn't be making a no-proto type here, especially in C++.
6886 if (ArgTypes.empty() && Variadic)
6887 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00006888
John McCalldb40c7f2010-12-14 08:05:40 +00006889 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00006890 EPI.ExtInfo = EI;
6891 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00006892
6893 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006894}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00006895
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006896GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6897 GVALinkage External = GVA_StrongExternal;
6898
6899 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006900 switch (L) {
6901 case NoLinkage:
6902 case InternalLinkage:
6903 case UniqueExternalLinkage:
6904 return GVA_Internal;
6905
6906 case ExternalLinkage:
6907 switch (FD->getTemplateSpecializationKind()) {
6908 case TSK_Undeclared:
6909 case TSK_ExplicitSpecialization:
6910 External = GVA_StrongExternal;
6911 break;
6912
6913 case TSK_ExplicitInstantiationDefinition:
6914 return GVA_ExplicitTemplateInstantiation;
6915
6916 case TSK_ExplicitInstantiationDeclaration:
6917 case TSK_ImplicitInstantiation:
6918 External = GVA_TemplateInstantiation;
6919 break;
6920 }
6921 }
6922
6923 if (!FD->isInlined())
6924 return External;
6925
David Blaikiebbafb8a2012-03-11 07:00:24 +00006926 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006927 // GNU or C99 inline semantics. Determine whether this symbol should be
6928 // externally visible.
6929 if (FD->isInlineDefinitionExternallyVisible())
6930 return External;
6931
6932 // C99 inline semantics, where the symbol is not externally visible.
6933 return GVA_C99Inline;
6934 }
6935
6936 // C++0x [temp.explicit]p9:
6937 // [ Note: The intent is that an inline function that is the subject of
6938 // an explicit instantiation declaration will still be implicitly
6939 // instantiated when used so that the body can be considered for
6940 // inlining, but that no out-of-line copy of the inline function would be
6941 // generated in the translation unit. -- end note ]
6942 if (FD->getTemplateSpecializationKind()
6943 == TSK_ExplicitInstantiationDeclaration)
6944 return GVA_C99Inline;
6945
6946 return GVA_CXXInline;
6947}
6948
6949GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6950 // If this is a static data member, compute the kind of template
6951 // specialization. Otherwise, this variable is not part of a
6952 // template.
6953 TemplateSpecializationKind TSK = TSK_Undeclared;
6954 if (VD->isStaticDataMember())
6955 TSK = VD->getTemplateSpecializationKind();
6956
6957 Linkage L = VD->getLinkage();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006958 if (L == ExternalLinkage && getLangOpts().CPlusPlus &&
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006959 VD->getType()->getLinkage() == UniqueExternalLinkage)
6960 L = UniqueExternalLinkage;
6961
6962 switch (L) {
6963 case NoLinkage:
6964 case InternalLinkage:
6965 case UniqueExternalLinkage:
6966 return GVA_Internal;
6967
6968 case ExternalLinkage:
6969 switch (TSK) {
6970 case TSK_Undeclared:
6971 case TSK_ExplicitSpecialization:
6972 return GVA_StrongExternal;
6973
6974 case TSK_ExplicitInstantiationDeclaration:
6975 llvm_unreachable("Variable should not be instantiated");
6976 // Fall through to treat this like any other instantiation.
6977
6978 case TSK_ExplicitInstantiationDefinition:
6979 return GVA_ExplicitTemplateInstantiation;
6980
6981 case TSK_ImplicitInstantiation:
6982 return GVA_TemplateInstantiation;
6983 }
6984 }
6985
David Blaikie8a40f702012-01-17 06:56:22 +00006986 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006987}
6988
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00006989bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006990 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6991 if (!VD->isFileVarDecl())
6992 return false;
Argyrios Kyrtzidisa98e8612011-09-13 21:35:00 +00006993 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006994 return false;
6995
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006996 // Weak references don't produce any output by themselves.
6997 if (D->hasAttr<WeakRefAttr>())
6998 return false;
6999
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007000 // Aliases and used decls are required.
7001 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7002 return true;
7003
7004 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7005 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007006 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007007 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007008
7009 // Constructors and destructors are required.
7010 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7011 return true;
7012
7013 // The key function for a class is required.
7014 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7015 const CXXRecordDecl *RD = MD->getParent();
7016 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7017 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
7018 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7019 return true;
7020 }
7021 }
7022
7023 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7024
7025 // static, static inline, always_inline, and extern inline functions can
7026 // always be deferred. Normal inline functions can be deferred in C99/C++.
7027 // Implicit template instantiations can also be deferred in C++.
7028 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007029 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007030 return false;
7031 return true;
7032 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007033
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007034 const VarDecl *VD = cast<VarDecl>(D);
7035 assert(VD->isFileVarDecl() && "Expected file scoped var");
7036
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007037 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7038 return false;
7039
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007040 // Structs that have non-trivial constructors or destructors are required.
7041
7042 // FIXME: Handle references.
Alexis Huntf479f1b2011-05-09 18:22:59 +00007043 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007044 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
7045 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Alexis Huntf479f1b2011-05-09 18:22:59 +00007046 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
7047 RD->hasTrivialCopyConstructor() &&
7048 RD->hasTrivialMoveConstructor() &&
7049 RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007050 return true;
7051 }
7052 }
7053
7054 GVALinkage L = GetGVALinkageForVariable(VD);
7055 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
7056 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
7057 return false;
7058 }
7059
7060 return true;
7061}
Charles Davis53c59df2010-08-16 03:33:14 +00007062
Charles Davis99202b32010-11-09 18:04:24 +00007063CallingConv ASTContext::getDefaultMethodCallConv() {
7064 // Pass through to the C++ ABI object
7065 return ABI->getDefaultMethodCallConv();
7066}
7067
Jay Foad39c79802011-01-12 09:06:06 +00007068bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007069 // Pass through to the C++ ABI object
7070 return ABI->isNearlyEmpty(RD);
7071}
7072
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007073MangleContext *ASTContext::createMangleContext() {
Douglas Gregore8bbc122011-09-02 00:18:52 +00007074 switch (Target->getCXXABI()) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007075 case CXXABI_ARM:
7076 case CXXABI_Itanium:
7077 return createItaniumMangleContext(*this, getDiagnostics());
7078 case CXXABI_Microsoft:
7079 return createMicrosoftMangleContext(*this, getDiagnostics());
7080 }
David Blaikie83d382b2011-09-23 05:06:16 +00007081 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007082}
7083
Charles Davis53c59df2010-08-16 03:33:14 +00007084CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007085
7086size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00007087 return ASTRecordLayouts.getMemorySize()
7088 + llvm::capacity_in_bytes(ObjCLayouts)
7089 + llvm::capacity_in_bytes(KeyFunctions)
7090 + llvm::capacity_in_bytes(ObjCImpls)
7091 + llvm::capacity_in_bytes(BlockVarCopyInits)
7092 + llvm::capacity_in_bytes(DeclAttrs)
7093 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7094 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7095 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7096 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7097 + llvm::capacity_in_bytes(OverriddenMethods)
7098 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007099 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00007100 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007101}
Ted Kremenek540017e2011-10-06 05:00:56 +00007102
Douglas Gregor63798542012-02-20 19:44:39 +00007103unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7104 CXXRecordDecl *Lambda = CallOperator->getParent();
7105 return LambdaMangleContexts[Lambda->getDeclContext()]
7106 .getManglingNumber(CallOperator);
7107}
7108
7109
Ted Kremenek540017e2011-10-06 05:00:56 +00007110void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7111 ParamIndices[D] = index;
7112}
7113
7114unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7115 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7116 assert(I != ParamIndices.end() &&
7117 "ParmIndices lacks entry set by ParmVarDecl");
7118 return I->second;
7119}