blob: 0452730201b5891369d77556a590804f7bc74480 [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Dmitri Gribenkoca7f80a2012-08-09 00:03:17 +000016#include "clang/AST/CommentCommandTraits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000017#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000018#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +000020#include "clang/AST/TypeLoc.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000021#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000023#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +000024#include "clang/AST/ASTMutationListener.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000025#include "clang/AST/RecordLayout.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000026#include "clang/AST/Mangle.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000027#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000028#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000029#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000030#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000031#include "llvm/ADT/StringExtras.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000032#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000033#include "llvm/Support/raw_ostream.h"
Ted Kremenek7d39c9a2011-07-27 18:41:12 +000034#include "llvm/Support/Capacity.h"
Charles Davis53c59df2010-08-16 03:33:14 +000035#include "CXXABI.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000036#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000037
Chris Lattnerddc135e2006-11-10 06:34:16 +000038using namespace clang;
39
Douglas Gregor9672f922010-07-03 00:47:00 +000040unsigned ASTContext::NumImplicitDefaultConstructors;
41unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000042unsigned ASTContext::NumImplicitCopyConstructors;
43unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000044unsigned ASTContext::NumImplicitMoveConstructors;
45unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000046unsigned ASTContext::NumImplicitCopyAssignmentOperators;
47unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000048unsigned ASTContext::NumImplicitMoveAssignmentOperators;
49unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000050unsigned ASTContext::NumImplicitDestructors;
51unsigned ASTContext::NumImplicitDestructorsDeclared;
52
Steve Naroff0af91202007-04-27 21:51:21 +000053enum FloatingRank {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000054 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Steve Naroff0af91202007-04-27 21:51:21 +000055};
56
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000057RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000058 if (!CommentsLoaded && ExternalSource) {
59 ExternalSource->ReadComments();
60 CommentsLoaded = true;
61 }
62
63 assert(D);
64
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000065 // User can not attach documentation to implicit declarations.
66 if (D->isImplicit())
67 return NULL;
68
Dmitri Gribenkob2610882012-08-14 17:17:18 +000069 // User can not attach documentation to implicit instantiations.
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000070 // FIXME: all these implicit instantiations shoud be marked as implicit
71 // declarations and get caught by condition above.
Dmitri Gribenkob2610882012-08-14 17:17:18 +000072 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
73 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
74 return NULL;
75 }
76
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000077 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
78 if (VD->isStaticDataMember() &&
79 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
80 return NULL;
81 }
82
83 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
84 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
85 return NULL;
86 }
87
88 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
89 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
90 return NULL;
91 }
92
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000093 // TODO: handle comments for function parameters properly.
94 if (isa<ParmVarDecl>(D))
95 return NULL;
96
Dmitri Gribenko34df2202012-07-31 22:37:06 +000097 // TODO: we could look up template parameter documentation in the template
98 // documentation.
99 if (isa<TemplateTypeParmDecl>(D) ||
100 isa<NonTypeTemplateParmDecl>(D) ||
101 isa<TemplateTemplateParmDecl>(D))
102 return NULL;
103
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000104 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000105
106 // If there are no comments anywhere, we won't find anything.
107 if (RawComments.empty())
108 return NULL;
109
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000110 // Find declaration location.
111 // For Objective-C declarations we generally don't expect to have multiple
112 // declarators, thus use declaration starting location as the "declaration
113 // location".
114 // For all other declarations multiple declarators are used quite frequently,
115 // so we use the location of the identifier as the "declaration location".
116 SourceLocation DeclLoc;
117 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000118 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000119 isa<RedeclarableTemplateDecl>(D) ||
120 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000121 DeclLoc = D->getLocStart();
122 else
123 DeclLoc = D->getLocation();
124
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000125 // If the declaration doesn't map directly to a location in a file, we
126 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000127 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
128 return NULL;
129
130 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000131 ArrayRef<RawComment *>::iterator Comment;
132 {
133 // When searching for comments during parsing, the comment we are looking
134 // for is usually among the last two comments we parsed -- check them
135 // first.
136 RawComment CommentAtDeclLoc(SourceMgr, SourceRange(DeclLoc));
137 BeforeThanCompare<RawComment> Compare(SourceMgr);
138 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
139 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
140 if (!Found && RawComments.size() >= 2) {
141 MaybeBeforeDecl--;
142 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
143 }
144
145 if (Found) {
146 Comment = MaybeBeforeDecl + 1;
147 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
148 &CommentAtDeclLoc, Compare));
149 } else {
150 // Slow path.
151 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
152 &CommentAtDeclLoc, Compare);
153 }
154 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000155
156 // Decompose the location for the declaration and find the beginning of the
157 // file buffer.
158 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
159
160 // First check whether we have a trailing comment.
161 if (Comment != RawComments.end() &&
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000162 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Dmitri Gribenko44cd7e62012-07-06 23:27:33 +0000163 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000164 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000165 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000166 // Check that Doxygen trailing comment comes after the declaration, starts
167 // on the same line and in the same file as the declaration.
168 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
169 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
170 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
171 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000172 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000173 }
174 }
175
176 // The comment just after the declaration was not a trailing comment.
177 // Let's look at the previous comment.
178 if (Comment == RawComments.begin())
179 return NULL;
180 --Comment;
181
182 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000183 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000184 return NULL;
185
186 // Decompose the end of the comment.
187 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000188 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000189
190 // If the comment and the declaration aren't in the same file, then they
191 // aren't related.
192 if (DeclLocDecomp.first != CommentEndDecomp.first)
193 return NULL;
194
195 // Get the corresponding buffer.
196 bool Invalid = false;
197 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
198 &Invalid).data();
199 if (Invalid)
200 return NULL;
201
202 // Extract text between the comment and declaration.
203 StringRef Text(Buffer + CommentEndDecomp.second,
204 DeclLocDecomp.second - CommentEndDecomp.second);
205
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000206 // There should be no other declarations or preprocessor directives between
207 // comment and declaration.
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000208 if (Text.find_first_of(",;{}#@") != StringRef::npos)
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000209 return NULL;
210
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000211 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000212}
213
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000214namespace {
215/// If we have a 'templated' declaration for a template, adjust 'D' to
216/// refer to the actual template.
217const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregor35ceb272012-08-13 16:37:30 +0000218 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
219 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
220 D = FTD;
221 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
222 if (const ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
223 D = CTD;
224 }
225 // FIXME: Alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000226 return D;
227}
228} // unnamed namespace
229
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000230const RawComment *ASTContext::getRawCommentForAnyRedecl(
231 const Decl *D,
232 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000233 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000234
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000235 // Check whether we have cached a comment for this declaration already.
236 {
237 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
238 RedeclComments.find(D);
239 if (Pos != RedeclComments.end()) {
240 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000241 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
242 if (OriginalDecl)
243 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000244 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000245 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000246 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000247 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000248
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000249 // Search for comments attached to declarations in the redeclaration chain.
250 const RawComment *RC = NULL;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000251 const Decl *OriginalDeclForRC = NULL;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000252 for (Decl::redecl_iterator I = D->redecls_begin(),
253 E = D->redecls_end();
254 I != E; ++I) {
255 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
256 RedeclComments.find(*I);
257 if (Pos != RedeclComments.end()) {
258 const RawCommentAndCacheFlags &Raw = Pos->second;
259 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
260 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000261 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000262 break;
263 }
264 } else {
265 RC = getRawCommentForDeclNoCache(*I);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000266 OriginalDeclForRC = *I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000267 RawCommentAndCacheFlags Raw;
268 if (RC) {
269 Raw.setRaw(RC);
270 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
271 } else
272 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000273 Raw.setOriginalDecl(*I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000274 RedeclComments[*I] = Raw;
275 if (RC)
276 break;
277 }
278 }
279
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000280 // If we found a comment, it should be a documentation comment.
281 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000282
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000283 if (OriginalDecl)
284 *OriginalDecl = OriginalDeclForRC;
285
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000286 // Update cache for every declaration in the redeclaration chain.
287 RawCommentAndCacheFlags Raw;
288 Raw.setRaw(RC);
289 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000290 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000291
292 for (Decl::redecl_iterator I = D->redecls_begin(),
293 E = D->redecls_end();
294 I != E; ++I) {
295 RawCommentAndCacheFlags &R = RedeclComments[*I];
296 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
297 R = Raw;
298 }
299
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000300 return RC;
301}
302
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000303comments::FullComment *ASTContext::getCommentForDecl(const Decl *D) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000304 D = adjustDeclToTemplate(D);
305 const Decl *Canonical = D->getCanonicalDecl();
306 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
307 ParsedComments.find(Canonical);
308 if (Pos != ParsedComments.end())
309 return Pos->second;
310
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000311 const Decl *OriginalDecl;
312 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000313 if (!RC)
314 return NULL;
315
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000316 if (D != OriginalDecl)
317 return getCommentForDecl(OriginalDecl);
318
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000319 comments::FullComment *FC = RC->parse(*this, D);
320 ParsedComments[Canonical] = FC;
321 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000322}
323
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000324void
325ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
326 TemplateTemplateParmDecl *Parm) {
327 ID.AddInteger(Parm->getDepth());
328 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000329 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000330
331 TemplateParameterList *Params = Parm->getTemplateParameters();
332 ID.AddInteger(Params->size());
333 for (TemplateParameterList::const_iterator P = Params->begin(),
334 PEnd = Params->end();
335 P != PEnd; ++P) {
336 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
337 ID.AddInteger(0);
338 ID.AddBoolean(TTP->isParameterPack());
339 continue;
340 }
341
342 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
343 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000344 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000345 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000346 if (NTTP->isExpandedParameterPack()) {
347 ID.AddBoolean(true);
348 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000349 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
350 QualType T = NTTP->getExpansionType(I);
351 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
352 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000353 } else
354 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000355 continue;
356 }
357
358 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
359 ID.AddInteger(2);
360 Profile(ID, TTP);
361 }
362}
363
364TemplateTemplateParmDecl *
365ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000366 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000367 // Check if we already have a canonical template template parameter.
368 llvm::FoldingSetNodeID ID;
369 CanonicalTemplateTemplateParm::Profile(ID, TTP);
370 void *InsertPos = 0;
371 CanonicalTemplateTemplateParm *Canonical
372 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
373 if (Canonical)
374 return Canonical->getParam();
375
376 // Build a canonical template parameter list.
377 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000378 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000379 CanonParams.reserve(Params->size());
380 for (TemplateParameterList::const_iterator P = Params->begin(),
381 PEnd = Params->end();
382 P != PEnd; ++P) {
383 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
384 CanonParams.push_back(
385 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000386 SourceLocation(),
387 SourceLocation(),
388 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000389 TTP->getIndex(), 0, false,
390 TTP->isParameterPack()));
391 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000392 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
393 QualType T = getCanonicalType(NTTP->getType());
394 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
395 NonTypeTemplateParmDecl *Param;
396 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000397 SmallVector<QualType, 2> ExpandedTypes;
398 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000399 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
400 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
401 ExpandedTInfos.push_back(
402 getTrivialTypeSourceInfo(ExpandedTypes.back()));
403 }
404
405 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000406 SourceLocation(),
407 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000408 NTTP->getDepth(),
409 NTTP->getPosition(), 0,
410 T,
411 TInfo,
412 ExpandedTypes.data(),
413 ExpandedTypes.size(),
414 ExpandedTInfos.data());
415 } else {
416 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000417 SourceLocation(),
418 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000419 NTTP->getDepth(),
420 NTTP->getPosition(), 0,
421 T,
422 NTTP->isParameterPack(),
423 TInfo);
424 }
425 CanonParams.push_back(Param);
426
427 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000428 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
429 cast<TemplateTemplateParmDecl>(*P)));
430 }
431
432 TemplateTemplateParmDecl *CanonTTP
433 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
434 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000435 TTP->getPosition(),
436 TTP->isParameterPack(),
437 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000438 TemplateParameterList::Create(*this, SourceLocation(),
439 SourceLocation(),
440 CanonParams.data(),
441 CanonParams.size(),
442 SourceLocation()));
443
444 // Get the new insert position for the node we care about.
445 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
446 assert(Canonical == 0 && "Shouldn't be in the map!");
447 (void)Canonical;
448
449 // Create the canonical template template parameter entry.
450 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
451 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
452 return CanonTTP;
453}
454
Charles Davis53c59df2010-08-16 03:33:14 +0000455CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000456 if (!LangOpts.CPlusPlus) return 0;
457
Charles Davis6bcb07a2010-08-19 02:18:14 +0000458 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000459 case CXXABI_ARM:
460 return CreateARMCXXABI(*this);
461 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000462 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000463 case CXXABI_Microsoft:
464 return CreateMicrosoftCXXABI(*this);
465 }
David Blaikie8a40f702012-01-17 06:56:22 +0000466 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000467}
468
Douglas Gregore8bbc122011-09-02 00:18:52 +0000469static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000470 const LangOptions &LOpts) {
471 if (LOpts.FakeAddressSpaceMap) {
472 // The fake address space map must have a distinct entry for each
473 // language-specific address space.
474 static const unsigned FakeAddrSpaceMap[] = {
475 1, // opencl_global
476 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000477 3, // opencl_constant
478 4, // cuda_device
479 5, // cuda_constant
480 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000481 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000482 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000483 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000484 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000485 }
486}
487
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000488ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000489 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000490 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000491 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000492 unsigned size_reserve,
493 bool DelayInitialization)
494 : FunctionProtoTypes(this_()),
495 TemplateSpecializationTypes(this_()),
496 DependentTemplateSpecializationTypes(this_()),
497 SubstTemplateTemplateParmPacks(this_()),
498 GlobalNestedNameSpecifier(0),
499 Int128Decl(0), UInt128Decl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000500 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000501 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000502 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000503 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000504 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
505 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
506 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000507 NullTypeSourceInfo(QualType()),
508 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000509 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000510 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000511 Idents(idents), Selectors(sels),
512 BuiltinInfo(builtins),
513 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000514 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000515 Comments(SM), CommentsLoaded(false),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000516 LastSDM(0, 0),
517 UniqueBlockByRefTypeID(0)
518{
Mike Stump11289f42009-09-09 15:08:12 +0000519 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000520 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000521
522 if (!DelayInitialization) {
523 assert(t && "No target supplied for ASTContext initialization");
524 InitBuiltinTypes(*t);
525 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000526}
527
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000528ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000529 // Release the DenseMaps associated with DeclContext objects.
530 // FIXME: Is this the ideal solution?
531 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000532
Douglas Gregor5b11d492010-07-25 17:53:33 +0000533 // Call all of the deallocation functions.
534 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
535 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000536
Ted Kremenek076baeb2010-06-08 23:00:58 +0000537 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000538 // because they can contain DenseMaps.
539 for (llvm::DenseMap<const ObjCContainerDecl*,
540 const ASTRecordLayout*>::iterator
541 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
542 // Increment in loop to prevent using deallocated memory.
543 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
544 R->Destroy(*this);
545
Ted Kremenek076baeb2010-06-08 23:00:58 +0000546 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
547 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
548 // Increment in loop to prevent using deallocated memory.
549 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
550 R->Destroy(*this);
551 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000552
553 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
554 AEnd = DeclAttrs.end();
555 A != AEnd; ++A)
556 A->second->~AttrVec();
557}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000558
Douglas Gregor1a809332010-05-23 18:26:36 +0000559void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
560 Deallocations.push_back(std::make_pair(Callback, Data));
561}
562
Mike Stump11289f42009-09-09 15:08:12 +0000563void
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000564ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000565 ExternalSource.reset(Source.take());
566}
567
Chris Lattner4eb445d2007-01-26 01:27:23 +0000568void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000569 llvm::errs() << "\n*** AST Context Stats:\n";
570 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000571
Douglas Gregora30d0462009-05-26 14:40:08 +0000572 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000573#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000574#define ABSTRACT_TYPE(Name, Parent)
575#include "clang/AST/TypeNodes.def"
576 0 // Extra
577 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000578
Chris Lattner4eb445d2007-01-26 01:27:23 +0000579 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
580 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000581 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000582 }
583
Douglas Gregora30d0462009-05-26 14:40:08 +0000584 unsigned Idx = 0;
585 unsigned TotalBytes = 0;
586#define TYPE(Name, Parent) \
587 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000588 llvm::errs() << " " << counts[Idx] << " " << #Name \
589 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000590 TotalBytes += counts[Idx] * sizeof(Name##Type); \
591 ++Idx;
592#define ABSTRACT_TYPE(Name, Parent)
593#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000594
Chandler Carruth3c147a72011-07-04 05:32:14 +0000595 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
596
Douglas Gregor7454c562010-07-02 20:37:36 +0000597 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000598 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
599 << NumImplicitDefaultConstructors
600 << " implicit default constructors created\n";
601 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
602 << NumImplicitCopyConstructors
603 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000604 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000605 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
606 << NumImplicitMoveConstructors
607 << " implicit move constructors created\n";
608 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
609 << NumImplicitCopyAssignmentOperators
610 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000611 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000612 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
613 << NumImplicitMoveAssignmentOperators
614 << " implicit move assignment operators created\n";
615 llvm::errs() << NumImplicitDestructorsDeclared << "/"
616 << NumImplicitDestructors
617 << " implicit destructors created\n";
618
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000619 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000620 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000621 ExternalSource->PrintStats();
622 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000623
Douglas Gregor5b11d492010-07-25 17:53:33 +0000624 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000625}
626
Douglas Gregor801c99d2011-08-12 06:49:56 +0000627TypedefDecl *ASTContext::getInt128Decl() const {
628 if (!Int128Decl) {
629 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
630 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
631 getTranslationUnitDecl(),
632 SourceLocation(),
633 SourceLocation(),
634 &Idents.get("__int128_t"),
635 TInfo);
636 }
637
638 return Int128Decl;
639}
640
641TypedefDecl *ASTContext::getUInt128Decl() const {
642 if (!UInt128Decl) {
643 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
644 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
645 getTranslationUnitDecl(),
646 SourceLocation(),
647 SourceLocation(),
648 &Idents.get("__uint128_t"),
649 TInfo);
650 }
651
652 return UInt128Decl;
653}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000654
John McCall48f2d582009-10-23 23:03:21 +0000655void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000656 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000657 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000658 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000659}
660
Douglas Gregore8bbc122011-09-02 00:18:52 +0000661void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
662 assert((!this->Target || this->Target == &Target) &&
663 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000664 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000665
Douglas Gregore8bbc122011-09-02 00:18:52 +0000666 this->Target = &Target;
667
668 ABI.reset(createCXXABI(Target));
669 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
670
Chris Lattner970e54e2006-11-12 00:37:36 +0000671 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000672 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000673
Chris Lattner970e54e2006-11-12 00:37:36 +0000674 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000675 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000676 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000677 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000678 InitBuiltinType(CharTy, BuiltinType::Char_S);
679 else
680 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000681 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000682 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
683 InitBuiltinType(ShortTy, BuiltinType::Short);
684 InitBuiltinType(IntTy, BuiltinType::Int);
685 InitBuiltinType(LongTy, BuiltinType::Long);
686 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000687
Chris Lattner970e54e2006-11-12 00:37:36 +0000688 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000689 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
690 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
691 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
692 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
693 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000694
Chris Lattner970e54e2006-11-12 00:37:36 +0000695 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000696 InitBuiltinType(FloatTy, BuiltinType::Float);
697 InitBuiltinType(DoubleTy, BuiltinType::Double);
698 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000699
Chris Lattnerf122cef2009-04-30 02:43:43 +0000700 // GNU extension, 128-bit integers.
701 InitBuiltinType(Int128Ty, BuiltinType::Int128);
702 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
703
Chris Lattnerad3467e2010-12-25 23:25:43 +0000704 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedman786d0872011-04-30 19:24:24 +0000705 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000706 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
707 else // -fshort-wchar makes wchar_t be unsigned.
708 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
709 } else // C99
Chris Lattner007cb022009-02-26 23:43:47 +0000710 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000711
James Molloy36365542012-05-04 10:55:22 +0000712 WIntTy = getFromTargetType(Target.getWIntType());
713
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000714 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
715 InitBuiltinType(Char16Ty, BuiltinType::Char16);
716 else // C99
717 Char16Ty = getFromTargetType(Target.getChar16Type());
718
719 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
720 InitBuiltinType(Char32Ty, BuiltinType::Char32);
721 else // C99
722 Char32Ty = getFromTargetType(Target.getChar32Type());
723
Douglas Gregor4619e432008-12-05 23:32:09 +0000724 // Placeholder type for type-dependent expressions whose type is
725 // completely unknown. No code should ever check a type against
726 // DependentTy and users should never see it; however, it is here to
727 // help diagnose failures to properly check for type-dependent
728 // expressions.
729 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000730
John McCall36e7fe32010-10-12 00:20:44 +0000731 // Placeholder type for functions.
732 InitBuiltinType(OverloadTy, BuiltinType::Overload);
733
John McCall0009fcc2011-04-26 20:42:42 +0000734 // Placeholder type for bound members.
735 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
736
John McCall526ab472011-10-25 17:37:35 +0000737 // Placeholder type for pseudo-objects.
738 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
739
John McCall31996342011-04-07 08:22:57 +0000740 // "any" type; useful for debugger-like clients.
741 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
742
John McCall8a6b59a2011-10-17 18:09:15 +0000743 // Placeholder type for unbridged ARC casts.
744 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
745
Chris Lattner970e54e2006-11-12 00:37:36 +0000746 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000747 FloatComplexTy = getComplexType(FloatTy);
748 DoubleComplexTy = getComplexType(DoubleTy);
749 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000750
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000751 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000752 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
753 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000754 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000755
756 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +0000757 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
758 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000759
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000760 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000761
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000762 // void * type
763 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000764
765 // nullptr type (C++0x 2.14.7)
766 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000767
768 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
769 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +0000770
771 // Builtin type used to help define __builtin_va_list.
772 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +0000773}
774
David Blaikie9c902b52011-09-25 23:23:43 +0000775DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000776 return SourceMgr.getDiagnostics();
777}
778
Douglas Gregor561eceb2010-08-30 16:49:28 +0000779AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
780 AttrVec *&Result = DeclAttrs[D];
781 if (!Result) {
782 void *Mem = Allocate(sizeof(AttrVec));
783 Result = new (Mem) AttrVec;
784 }
785
786 return *Result;
787}
788
789/// \brief Erase the attributes corresponding to the given declaration.
790void ASTContext::eraseDeclAttrs(const Decl *D) {
791 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
792 if (Pos != DeclAttrs.end()) {
793 Pos->second->~AttrVec();
794 DeclAttrs.erase(Pos);
795 }
796}
797
Douglas Gregor86d142a2009-10-08 07:24:58 +0000798MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000799ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000800 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000801 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000802 = InstantiatedFromStaticDataMember.find(Var);
803 if (Pos == InstantiatedFromStaticDataMember.end())
804 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000805
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000806 return Pos->second;
807}
808
Mike Stump11289f42009-09-09 15:08:12 +0000809void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000810ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000811 TemplateSpecializationKind TSK,
812 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000813 assert(Inst->isStaticDataMember() && "Not a static data member");
814 assert(Tmpl->isStaticDataMember() && "Not a static data member");
815 assert(!InstantiatedFromStaticDataMember[Inst] &&
816 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000817 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000818 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000819}
820
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000821FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
822 const FunctionDecl *FD){
823 assert(FD && "Specialization is 0");
824 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +0000825 = ClassScopeSpecializationPattern.find(FD);
826 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000827 return 0;
828
829 return Pos->second;
830}
831
832void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
833 FunctionDecl *Pattern) {
834 assert(FD && "Specialization is 0");
835 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +0000836 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000837}
838
John McCalle61f2ba2009-11-18 02:36:19 +0000839NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000840ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000841 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000842 = InstantiatedFromUsingDecl.find(UUD);
843 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000844 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000845
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000846 return Pos->second;
847}
848
849void
John McCallb96ec562009-12-04 22:46:56 +0000850ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
851 assert((isa<UsingDecl>(Pattern) ||
852 isa<UnresolvedUsingValueDecl>(Pattern) ||
853 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
854 "pattern decl is not a using decl");
855 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
856 InstantiatedFromUsingDecl[Inst] = Pattern;
857}
858
859UsingShadowDecl *
860ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
861 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
862 = InstantiatedFromUsingShadowDecl.find(Inst);
863 if (Pos == InstantiatedFromUsingShadowDecl.end())
864 return 0;
865
866 return Pos->second;
867}
868
869void
870ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
871 UsingShadowDecl *Pattern) {
872 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
873 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000874}
875
Anders Carlsson5da84842009-09-01 04:26:58 +0000876FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
877 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
878 = InstantiatedFromUnnamedFieldDecl.find(Field);
879 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
880 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000881
Anders Carlsson5da84842009-09-01 04:26:58 +0000882 return Pos->second;
883}
884
885void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
886 FieldDecl *Tmpl) {
887 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
888 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
889 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
890 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000891
Anders Carlsson5da84842009-09-01 04:26:58 +0000892 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
893}
894
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000895bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
896 const FieldDecl *LastFD) const {
897 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000898 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000899}
900
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000901bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
902 const FieldDecl *LastFD) const {
903 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000904 FD->getBitWidthValue(*this) == 0 &&
905 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000906}
907
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000908bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
909 const FieldDecl *LastFD) const {
910 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000911 FD->getBitWidthValue(*this) &&
912 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000913}
914
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000915bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000916 const FieldDecl *LastFD) const {
917 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000918 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000919}
920
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000921bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000922 const FieldDecl *LastFD) const {
923 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000924 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000925}
926
Douglas Gregor832940b2010-03-02 23:58:15 +0000927ASTContext::overridden_cxx_method_iterator
928ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
929 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
930 = OverriddenMethods.find(Method);
931 if (Pos == OverriddenMethods.end())
932 return 0;
933
934 return Pos->second.begin();
935}
936
937ASTContext::overridden_cxx_method_iterator
938ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
939 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
940 = OverriddenMethods.find(Method);
941 if (Pos == OverriddenMethods.end())
942 return 0;
943
944 return Pos->second.end();
945}
946
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000947unsigned
948ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
949 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
950 = OverriddenMethods.find(Method);
951 if (Pos == OverriddenMethods.end())
952 return 0;
953
954 return Pos->second.size();
955}
956
Douglas Gregor832940b2010-03-02 23:58:15 +0000957void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
958 const CXXMethodDecl *Overridden) {
959 OverriddenMethods[Method].push_back(Overridden);
960}
961
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000962void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
963 assert(!Import->NextLocalImport && "Import declaration already in the chain");
964 assert(!Import->isFromASTFile() && "Non-local import declaration");
965 if (!FirstLocalImport) {
966 FirstLocalImport = Import;
967 LastLocalImport = Import;
968 return;
969 }
970
971 LastLocalImport->NextLocalImport = Import;
972 LastLocalImport = Import;
973}
974
Chris Lattner53cfe802007-07-18 17:52:12 +0000975//===----------------------------------------------------------------------===//
976// Type Sizing and Analysis
977//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000978
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000979/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
980/// scalar floating point type.
981const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000982 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000983 assert(BT && "Not a floating point type!");
984 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +0000985 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000986 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +0000987 case BuiltinType::Float: return Target->getFloatFormat();
988 case BuiltinType::Double: return Target->getDoubleFormat();
989 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000990 }
991}
992
Ken Dyck160146e2010-01-27 17:10:57 +0000993/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000994/// specified decl. Note that bitfields do not have a valid alignment, so
995/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000996/// If @p RefAsPointee, references are treated like their underlying type
997/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000998CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000999 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001000
John McCall94268702010-10-08 18:24:19 +00001001 bool UseAlignAttrOnly = false;
1002 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1003 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001004
John McCall94268702010-10-08 18:24:19 +00001005 // __attribute__((aligned)) can increase or decrease alignment
1006 // *except* on a struct or struct member, where it only increases
1007 // alignment unless 'packed' is also specified.
1008 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001009 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001010 // ignore that possibility; Sema should diagnose it.
1011 if (isa<FieldDecl>(D)) {
1012 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1013 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1014 } else {
1015 UseAlignAttrOnly = true;
1016 }
1017 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001018 else if (isa<FieldDecl>(D))
1019 UseAlignAttrOnly =
1020 D->hasAttr<PackedAttr>() ||
1021 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001022
John McCall4e819612011-01-20 07:57:12 +00001023 // If we're using the align attribute only, just ignore everything
1024 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001025 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001026 // do nothing
1027
John McCall94268702010-10-08 18:24:19 +00001028 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001029 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001030 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001031 if (RefAsPointee)
1032 T = RT->getPointeeType();
1033 else
1034 T = getPointerType(RT->getPointeeType());
1035 }
1036 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001037 // Adjust alignments of declarations with array type by the
1038 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +00001039 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +00001040 const ArrayType *arrayType;
1041 if (MinWidth && (arrayType = getAsArrayType(T))) {
1042 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001043 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +00001044 else if (isa<ConstantArrayType>(arrayType) &&
1045 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001046 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +00001047
John McCall33ddac02011-01-19 10:06:00 +00001048 // Walk through any array types while we're at it.
1049 T = getBaseElementType(arrayType);
1050 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001051 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +00001052 }
John McCall4e819612011-01-20 07:57:12 +00001053
1054 // Fields can be subject to extra alignment constraints, like if
1055 // the field is packed, the struct is packed, or the struct has a
1056 // a max-field-alignment constraint (#pragma pack). So calculate
1057 // the actual alignment of the field within the struct, and then
1058 // (as we're expected to) constrain that by the alignment of the type.
1059 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
1060 // So calculate the alignment of the field.
1061 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
1062
1063 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +00001064 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001065
1066 // Use the GCD of that and the offset within the record.
1067 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
1068 if (offset > 0) {
1069 // Alignment is always a power of 2, so the GCD will be a power of 2,
1070 // which means we get to do this crazy thing instead of Euclid's.
1071 uint64_t lowBitOfOffset = offset & (~offset + 1);
1072 if (lowBitOfOffset < fieldAlign)
1073 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
1074 }
1075
1076 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +00001077 }
Chris Lattner68061312009-01-24 21:53:27 +00001078 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001079
Ken Dyckcc56c542011-01-15 18:38:59 +00001080 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001081}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001082
John McCall87fe5d52010-05-20 01:18:31 +00001083std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001084ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001085 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +00001086 return std::make_pair(toCharUnitsFromBits(Info.first),
1087 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +00001088}
1089
1090std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001091ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001092 return getTypeInfoInChars(T.getTypePtr());
1093}
1094
Daniel Dunbarc6475872012-03-09 04:12:54 +00001095std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1096 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1097 if (it != MemoizedTypeInfo.end())
1098 return it->second;
1099
1100 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1101 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1102 return Info;
1103}
1104
1105/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1106/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001107///
1108/// FIXME: Pointers into different addr spaces could have different sizes and
1109/// alignment requirements: getPointerInfo should take an AddrSpace, this
1110/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +00001111std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +00001112ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +00001113 uint64_t Width=0;
1114 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001115 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001116#define TYPE(Class, Base)
1117#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001118#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001119#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1120#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001121 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001122
Chris Lattner355332d2007-07-13 22:27:08 +00001123 case Type::FunctionNoProto:
1124 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001125 // GCC extension: alignof(function) = 32 bits
1126 Width = 0;
1127 Align = 32;
1128 break;
1129
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001130 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001131 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001132 Width = 0;
1133 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1134 break;
1135
Steve Naroff5c131802007-08-30 01:06:46 +00001136 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001137 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001138
Chris Lattner37e05872008-03-05 18:54:05 +00001139 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001140 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +00001141 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1142 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001143 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001144 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +00001145 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001146 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001147 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001148 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001149 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001150 const VectorType *VT = cast<VectorType>(T);
1151 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1152 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001153 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001154 // If the alignment is not a power of 2, round up to the next power of 2.
1155 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001156 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001157 Align = llvm::NextPowerOf2(Align);
1158 Width = llvm::RoundUpToAlignment(Width, Align);
1159 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001160 // Adjust the alignment based on the target max.
1161 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1162 if (TargetVectorAlign && TargetVectorAlign < Align)
1163 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001164 break;
1165 }
Chris Lattner647fb222007-07-18 18:26:58 +00001166
Chris Lattner7570e9c2008-03-08 08:52:55 +00001167 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001168 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001169 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001170 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001171 // GCC extension: alignof(void) = 8 bits.
1172 Width = 0;
1173 Align = 8;
1174 break;
1175
Chris Lattner6a4f7452007-12-19 19:23:28 +00001176 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001177 Width = Target->getBoolWidth();
1178 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001179 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001180 case BuiltinType::Char_S:
1181 case BuiltinType::Char_U:
1182 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001183 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001184 Width = Target->getCharWidth();
1185 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001186 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001187 case BuiltinType::WChar_S:
1188 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001189 Width = Target->getWCharWidth();
1190 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001191 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001192 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001193 Width = Target->getChar16Width();
1194 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001195 break;
1196 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001197 Width = Target->getChar32Width();
1198 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001199 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001200 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001201 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001202 Width = Target->getShortWidth();
1203 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001204 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001205 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001206 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001207 Width = Target->getIntWidth();
1208 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001209 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001210 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001211 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001212 Width = Target->getLongWidth();
1213 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001214 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001215 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001216 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001217 Width = Target->getLongLongWidth();
1218 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001219 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001220 case BuiltinType::Int128:
1221 case BuiltinType::UInt128:
1222 Width = 128;
1223 Align = 128; // int128_t is 128-bit aligned on all targets.
1224 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001225 case BuiltinType::Half:
1226 Width = Target->getHalfWidth();
1227 Align = Target->getHalfAlign();
1228 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001229 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001230 Width = Target->getFloatWidth();
1231 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001232 break;
1233 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001234 Width = Target->getDoubleWidth();
1235 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001236 break;
1237 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001238 Width = Target->getLongDoubleWidth();
1239 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001240 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001241 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001242 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1243 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001244 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001245 case BuiltinType::ObjCId:
1246 case BuiltinType::ObjCClass:
1247 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001248 Width = Target->getPointerWidth(0);
1249 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001250 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001251 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001252 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001253 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001254 Width = Target->getPointerWidth(0);
1255 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001256 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001257 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001258 unsigned AS = getTargetAddressSpace(
1259 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001260 Width = Target->getPointerWidth(AS);
1261 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001262 break;
1263 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001264 case Type::LValueReference:
1265 case Type::RValueReference: {
1266 // alignof and sizeof should never enter this code path here, so we go
1267 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001268 unsigned AS = getTargetAddressSpace(
1269 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001270 Width = Target->getPointerWidth(AS);
1271 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001272 break;
1273 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001274 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001275 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001276 Width = Target->getPointerWidth(AS);
1277 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001278 break;
1279 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001280 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001281 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001282 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +00001283 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +00001284 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001285 Align = PtrDiffInfo.second;
1286 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001287 }
Chris Lattner647fb222007-07-18 18:26:58 +00001288 case Type::Complex: {
1289 // Complex types have the same alignment as their elements, but twice the
1290 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001291 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001292 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001293 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001294 Align = EltInfo.second;
1295 break;
1296 }
John McCall8b07ec22010-05-15 11:32:37 +00001297 case Type::ObjCObject:
1298 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001299 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001300 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001301 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001302 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001303 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001304 break;
1305 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001306 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001307 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001308 const TagType *TT = cast<TagType>(T);
1309
1310 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001311 Width = 8;
1312 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001313 break;
1314 }
Mike Stump11289f42009-09-09 15:08:12 +00001315
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001316 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001317 return getTypeInfo(ET->getDecl()->getIntegerType());
1318
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001319 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001320 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001321 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001322 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001323 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001324 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001325
Chris Lattner63d2b362009-10-22 05:17:15 +00001326 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001327 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1328 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001329
Richard Smith30482bc2011-02-20 03:19:35 +00001330 case Type::Auto: {
1331 const AutoType *A = cast<AutoType>(T);
1332 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001333 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001334 }
1335
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001336 case Type::Paren:
1337 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1338
Douglas Gregoref462e62009-04-30 17:32:17 +00001339 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001340 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001341 std::pair<uint64_t, unsigned> Info
1342 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001343 // If the typedef has an aligned attribute on it, it overrides any computed
1344 // alignment we have. This violates the GCC documentation (which says that
1345 // attribute(aligned) can only round up) but matches its implementation.
1346 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1347 Align = AttrAlign;
1348 else
1349 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001350 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001351 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001352 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001353
1354 case Type::TypeOfExpr:
1355 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1356 .getTypePtr());
1357
1358 case Type::TypeOf:
1359 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1360
Anders Carlsson81df7b82009-06-24 19:06:50 +00001361 case Type::Decltype:
1362 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1363 .getTypePtr());
1364
Alexis Hunte852b102011-05-24 22:41:36 +00001365 case Type::UnaryTransform:
1366 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1367
Abramo Bagnara6150c882010-05-11 21:36:43 +00001368 case Type::Elaborated:
1369 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001370
John McCall81904512011-01-06 01:58:22 +00001371 case Type::Attributed:
1372 return getTypeInfo(
1373 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1374
Richard Smith3f1b5d02011-05-05 21:57:07 +00001375 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001376 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001377 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001378 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1379 // A type alias template specialization may refer to a typedef with the
1380 // aligned attribute on it.
1381 if (TST->isTypeAlias())
1382 return getTypeInfo(TST->getAliasedType().getTypePtr());
1383 else
1384 return getTypeInfo(getCanonicalType(T));
1385 }
1386
Eli Friedman0dfb8892011-10-06 23:00:33 +00001387 case Type::Atomic: {
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001388 std::pair<uint64_t, unsigned> Info
1389 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1390 Width = Info.first;
1391 Align = Info.second;
1392 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1393 llvm::isPowerOf2_64(Width)) {
1394 // We can potentially perform lock-free atomic operations for this
1395 // type; promote the alignment appropriately.
1396 // FIXME: We could potentially promote the width here as well...
1397 // is that worthwhile? (Non-struct atomic types generally have
1398 // power-of-two size anyway, but structs might not. Requires a bit
1399 // of implementation work to make sure we zero out the extra bits.)
1400 Align = static_cast<unsigned>(Width);
1401 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001402 }
1403
Douglas Gregoref462e62009-04-30 17:32:17 +00001404 }
Mike Stump11289f42009-09-09 15:08:12 +00001405
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001406 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001407 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001408}
1409
Ken Dyckcc56c542011-01-15 18:38:59 +00001410/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1411CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1412 return CharUnits::fromQuantity(BitSize / getCharWidth());
1413}
1414
Ken Dyckb0fcc592011-02-11 01:54:29 +00001415/// toBits - Convert a size in characters to a size in characters.
1416int64_t ASTContext::toBits(CharUnits CharSize) const {
1417 return CharSize.getQuantity() * getCharWidth();
1418}
1419
Ken Dyck8c89d592009-12-22 14:23:30 +00001420/// getTypeSizeInChars - Return the size of the specified type, in characters.
1421/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001422CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001423 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001424}
Jay Foad39c79802011-01-12 09:06:06 +00001425CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001426 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001427}
1428
Ken Dycka6046ab2010-01-26 17:25:18 +00001429/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001430/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001431CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001432 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001433}
Jay Foad39c79802011-01-12 09:06:06 +00001434CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001435 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001436}
1437
Chris Lattnera3402cd2009-01-27 18:08:34 +00001438/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1439/// type for the current target in bits. This can be different than the ABI
1440/// alignment in cases where it is beneficial for performance to overalign
1441/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001442unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001443 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001444
1445 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001446 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001447 T = CT->getElementType().getTypePtr();
1448 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001449 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1450 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001451 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1452
Chris Lattnera3402cd2009-01-27 18:08:34 +00001453 return ABIAlign;
1454}
1455
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001456/// DeepCollectObjCIvars -
1457/// This routine first collects all declared, but not synthesized, ivars in
1458/// super class and then collects all ivars, including those synthesized for
1459/// current class. This routine is used for implementation of current class
1460/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001461///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001462void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1463 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001464 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001465 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1466 DeepCollectObjCIvars(SuperClass, false, Ivars);
1467 if (!leafClass) {
1468 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1469 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001470 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001471 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001472 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001473 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001474 Iv= Iv->getNextIvar())
1475 Ivars.push_back(Iv);
1476 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001477}
1478
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001479/// CollectInheritedProtocols - Collect all protocols in current class and
1480/// those inherited by it.
1481void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001482 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001483 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001484 // We can use protocol_iterator here instead of
1485 // all_referenced_protocol_iterator since we are walking all categories.
1486 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1487 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001488 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001489 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001490 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001491 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001492 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001493 CollectInheritedProtocols(*P, Protocols);
1494 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001495 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001496
1497 // Categories of this Interface.
1498 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1499 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1500 CollectInheritedProtocols(CDeclChain, Protocols);
1501 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1502 while (SD) {
1503 CollectInheritedProtocols(SD, Protocols);
1504 SD = SD->getSuperClass();
1505 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001506 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001507 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001508 PE = OC->protocol_end(); P != PE; ++P) {
1509 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001510 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001511 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1512 PE = Proto->protocol_end(); P != PE; ++P)
1513 CollectInheritedProtocols(*P, Protocols);
1514 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001515 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001516 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1517 PE = OP->protocol_end(); P != PE; ++P) {
1518 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001519 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001520 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1521 PE = Proto->protocol_end(); P != PE; ++P)
1522 CollectInheritedProtocols(*P, Protocols);
1523 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001524 }
1525}
1526
Jay Foad39c79802011-01-12 09:06:06 +00001527unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001528 unsigned count = 0;
1529 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001530 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1531 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001532 count += CDecl->ivar_size();
1533
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001534 // Count ivar defined in this class's implementation. This
1535 // includes synthesized ivars.
1536 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001537 count += ImplDecl->ivar_size();
1538
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001539 return count;
1540}
1541
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001542bool ASTContext::isSentinelNullExpr(const Expr *E) {
1543 if (!E)
1544 return false;
1545
1546 // nullptr_t is always treated as null.
1547 if (E->getType()->isNullPtrType()) return true;
1548
1549 if (E->getType()->isAnyPointerType() &&
1550 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1551 Expr::NPC_ValueDependentIsNull))
1552 return true;
1553
1554 // Unfortunately, __null has type 'int'.
1555 if (isa<GNUNullExpr>(E)) return true;
1556
1557 return false;
1558}
1559
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001560/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1561ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1562 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1563 I = ObjCImpls.find(D);
1564 if (I != ObjCImpls.end())
1565 return cast<ObjCImplementationDecl>(I->second);
1566 return 0;
1567}
1568/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1569ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1570 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1571 I = ObjCImpls.find(D);
1572 if (I != ObjCImpls.end())
1573 return cast<ObjCCategoryImplDecl>(I->second);
1574 return 0;
1575}
1576
1577/// \brief Set the implementation of ObjCInterfaceDecl.
1578void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1579 ObjCImplementationDecl *ImplD) {
1580 assert(IFaceD && ImplD && "Passed null params");
1581 ObjCImpls[IFaceD] = ImplD;
1582}
1583/// \brief Set the implementation of ObjCCategoryDecl.
1584void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1585 ObjCCategoryImplDecl *ImplD) {
1586 assert(CatD && ImplD && "Passed null params");
1587 ObjCImpls[CatD] = ImplD;
1588}
1589
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001590ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1591 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1592 return ID;
1593 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1594 return CD->getClassInterface();
1595 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1596 return IMD->getClassInterface();
1597
1598 return 0;
1599}
1600
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001601/// \brief Get the copy initialization expression of VarDecl,or NULL if
1602/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001603Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001604 assert(VD && "Passed null params");
1605 assert(VD->hasAttr<BlocksAttr>() &&
1606 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001607 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001608 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001609 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1610}
1611
1612/// \brief Set the copy inialization expression of a block var decl.
1613void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1614 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001615 assert(VD->hasAttr<BlocksAttr>() &&
1616 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001617 BlockVarCopyInits[VD] = Init;
1618}
1619
John McCallbcd03502009-12-07 02:54:59 +00001620TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001621 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001622 if (!DataSize)
1623 DataSize = TypeLoc::getFullDataSizeForType(T);
1624 else
1625 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001626 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001627
John McCallbcd03502009-12-07 02:54:59 +00001628 TypeSourceInfo *TInfo =
1629 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1630 new (TInfo) TypeSourceInfo(T);
1631 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001632}
1633
John McCallbcd03502009-12-07 02:54:59 +00001634TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001635 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001636 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001637 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001638 return DI;
1639}
1640
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001641const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001642ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001643 return getObjCLayout(D, 0);
1644}
1645
1646const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001647ASTContext::getASTObjCImplementationLayout(
1648 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001649 return getObjCLayout(D->getClassInterface(), D);
1650}
1651
Chris Lattner983a8bb2007-07-13 22:13:22 +00001652//===----------------------------------------------------------------------===//
1653// Type creation/memoization methods
1654//===----------------------------------------------------------------------===//
1655
Jay Foad39c79802011-01-12 09:06:06 +00001656QualType
John McCall33ddac02011-01-19 10:06:00 +00001657ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1658 unsigned fastQuals = quals.getFastQualifiers();
1659 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001660
1661 // Check if we've already instantiated this type.
1662 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001663 ExtQuals::Profile(ID, baseType, quals);
1664 void *insertPos = 0;
1665 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1666 assert(eq->getQualifiers() == quals);
1667 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001668 }
1669
John McCall33ddac02011-01-19 10:06:00 +00001670 // If the base type is not canonical, make the appropriate canonical type.
1671 QualType canon;
1672 if (!baseType->isCanonicalUnqualified()) {
1673 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00001674 canonSplit.Quals.addConsistentQualifiers(quals);
1675 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001676
1677 // Re-find the insert position.
1678 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1679 }
1680
1681 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1682 ExtQualNodes.InsertNode(eq, insertPos);
1683 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001684}
1685
Jay Foad39c79802011-01-12 09:06:06 +00001686QualType
1687ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001688 QualType CanT = getCanonicalType(T);
1689 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001690 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001691
John McCall8ccfcb52009-09-24 19:53:00 +00001692 // If we are composing extended qualifiers together, merge together
1693 // into one ExtQuals node.
1694 QualifierCollector Quals;
1695 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001696
John McCall8ccfcb52009-09-24 19:53:00 +00001697 // If this type already has an address space specified, it cannot get
1698 // another one.
1699 assert(!Quals.hasAddressSpace() &&
1700 "Type cannot be in multiple addr spaces!");
1701 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001702
John McCall8ccfcb52009-09-24 19:53:00 +00001703 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001704}
1705
Chris Lattnerd60183d2009-02-18 22:53:11 +00001706QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001707 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001708 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001709 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001710 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001711
John McCall53fa7142010-12-24 02:08:15 +00001712 if (const PointerType *ptr = T->getAs<PointerType>()) {
1713 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001714 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001715 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1716 return getPointerType(ResultType);
1717 }
1718 }
Mike Stump11289f42009-09-09 15:08:12 +00001719
John McCall8ccfcb52009-09-24 19:53:00 +00001720 // If we are composing extended qualifiers together, merge together
1721 // into one ExtQuals node.
1722 QualifierCollector Quals;
1723 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001724
John McCall8ccfcb52009-09-24 19:53:00 +00001725 // If this type already has an ObjCGC specified, it cannot get
1726 // another one.
1727 assert(!Quals.hasObjCGCAttr() &&
1728 "Type cannot have multiple ObjCGCs!");
1729 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001730
John McCall8ccfcb52009-09-24 19:53:00 +00001731 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001732}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001733
John McCall4f5019e2010-12-19 02:44:49 +00001734const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1735 FunctionType::ExtInfo Info) {
1736 if (T->getExtInfo() == Info)
1737 return T;
1738
1739 QualType Result;
1740 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1741 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1742 } else {
1743 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1744 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1745 EPI.ExtInfo = Info;
1746 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1747 FPT->getNumArgs(), EPI);
1748 }
1749
1750 return cast<FunctionType>(Result.getTypePtr());
1751}
1752
Chris Lattnerc6395932007-06-22 20:56:16 +00001753/// getComplexType - Return the uniqued reference to the type for a complex
1754/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001755QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001756 // Unique pointers, to guarantee there is only one pointer of a particular
1757 // structure.
1758 llvm::FoldingSetNodeID ID;
1759 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001760
Chris Lattnerc6395932007-06-22 20:56:16 +00001761 void *InsertPos = 0;
1762 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1763 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001764
Chris Lattnerc6395932007-06-22 20:56:16 +00001765 // If the pointee type isn't canonical, this won't be a canonical type either,
1766 // so fill in the canonical type field.
1767 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001768 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001769 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001770
Chris Lattnerc6395932007-06-22 20:56:16 +00001771 // Get the new insert position for the node we care about.
1772 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001773 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001774 }
John McCall90d1c2d2009-09-24 23:30:46 +00001775 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001776 Types.push_back(New);
1777 ComplexTypes.InsertNode(New, InsertPos);
1778 return QualType(New, 0);
1779}
1780
Chris Lattner970e54e2006-11-12 00:37:36 +00001781/// getPointerType - Return the uniqued reference to the type for a pointer to
1782/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001783QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001784 // Unique pointers, to guarantee there is only one pointer of a particular
1785 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001786 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001787 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001788
Chris Lattner67521df2007-01-27 01:29:36 +00001789 void *InsertPos = 0;
1790 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001791 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001792
Chris Lattner7ccecb92006-11-12 08:50:50 +00001793 // If the pointee type isn't canonical, this won't be a canonical type either,
1794 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001795 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001796 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001797 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001798
Chris Lattner67521df2007-01-27 01:29:36 +00001799 // Get the new insert position for the node we care about.
1800 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001801 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001802 }
John McCall90d1c2d2009-09-24 23:30:46 +00001803 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001804 Types.push_back(New);
1805 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001806 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001807}
1808
Mike Stump11289f42009-09-09 15:08:12 +00001809/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001810/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001811QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001812 assert(T->isFunctionType() && "block of function types only");
1813 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001814 // structure.
1815 llvm::FoldingSetNodeID ID;
1816 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001817
Steve Naroffec33ed92008-08-27 16:04:49 +00001818 void *InsertPos = 0;
1819 if (BlockPointerType *PT =
1820 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1821 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001822
1823 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001824 // type either so fill in the canonical type field.
1825 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001826 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001827 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001828
Steve Naroffec33ed92008-08-27 16:04:49 +00001829 // Get the new insert position for the node we care about.
1830 BlockPointerType *NewIP =
1831 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001832 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001833 }
John McCall90d1c2d2009-09-24 23:30:46 +00001834 BlockPointerType *New
1835 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001836 Types.push_back(New);
1837 BlockPointerTypes.InsertNode(New, InsertPos);
1838 return QualType(New, 0);
1839}
1840
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001841/// getLValueReferenceType - Return the uniqued reference to the type for an
1842/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001843QualType
1844ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00001845 assert(getCanonicalType(T) != OverloadTy &&
1846 "Unresolved overloaded function type");
1847
Bill Wendling3708c182007-05-27 10:15:43 +00001848 // Unique pointers, to guarantee there is only one pointer of a particular
1849 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001850 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001851 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001852
1853 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001854 if (LValueReferenceType *RT =
1855 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001856 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001857
John McCallfc93cf92009-10-22 22:37:11 +00001858 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1859
Bill Wendling3708c182007-05-27 10:15:43 +00001860 // If the referencee type isn't canonical, this won't be a canonical type
1861 // either, so fill in the canonical type field.
1862 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001863 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1864 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1865 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001866
Bill Wendling3708c182007-05-27 10:15:43 +00001867 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001868 LValueReferenceType *NewIP =
1869 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001870 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001871 }
1872
John McCall90d1c2d2009-09-24 23:30:46 +00001873 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001874 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1875 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001876 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001877 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001878
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001879 return QualType(New, 0);
1880}
1881
1882/// getRValueReferenceType - Return the uniqued reference to the type for an
1883/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001884QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001885 // Unique pointers, to guarantee there is only one pointer of a particular
1886 // structure.
1887 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001888 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001889
1890 void *InsertPos = 0;
1891 if (RValueReferenceType *RT =
1892 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1893 return QualType(RT, 0);
1894
John McCallfc93cf92009-10-22 22:37:11 +00001895 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1896
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001897 // If the referencee type isn't canonical, this won't be a canonical type
1898 // either, so fill in the canonical type field.
1899 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001900 if (InnerRef || !T.isCanonical()) {
1901 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1902 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001903
1904 // Get the new insert position for the node we care about.
1905 RValueReferenceType *NewIP =
1906 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001907 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001908 }
1909
John McCall90d1c2d2009-09-24 23:30:46 +00001910 RValueReferenceType *New
1911 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001912 Types.push_back(New);
1913 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001914 return QualType(New, 0);
1915}
1916
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001917/// getMemberPointerType - Return the uniqued reference to the type for a
1918/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001919QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001920 // Unique pointers, to guarantee there is only one pointer of a particular
1921 // structure.
1922 llvm::FoldingSetNodeID ID;
1923 MemberPointerType::Profile(ID, T, Cls);
1924
1925 void *InsertPos = 0;
1926 if (MemberPointerType *PT =
1927 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1928 return QualType(PT, 0);
1929
1930 // If the pointee or class type isn't canonical, this won't be a canonical
1931 // type either, so fill in the canonical type field.
1932 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001933 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001934 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1935
1936 // Get the new insert position for the node we care about.
1937 MemberPointerType *NewIP =
1938 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001939 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001940 }
John McCall90d1c2d2009-09-24 23:30:46 +00001941 MemberPointerType *New
1942 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001943 Types.push_back(New);
1944 MemberPointerTypes.InsertNode(New, InsertPos);
1945 return QualType(New, 0);
1946}
1947
Mike Stump11289f42009-09-09 15:08:12 +00001948/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001949/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001950QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001951 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001952 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001953 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001954 assert((EltTy->isDependentType() ||
1955 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001956 "Constant array of VLAs is illegal!");
1957
Chris Lattnere2df3f92009-05-13 04:12:56 +00001958 // Convert the array size into a canonical width matching the pointer size for
1959 // the target.
1960 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001961 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001962 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00001963
Chris Lattner23b7eb62007-06-15 23:05:46 +00001964 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001965 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001966
Chris Lattner36f8e652007-01-27 08:31:04 +00001967 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001968 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001969 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001970 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001971
John McCall33ddac02011-01-19 10:06:00 +00001972 // If the element type isn't canonical or has qualifiers, this won't
1973 // be a canonical type either, so fill in the canonical type field.
1974 QualType Canon;
1975 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1976 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00001977 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001978 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00001979 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001980
Chris Lattner36f8e652007-01-27 08:31:04 +00001981 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001982 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001983 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001984 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001985 }
Mike Stump11289f42009-09-09 15:08:12 +00001986
John McCall90d1c2d2009-09-24 23:30:46 +00001987 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001988 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001989 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001990 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001991 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001992}
1993
John McCall06549462011-01-18 08:40:38 +00001994/// getVariableArrayDecayedType - Turns the given type, which may be
1995/// variably-modified, into the corresponding type with all the known
1996/// sizes replaced with [*].
1997QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1998 // Vastly most common case.
1999 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002000
John McCall06549462011-01-18 08:40:38 +00002001 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002002
John McCall06549462011-01-18 08:40:38 +00002003 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002004 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002005 switch (ty->getTypeClass()) {
2006#define TYPE(Class, Base)
2007#define ABSTRACT_TYPE(Class, Base)
2008#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2009#include "clang/AST/TypeNodes.def"
2010 llvm_unreachable("didn't desugar past all non-canonical types?");
2011
2012 // These types should never be variably-modified.
2013 case Type::Builtin:
2014 case Type::Complex:
2015 case Type::Vector:
2016 case Type::ExtVector:
2017 case Type::DependentSizedExtVector:
2018 case Type::ObjCObject:
2019 case Type::ObjCInterface:
2020 case Type::ObjCObjectPointer:
2021 case Type::Record:
2022 case Type::Enum:
2023 case Type::UnresolvedUsing:
2024 case Type::TypeOfExpr:
2025 case Type::TypeOf:
2026 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002027 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002028 case Type::DependentName:
2029 case Type::InjectedClassName:
2030 case Type::TemplateSpecialization:
2031 case Type::DependentTemplateSpecialization:
2032 case Type::TemplateTypeParm:
2033 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002034 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002035 case Type::PackExpansion:
2036 llvm_unreachable("type should never be variably-modified");
2037
2038 // These types can be variably-modified but should never need to
2039 // further decay.
2040 case Type::FunctionNoProto:
2041 case Type::FunctionProto:
2042 case Type::BlockPointer:
2043 case Type::MemberPointer:
2044 return type;
2045
2046 // These types can be variably-modified. All these modifications
2047 // preserve structure except as noted by comments.
2048 // TODO: if we ever care about optimizing VLAs, there are no-op
2049 // optimizations available here.
2050 case Type::Pointer:
2051 result = getPointerType(getVariableArrayDecayedType(
2052 cast<PointerType>(ty)->getPointeeType()));
2053 break;
2054
2055 case Type::LValueReference: {
2056 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2057 result = getLValueReferenceType(
2058 getVariableArrayDecayedType(lv->getPointeeType()),
2059 lv->isSpelledAsLValue());
2060 break;
2061 }
2062
2063 case Type::RValueReference: {
2064 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2065 result = getRValueReferenceType(
2066 getVariableArrayDecayedType(lv->getPointeeType()));
2067 break;
2068 }
2069
Eli Friedman0dfb8892011-10-06 23:00:33 +00002070 case Type::Atomic: {
2071 const AtomicType *at = cast<AtomicType>(ty);
2072 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2073 break;
2074 }
2075
John McCall06549462011-01-18 08:40:38 +00002076 case Type::ConstantArray: {
2077 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2078 result = getConstantArrayType(
2079 getVariableArrayDecayedType(cat->getElementType()),
2080 cat->getSize(),
2081 cat->getSizeModifier(),
2082 cat->getIndexTypeCVRQualifiers());
2083 break;
2084 }
2085
2086 case Type::DependentSizedArray: {
2087 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2088 result = getDependentSizedArrayType(
2089 getVariableArrayDecayedType(dat->getElementType()),
2090 dat->getSizeExpr(),
2091 dat->getSizeModifier(),
2092 dat->getIndexTypeCVRQualifiers(),
2093 dat->getBracketsRange());
2094 break;
2095 }
2096
2097 // Turn incomplete types into [*] types.
2098 case Type::IncompleteArray: {
2099 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2100 result = getVariableArrayType(
2101 getVariableArrayDecayedType(iat->getElementType()),
2102 /*size*/ 0,
2103 ArrayType::Normal,
2104 iat->getIndexTypeCVRQualifiers(),
2105 SourceRange());
2106 break;
2107 }
2108
2109 // Turn VLA types into [*] types.
2110 case Type::VariableArray: {
2111 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2112 result = getVariableArrayType(
2113 getVariableArrayDecayedType(vat->getElementType()),
2114 /*size*/ 0,
2115 ArrayType::Star,
2116 vat->getIndexTypeCVRQualifiers(),
2117 vat->getBracketsRange());
2118 break;
2119 }
2120 }
2121
2122 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002123 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002124}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002125
Steve Naroffcadebd02007-08-30 18:14:25 +00002126/// getVariableArrayType - Returns a non-unique reference to the type for a
2127/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002128QualType ASTContext::getVariableArrayType(QualType EltTy,
2129 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002130 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002131 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002132 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002133 // Since we don't unique expressions, it isn't possible to unique VLA's
2134 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002135 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002136
John McCall33ddac02011-01-19 10:06:00 +00002137 // Be sure to pull qualifiers off the element type.
2138 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2139 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002140 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002141 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002142 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002143 }
2144
John McCall90d1c2d2009-09-24 23:30:46 +00002145 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002146 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002147
2148 VariableArrayTypes.push_back(New);
2149 Types.push_back(New);
2150 return QualType(New, 0);
2151}
2152
Douglas Gregor4619e432008-12-05 23:32:09 +00002153/// getDependentSizedArrayType - Returns a non-unique reference to
2154/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002155/// type.
John McCall33ddac02011-01-19 10:06:00 +00002156QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2157 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002158 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002159 unsigned elementTypeQuals,
2160 SourceRange brackets) const {
2161 assert((!numElements || numElements->isTypeDependent() ||
2162 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002163 "Size must be type- or value-dependent!");
2164
John McCall33ddac02011-01-19 10:06:00 +00002165 // Dependently-sized array types that do not have a specified number
2166 // of elements will have their sizes deduced from a dependent
2167 // initializer. We do no canonicalization here at all, which is okay
2168 // because they can't be used in most locations.
2169 if (!numElements) {
2170 DependentSizedArrayType *newType
2171 = new (*this, TypeAlignment)
2172 DependentSizedArrayType(*this, elementType, QualType(),
2173 numElements, ASM, elementTypeQuals,
2174 brackets);
2175 Types.push_back(newType);
2176 return QualType(newType, 0);
2177 }
2178
2179 // Otherwise, we actually build a new type every time, but we
2180 // also build a canonical type.
2181
2182 SplitQualType canonElementType = getCanonicalType(elementType).split();
2183
2184 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002185 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002186 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002187 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002188 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002189
John McCall33ddac02011-01-19 10:06:00 +00002190 // Look for an existing type with these properties.
2191 DependentSizedArrayType *canonTy =
2192 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002193
John McCall33ddac02011-01-19 10:06:00 +00002194 // If we don't have one, build one.
2195 if (!canonTy) {
2196 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002197 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002198 QualType(), numElements, ASM, elementTypeQuals,
2199 brackets);
2200 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2201 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002202 }
2203
John McCall33ddac02011-01-19 10:06:00 +00002204 // Apply qualifiers from the element type to the array.
2205 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002206 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002207
John McCall33ddac02011-01-19 10:06:00 +00002208 // If we didn't need extra canonicalization for the element type,
2209 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002210 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002211 return canon;
2212
2213 // Otherwise, we need to build a type which follows the spelling
2214 // of the element type.
2215 DependentSizedArrayType *sugaredType
2216 = new (*this, TypeAlignment)
2217 DependentSizedArrayType(*this, elementType, canon, numElements,
2218 ASM, elementTypeQuals, brackets);
2219 Types.push_back(sugaredType);
2220 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002221}
2222
John McCall33ddac02011-01-19 10:06:00 +00002223QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002224 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002225 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002226 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002227 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002228
John McCall33ddac02011-01-19 10:06:00 +00002229 void *insertPos = 0;
2230 if (IncompleteArrayType *iat =
2231 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2232 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002233
2234 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002235 // either, so fill in the canonical type field. We also have to pull
2236 // qualifiers off the element type.
2237 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002238
John McCall33ddac02011-01-19 10:06:00 +00002239 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2240 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002241 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002242 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002243 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002244
2245 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002246 IncompleteArrayType *existing =
2247 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2248 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002249 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002250
John McCall33ddac02011-01-19 10:06:00 +00002251 IncompleteArrayType *newType = new (*this, TypeAlignment)
2252 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002253
John McCall33ddac02011-01-19 10:06:00 +00002254 IncompleteArrayTypes.InsertNode(newType, insertPos);
2255 Types.push_back(newType);
2256 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002257}
2258
Steve Naroff91fcddb2007-07-18 18:00:27 +00002259/// getVectorType - Return the unique reference to a vector type of
2260/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002261QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002262 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002263 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002264
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002265 // Check if we've already instantiated a vector of this type.
2266 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002267 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002268
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002269 void *InsertPos = 0;
2270 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2271 return QualType(VTP, 0);
2272
2273 // If the element type isn't canonical, this won't be a canonical type either,
2274 // so fill in the canonical type field.
2275 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002276 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002277 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002278
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002279 // Get the new insert position for the node we care about.
2280 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002281 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002282 }
John McCall90d1c2d2009-09-24 23:30:46 +00002283 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002284 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002285 VectorTypes.InsertNode(New, InsertPos);
2286 Types.push_back(New);
2287 return QualType(New, 0);
2288}
2289
Nate Begemance4d7fc2008-04-18 23:10:10 +00002290/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002291/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002292QualType
2293ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002294 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002295
Steve Naroff91fcddb2007-07-18 18:00:27 +00002296 // Check if we've already instantiated a vector of this type.
2297 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002298 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002299 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002300 void *InsertPos = 0;
2301 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2302 return QualType(VTP, 0);
2303
2304 // If the element type isn't canonical, this won't be a canonical type either,
2305 // so fill in the canonical type field.
2306 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002307 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002308 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002309
Steve Naroff91fcddb2007-07-18 18:00:27 +00002310 // Get the new insert position for the node we care about.
2311 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002312 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002313 }
John McCall90d1c2d2009-09-24 23:30:46 +00002314 ExtVectorType *New = new (*this, TypeAlignment)
2315 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002316 VectorTypes.InsertNode(New, InsertPos);
2317 Types.push_back(New);
2318 return QualType(New, 0);
2319}
2320
Jay Foad39c79802011-01-12 09:06:06 +00002321QualType
2322ASTContext::getDependentSizedExtVectorType(QualType vecType,
2323 Expr *SizeExpr,
2324 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002325 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002326 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002327 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002328
Douglas Gregor352169a2009-07-31 03:54:25 +00002329 void *InsertPos = 0;
2330 DependentSizedExtVectorType *Canon
2331 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2332 DependentSizedExtVectorType *New;
2333 if (Canon) {
2334 // We already have a canonical version of this array type; use it as
2335 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002336 New = new (*this, TypeAlignment)
2337 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2338 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002339 } else {
2340 QualType CanonVecTy = getCanonicalType(vecType);
2341 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002342 New = new (*this, TypeAlignment)
2343 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2344 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002345
2346 DependentSizedExtVectorType *CanonCheck
2347 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2348 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2349 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002350 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2351 } else {
2352 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2353 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002354 New = new (*this, TypeAlignment)
2355 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002356 }
2357 }
Mike Stump11289f42009-09-09 15:08:12 +00002358
Douglas Gregor758a8692009-06-17 21:51:59 +00002359 Types.push_back(New);
2360 return QualType(New, 0);
2361}
2362
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002363/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002364///
Jay Foad39c79802011-01-12 09:06:06 +00002365QualType
2366ASTContext::getFunctionNoProtoType(QualType ResultTy,
2367 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002368 const CallingConv DefaultCC = Info.getCC();
2369 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2370 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002371 // Unique functions, to guarantee there is only one function of a particular
2372 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002373 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002374 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002375
Chris Lattner47955de2007-01-27 08:37:20 +00002376 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002377 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002378 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002379 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002380
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002381 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002382 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002383 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002384 Canonical =
2385 getFunctionNoProtoType(getCanonicalType(ResultTy),
2386 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002387
Chris Lattner47955de2007-01-27 08:37:20 +00002388 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002389 FunctionNoProtoType *NewIP =
2390 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002391 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002392 }
Mike Stump11289f42009-09-09 15:08:12 +00002393
Roman Divacky65b88cd2011-03-01 17:40:53 +00002394 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002395 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002396 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002397 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002398 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002399 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002400}
2401
2402/// getFunctionType - Return a normal function type with a typed argument
2403/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002404QualType
2405ASTContext::getFunctionType(QualType ResultTy,
2406 const QualType *ArgArray, unsigned NumArgs,
2407 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002408 // Unique functions, to guarantee there is only one function of a particular
2409 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002410 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002411 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002412
2413 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002414 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002415 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002416 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002417
2418 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002419 bool isCanonical =
2420 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2421 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002422 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002423 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002424 isCanonical = false;
2425
Roman Divacky65b88cd2011-03-01 17:40:53 +00002426 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2427 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2428 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002429
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002430 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002431 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002432 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002433 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002434 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002435 CanonicalArgs.reserve(NumArgs);
2436 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002437 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002438
John McCalldb40c7f2010-12-14 08:05:40 +00002439 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002440 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002441 CanonicalEPI.ExceptionSpecType = EST_None;
2442 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002443 CanonicalEPI.ExtInfo
2444 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2445
Chris Lattner76a00cf2008-04-06 22:59:24 +00002446 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002447 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002448 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002449
Chris Lattnerfd4de792007-01-27 01:15:32 +00002450 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002451 FunctionProtoType *NewIP =
2452 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002453 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002454 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002455
John McCall31168b02011-06-15 23:02:42 +00002456 // FunctionProtoType objects are allocated with extra bytes after
2457 // them for three variable size arrays at the end:
2458 // - parameter types
2459 // - exception types
2460 // - consumed-arguments flags
2461 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002462 // expression, or information used to resolve the exception
2463 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002464 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002465 NumArgs * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002466 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002467 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002468 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002469 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002470 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002471 Size += 2 * sizeof(FunctionDecl*);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002472 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2473 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002474 }
John McCall31168b02011-06-15 23:02:42 +00002475 if (EPI.ConsumedArguments)
2476 Size += NumArgs * sizeof(bool);
2477
John McCalldb40c7f2010-12-14 08:05:40 +00002478 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002479 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2480 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002481 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002482 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002483 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002484 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002485}
Chris Lattneref51c202006-11-10 07:17:23 +00002486
John McCalle78aac42010-03-10 03:28:59 +00002487#ifndef NDEBUG
2488static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2489 if (!isa<CXXRecordDecl>(D)) return false;
2490 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2491 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2492 return true;
2493 if (RD->getDescribedClassTemplate() &&
2494 !isa<ClassTemplateSpecializationDecl>(RD))
2495 return true;
2496 return false;
2497}
2498#endif
2499
2500/// getInjectedClassNameType - Return the unique reference to the
2501/// injected class name type for the specified templated declaration.
2502QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002503 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002504 assert(NeedsInjectedClassNameType(Decl));
2505 if (Decl->TypeForDecl) {
2506 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002507 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002508 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2509 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2510 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2511 } else {
John McCall424cec92011-01-19 06:33:43 +00002512 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002513 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002514 Decl->TypeForDecl = newType;
2515 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002516 }
2517 return QualType(Decl->TypeForDecl, 0);
2518}
2519
Douglas Gregor83a586e2008-04-13 21:07:44 +00002520/// getTypeDeclType - Return the unique reference to the type for the
2521/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002522QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002523 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002524 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002525
Richard Smithdda56e42011-04-15 14:24:37 +00002526 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002527 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002528
John McCall96f0b5f2010-03-10 06:48:02 +00002529 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2530 "Template type parameter types are always available.");
2531
John McCall81e38502010-02-16 03:57:14 +00002532 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002533 assert(!Record->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002534 "struct/union has previous declaration");
2535 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002536 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002537 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002538 assert(!Enum->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002539 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002540 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002541 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002542 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002543 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2544 Decl->TypeForDecl = newType;
2545 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002546 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002547 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002548
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002549 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002550}
2551
Chris Lattner32d920b2007-01-26 02:01:53 +00002552/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002553/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002554QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002555ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2556 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002557 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002558
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002559 if (Canonical.isNull())
2560 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002561 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002562 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002563 Decl->TypeForDecl = newType;
2564 Types.push_back(newType);
2565 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002566}
2567
Jay Foad39c79802011-01-12 09:06:06 +00002568QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002569 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2570
Douglas Gregorec9fd132012-01-14 16:38:05 +00002571 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002572 if (PrevDecl->TypeForDecl)
2573 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2574
John McCall424cec92011-01-19 06:33:43 +00002575 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2576 Decl->TypeForDecl = newType;
2577 Types.push_back(newType);
2578 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002579}
2580
Jay Foad39c79802011-01-12 09:06:06 +00002581QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002582 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2583
Douglas Gregorec9fd132012-01-14 16:38:05 +00002584 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002585 if (PrevDecl->TypeForDecl)
2586 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2587
John McCall424cec92011-01-19 06:33:43 +00002588 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2589 Decl->TypeForDecl = newType;
2590 Types.push_back(newType);
2591 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002592}
2593
John McCall81904512011-01-06 01:58:22 +00002594QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2595 QualType modifiedType,
2596 QualType equivalentType) {
2597 llvm::FoldingSetNodeID id;
2598 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2599
2600 void *insertPos = 0;
2601 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2602 if (type) return QualType(type, 0);
2603
2604 QualType canon = getCanonicalType(equivalentType);
2605 type = new (*this, TypeAlignment)
2606 AttributedType(canon, attrKind, modifiedType, equivalentType);
2607
2608 Types.push_back(type);
2609 AttributedTypes.InsertNode(type, insertPos);
2610
2611 return QualType(type, 0);
2612}
2613
2614
John McCallcebee162009-10-18 09:09:24 +00002615/// \brief Retrieve a substitution-result type.
2616QualType
2617ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002618 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002619 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002620 && "replacement types must always be canonical");
2621
2622 llvm::FoldingSetNodeID ID;
2623 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2624 void *InsertPos = 0;
2625 SubstTemplateTypeParmType *SubstParm
2626 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2627
2628 if (!SubstParm) {
2629 SubstParm = new (*this, TypeAlignment)
2630 SubstTemplateTypeParmType(Parm, Replacement);
2631 Types.push_back(SubstParm);
2632 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2633 }
2634
2635 return QualType(SubstParm, 0);
2636}
2637
Douglas Gregorada4b792011-01-14 02:55:32 +00002638/// \brief Retrieve a
2639QualType ASTContext::getSubstTemplateTypeParmPackType(
2640 const TemplateTypeParmType *Parm,
2641 const TemplateArgument &ArgPack) {
2642#ifndef NDEBUG
2643 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2644 PEnd = ArgPack.pack_end();
2645 P != PEnd; ++P) {
2646 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2647 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2648 }
2649#endif
2650
2651 llvm::FoldingSetNodeID ID;
2652 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2653 void *InsertPos = 0;
2654 if (SubstTemplateTypeParmPackType *SubstParm
2655 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2656 return QualType(SubstParm, 0);
2657
2658 QualType Canon;
2659 if (!Parm->isCanonicalUnqualified()) {
2660 Canon = getCanonicalType(QualType(Parm, 0));
2661 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2662 ArgPack);
2663 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2664 }
2665
2666 SubstTemplateTypeParmPackType *SubstParm
2667 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2668 ArgPack);
2669 Types.push_back(SubstParm);
2670 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2671 return QualType(SubstParm, 0);
2672}
2673
Douglas Gregoreff93e02009-02-05 23:33:38 +00002674/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002675/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002676/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002677QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002678 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002679 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002680 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002681 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002682 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002683 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002684 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2685
2686 if (TypeParm)
2687 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002688
Chandler Carruth08836322011-05-01 00:51:33 +00002689 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002690 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002691 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002692
2693 TemplateTypeParmType *TypeCheck
2694 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2695 assert(!TypeCheck && "Template type parameter canonical type broken");
2696 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002697 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002698 TypeParm = new (*this, TypeAlignment)
2699 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002700
2701 Types.push_back(TypeParm);
2702 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2703
2704 return QualType(TypeParm, 0);
2705}
2706
John McCalle78aac42010-03-10 03:28:59 +00002707TypeSourceInfo *
2708ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2709 SourceLocation NameLoc,
2710 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002711 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002712 assert(!Name.getAsDependentTemplateName() &&
2713 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002714 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002715
2716 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2717 TemplateSpecializationTypeLoc TL
2718 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002719 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00002720 TL.setTemplateNameLoc(NameLoc);
2721 TL.setLAngleLoc(Args.getLAngleLoc());
2722 TL.setRAngleLoc(Args.getRAngleLoc());
2723 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2724 TL.setArgLocInfo(i, Args[i].getLocInfo());
2725 return DI;
2726}
2727
Mike Stump11289f42009-09-09 15:08:12 +00002728QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002729ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002730 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002731 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002732 assert(!Template.getAsDependentTemplateName() &&
2733 "No dependent template names here!");
2734
John McCall6b51f282009-11-23 01:53:49 +00002735 unsigned NumArgs = Args.size();
2736
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002737 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002738 ArgVec.reserve(NumArgs);
2739 for (unsigned i = 0; i != NumArgs; ++i)
2740 ArgVec.push_back(Args[i].getArgument());
2741
John McCall2408e322010-04-27 00:57:59 +00002742 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002743 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002744}
2745
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002746#ifndef NDEBUG
2747static bool hasAnyPackExpansions(const TemplateArgument *Args,
2748 unsigned NumArgs) {
2749 for (unsigned I = 0; I != NumArgs; ++I)
2750 if (Args[I].isPackExpansion())
2751 return true;
2752
2753 return true;
2754}
2755#endif
2756
John McCall0ad16662009-10-29 08:12:44 +00002757QualType
2758ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002759 const TemplateArgument *Args,
2760 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002761 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002762 assert(!Template.getAsDependentTemplateName() &&
2763 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002764 // Look through qualified template names.
2765 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2766 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002767
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002768 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00002769 Template.getAsTemplateDecl() &&
2770 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00002771 QualType CanonType;
2772 if (!Underlying.isNull())
2773 CanonType = getCanonicalType(Underlying);
2774 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002775 // We can get here with an alias template when the specialization contains
2776 // a pack expansion that does not match up with a parameter pack.
2777 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2778 "Caller must compute aliased type");
2779 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00002780 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2781 NumArgs);
2782 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002783
Douglas Gregora8e02e72009-07-28 23:00:59 +00002784 // Allocate the (non-canonical) template specialization type, but don't
2785 // try to unique it: these types typically have location information that
2786 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002787 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2788 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002789 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002790 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002791 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002792 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2793 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002794
Douglas Gregor8bf42052009-02-09 18:46:07 +00002795 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002796 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002797}
2798
Mike Stump11289f42009-09-09 15:08:12 +00002799QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002800ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2801 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002802 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002803 assert(!Template.getAsDependentTemplateName() &&
2804 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002805
Douglas Gregore29139c2011-03-03 17:04:51 +00002806 // Look through qualified template names.
2807 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2808 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002809
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002810 // Build the canonical template specialization type.
2811 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002812 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002813 CanonArgs.reserve(NumArgs);
2814 for (unsigned I = 0; I != NumArgs; ++I)
2815 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2816
2817 // Determine whether this canonical template specialization type already
2818 // exists.
2819 llvm::FoldingSetNodeID ID;
2820 TemplateSpecializationType::Profile(ID, CanonTemplate,
2821 CanonArgs.data(), NumArgs, *this);
2822
2823 void *InsertPos = 0;
2824 TemplateSpecializationType *Spec
2825 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2826
2827 if (!Spec) {
2828 // Allocate a new canonical template specialization type.
2829 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2830 sizeof(TemplateArgument) * NumArgs),
2831 TypeAlignment);
2832 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2833 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002834 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002835 Types.push_back(Spec);
2836 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2837 }
2838
2839 assert(Spec->isDependentType() &&
2840 "Non-dependent template-id type must have a canonical type");
2841 return QualType(Spec, 0);
2842}
2843
2844QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002845ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2846 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002847 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002848 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002849 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002850
2851 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002852 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002853 if (T)
2854 return QualType(T, 0);
2855
Douglas Gregorc42075a2010-02-04 18:10:26 +00002856 QualType Canon = NamedType;
2857 if (!Canon.isCanonical()) {
2858 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002859 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2860 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002861 (void)CheckT;
2862 }
2863
Abramo Bagnara6150c882010-05-11 21:36:43 +00002864 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002865 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002866 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002867 return QualType(T, 0);
2868}
2869
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002870QualType
Jay Foad39c79802011-01-12 09:06:06 +00002871ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002872 llvm::FoldingSetNodeID ID;
2873 ParenType::Profile(ID, InnerType);
2874
2875 void *InsertPos = 0;
2876 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2877 if (T)
2878 return QualType(T, 0);
2879
2880 QualType Canon = InnerType;
2881 if (!Canon.isCanonical()) {
2882 Canon = getCanonicalType(InnerType);
2883 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2884 assert(!CheckT && "Paren canonical type broken");
2885 (void)CheckT;
2886 }
2887
2888 T = new (*this) ParenType(InnerType, Canon);
2889 Types.push_back(T);
2890 ParenTypes.InsertNode(T, InsertPos);
2891 return QualType(T, 0);
2892}
2893
Douglas Gregor02085352010-03-31 20:19:30 +00002894QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2895 NestedNameSpecifier *NNS,
2896 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002897 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002898 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2899
2900 if (Canon.isNull()) {
2901 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002902 ElaboratedTypeKeyword CanonKeyword = Keyword;
2903 if (Keyword == ETK_None)
2904 CanonKeyword = ETK_Typename;
2905
2906 if (CanonNNS != NNS || CanonKeyword != Keyword)
2907 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002908 }
2909
2910 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002911 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002912
2913 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002914 DependentNameType *T
2915 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002916 if (T)
2917 return QualType(T, 0);
2918
Douglas Gregor02085352010-03-31 20:19:30 +00002919 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002920 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002921 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002922 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002923}
2924
Mike Stump11289f42009-09-09 15:08:12 +00002925QualType
John McCallc392f372010-06-11 00:33:02 +00002926ASTContext::getDependentTemplateSpecializationType(
2927 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002928 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002929 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002930 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002931 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002932 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00002933 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2934 ArgCopy.push_back(Args[I].getArgument());
2935 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2936 ArgCopy.size(),
2937 ArgCopy.data());
2938}
2939
2940QualType
2941ASTContext::getDependentTemplateSpecializationType(
2942 ElaboratedTypeKeyword Keyword,
2943 NestedNameSpecifier *NNS,
2944 const IdentifierInfo *Name,
2945 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002946 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00002947 assert((!NNS || NNS->isDependent()) &&
2948 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00002949
Douglas Gregorc42075a2010-02-04 18:10:26 +00002950 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002951 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2952 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002953
2954 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002955 DependentTemplateSpecializationType *T
2956 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002957 if (T)
2958 return QualType(T, 0);
2959
John McCallc392f372010-06-11 00:33:02 +00002960 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002961
John McCallc392f372010-06-11 00:33:02 +00002962 ElaboratedTypeKeyword CanonKeyword = Keyword;
2963 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2964
2965 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002966 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00002967 for (unsigned I = 0; I != NumArgs; ++I) {
2968 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2969 if (!CanonArgs[I].structurallyEquals(Args[I]))
2970 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002971 }
2972
John McCallc392f372010-06-11 00:33:02 +00002973 QualType Canon;
2974 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2975 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2976 Name, NumArgs,
2977 CanonArgs.data());
2978
2979 // Find the insert position again.
2980 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2981 }
2982
2983 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2984 sizeof(TemplateArgument) * NumArgs),
2985 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002986 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002987 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002988 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002989 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002990 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002991}
2992
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002993QualType ASTContext::getPackExpansionType(QualType Pattern,
2994 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002995 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002996 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002997
2998 assert(Pattern->containsUnexpandedParameterPack() &&
2999 "Pack expansions must expand one or more parameter packs");
3000 void *InsertPos = 0;
3001 PackExpansionType *T
3002 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3003 if (T)
3004 return QualType(T, 0);
3005
3006 QualType Canon;
3007 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003008 Canon = getCanonicalType(Pattern);
3009 // The canonical type might not contain an unexpanded parameter pack, if it
3010 // contains an alias template specialization which ignores one of its
3011 // parameters.
3012 if (Canon->containsUnexpandedParameterPack()) {
3013 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003014
Richard Smith68eea502012-07-16 00:20:35 +00003015 // Find the insert position again, in case we inserted an element into
3016 // PackExpansionTypes and invalidated our insert position.
3017 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3018 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003019 }
3020
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003021 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003022 Types.push_back(T);
3023 PackExpansionTypes.InsertNode(T, InsertPos);
3024 return QualType(T, 0);
3025}
3026
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003027/// CmpProtocolNames - Comparison predicate for sorting protocols
3028/// alphabetically.
3029static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3030 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003031 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003032}
3033
John McCall8b07ec22010-05-15 11:32:37 +00003034static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003035 unsigned NumProtocols) {
3036 if (NumProtocols == 0) return true;
3037
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003038 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3039 return false;
3040
John McCallfc93cf92009-10-22 22:37:11 +00003041 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003042 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3043 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003044 return false;
3045 return true;
3046}
3047
3048static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003049 unsigned &NumProtocols) {
3050 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003051
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003052 // Sort protocols, keyed by name.
3053 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3054
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003055 // Canonicalize.
3056 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3057 Protocols[I] = Protocols[I]->getCanonicalDecl();
3058
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003059 // Remove duplicates.
3060 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3061 NumProtocols = ProtocolsEnd-Protocols;
3062}
3063
John McCall8b07ec22010-05-15 11:32:37 +00003064QualType ASTContext::getObjCObjectType(QualType BaseType,
3065 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003066 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003067 // If the base type is an interface and there aren't any protocols
3068 // to add, then the interface type will do just fine.
3069 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3070 return BaseType;
3071
3072 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003073 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003074 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00003075 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00003076 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3077 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003078
John McCall8b07ec22010-05-15 11:32:37 +00003079 // Build the canonical type, which has the canonical base type and
3080 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003081 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003082 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3083 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3084 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003085 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003086 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003087 unsigned UniqueCount = NumProtocols;
3088
John McCallfc93cf92009-10-22 22:37:11 +00003089 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003090 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3091 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003092 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003093 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3094 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003095 }
3096
3097 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003098 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3099 }
3100
3101 unsigned Size = sizeof(ObjCObjectTypeImpl);
3102 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3103 void *Mem = Allocate(Size, TypeAlignment);
3104 ObjCObjectTypeImpl *T =
3105 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3106
3107 Types.push_back(T);
3108 ObjCObjectTypes.InsertNode(T, InsertPos);
3109 return QualType(T, 0);
3110}
3111
3112/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3113/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003114QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003115 llvm::FoldingSetNodeID ID;
3116 ObjCObjectPointerType::Profile(ID, ObjectT);
3117
3118 void *InsertPos = 0;
3119 if (ObjCObjectPointerType *QT =
3120 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3121 return QualType(QT, 0);
3122
3123 // Find the canonical object type.
3124 QualType Canonical;
3125 if (!ObjectT.isCanonical()) {
3126 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3127
3128 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003129 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3130 }
3131
Douglas Gregorf85bee62010-02-08 22:59:26 +00003132 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003133 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3134 ObjCObjectPointerType *QType =
3135 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003136
Steve Narofffb4330f2009-06-17 22:40:22 +00003137 Types.push_back(QType);
3138 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003139 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003140}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003141
Douglas Gregor1c283312010-08-11 12:19:30 +00003142/// getObjCInterfaceType - Return the unique reference to the type for the
3143/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003144QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3145 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003146 if (Decl->TypeForDecl)
3147 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003148
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003149 if (PrevDecl) {
3150 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3151 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3152 return QualType(PrevDecl->TypeForDecl, 0);
3153 }
3154
Douglas Gregor7671e532011-12-16 16:34:57 +00003155 // Prefer the definition, if there is one.
3156 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3157 Decl = Def;
3158
Douglas Gregor1c283312010-08-11 12:19:30 +00003159 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3160 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3161 Decl->TypeForDecl = T;
3162 Types.push_back(T);
3163 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003164}
3165
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003166/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3167/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003168/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003169/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003170/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003171QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003172 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003173 if (tofExpr->isTypeDependent()) {
3174 llvm::FoldingSetNodeID ID;
3175 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003176
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003177 void *InsertPos = 0;
3178 DependentTypeOfExprType *Canon
3179 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3180 if (Canon) {
3181 // We already have a "canonical" version of an identical, dependent
3182 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003183 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003184 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003185 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003186 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003187 Canon
3188 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003189 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3190 toe = Canon;
3191 }
3192 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003193 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003194 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003195 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003196 Types.push_back(toe);
3197 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003198}
3199
Steve Naroffa773cd52007-08-01 18:02:17 +00003200/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3201/// TypeOfType AST's. The only motivation to unique these nodes would be
3202/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003203/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003204/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003205QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003206 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003207 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003208 Types.push_back(tot);
3209 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003210}
3211
Anders Carlssonad6bd352009-06-24 21:24:56 +00003212
Anders Carlsson81df7b82009-06-24 19:06:50 +00003213/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3214/// DecltypeType AST's. The only motivation to unique these nodes would be
3215/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003216/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003217/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003218QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003219 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003220
3221 // C++0x [temp.type]p2:
3222 // If an expression e involves a template parameter, decltype(e) denotes a
3223 // unique dependent type. Two such decltype-specifiers refer to the same
3224 // type only if their expressions are equivalent (14.5.6.1).
3225 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003226 llvm::FoldingSetNodeID ID;
3227 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003228
Douglas Gregora21f6c32009-07-30 23:36:40 +00003229 void *InsertPos = 0;
3230 DependentDecltypeType *Canon
3231 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3232 if (Canon) {
3233 // We already have a "canonical" version of an equivalent, dependent
3234 // decltype type. Use that as our canonical type.
Richard Smithef8bf432012-08-13 20:08:14 +00003235 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003236 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003237 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003238 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003239 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003240 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3241 dt = Canon;
3242 }
3243 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003244 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3245 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003246 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003247 Types.push_back(dt);
3248 return QualType(dt, 0);
3249}
3250
Alexis Hunte852b102011-05-24 22:41:36 +00003251/// getUnaryTransformationType - We don't unique these, since the memory
3252/// savings are minimal and these are rare.
3253QualType ASTContext::getUnaryTransformType(QualType BaseType,
3254 QualType UnderlyingType,
3255 UnaryTransformType::UTTKind Kind)
3256 const {
3257 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003258 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3259 Kind,
3260 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003261 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003262 Types.push_back(Ty);
3263 return QualType(Ty, 0);
3264}
3265
Richard Smithb2bc2e62011-02-21 20:05:19 +00003266/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003267QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00003268 void *InsertPos = 0;
3269 if (!DeducedType.isNull()) {
3270 // Look in the folding set for an existing type.
3271 llvm::FoldingSetNodeID ID;
3272 AutoType::Profile(ID, DeducedType);
3273 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3274 return QualType(AT, 0);
3275 }
3276
3277 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3278 Types.push_back(AT);
3279 if (InsertPos)
3280 AutoTypes.InsertNode(AT, InsertPos);
3281 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003282}
3283
Eli Friedman0dfb8892011-10-06 23:00:33 +00003284/// getAtomicType - Return the uniqued reference to the atomic type for
3285/// the given value type.
3286QualType ASTContext::getAtomicType(QualType T) const {
3287 // Unique pointers, to guarantee there is only one pointer of a particular
3288 // structure.
3289 llvm::FoldingSetNodeID ID;
3290 AtomicType::Profile(ID, T);
3291
3292 void *InsertPos = 0;
3293 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3294 return QualType(AT, 0);
3295
3296 // If the atomic value type isn't canonical, this won't be a canonical type
3297 // either, so fill in the canonical type field.
3298 QualType Canonical;
3299 if (!T.isCanonical()) {
3300 Canonical = getAtomicType(getCanonicalType(T));
3301
3302 // Get the new insert position for the node we care about.
3303 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3304 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3305 }
3306 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3307 Types.push_back(New);
3308 AtomicTypes.InsertNode(New, InsertPos);
3309 return QualType(New, 0);
3310}
3311
Richard Smith02e85f32011-04-14 22:09:26 +00003312/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3313QualType ASTContext::getAutoDeductType() const {
3314 if (AutoDeductTy.isNull())
3315 AutoDeductTy = getAutoType(QualType());
3316 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3317 return AutoDeductTy;
3318}
3319
3320/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3321QualType ASTContext::getAutoRRefDeductType() const {
3322 if (AutoRRefDeductTy.isNull())
3323 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3324 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3325 return AutoRRefDeductTy;
3326}
3327
Chris Lattnerfb072462007-01-23 05:45:31 +00003328/// getTagDeclType - Return the unique reference to the type for the
3329/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003330QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003331 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003332 // FIXME: What is the design on getTagDeclType when it requires casting
3333 // away const? mutable?
3334 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003335}
3336
Mike Stump11289f42009-09-09 15:08:12 +00003337/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3338/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3339/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003340CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003341 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003342}
Chris Lattnerfb072462007-01-23 05:45:31 +00003343
Hans Wennborg27541db2011-10-27 08:29:09 +00003344/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3345CanQualType ASTContext::getIntMaxType() const {
3346 return getFromTargetType(Target->getIntMaxType());
3347}
3348
3349/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3350CanQualType ASTContext::getUIntMaxType() const {
3351 return getFromTargetType(Target->getUIntMaxType());
3352}
3353
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003354/// getSignedWCharType - Return the type of "signed wchar_t".
3355/// Used when in C++, as a GCC extension.
3356QualType ASTContext::getSignedWCharType() const {
3357 // FIXME: derive from "Target" ?
3358 return WCharTy;
3359}
3360
3361/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3362/// Used when in C++, as a GCC extension.
3363QualType ASTContext::getUnsignedWCharType() const {
3364 // FIXME: derive from "Target" ?
3365 return UnsignedIntTy;
3366}
3367
Hans Wennborg27541db2011-10-27 08:29:09 +00003368/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003369/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3370QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003371 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003372}
3373
Chris Lattnera21ad802008-04-02 05:18:44 +00003374//===----------------------------------------------------------------------===//
3375// Type Operators
3376//===----------------------------------------------------------------------===//
3377
Jay Foad39c79802011-01-12 09:06:06 +00003378CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003379 // Push qualifiers into arrays, and then discard any remaining
3380 // qualifiers.
3381 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003382 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003383 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003384 QualType Result;
3385 if (isa<ArrayType>(Ty)) {
3386 Result = getArrayDecayedType(QualType(Ty,0));
3387 } else if (isa<FunctionType>(Ty)) {
3388 Result = getPointerType(QualType(Ty, 0));
3389 } else {
3390 Result = QualType(Ty, 0);
3391 }
3392
3393 return CanQualType::CreateUnsafe(Result);
3394}
3395
John McCall6c9dd522011-01-18 07:41:22 +00003396QualType ASTContext::getUnqualifiedArrayType(QualType type,
3397 Qualifiers &quals) {
3398 SplitQualType splitType = type.getSplitUnqualifiedType();
3399
3400 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3401 // the unqualified desugared type and then drops it on the floor.
3402 // We then have to strip that sugar back off with
3403 // getUnqualifiedDesugaredType(), which is silly.
3404 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003405 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003406
3407 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003408 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003409 quals = splitType.Quals;
3410 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003411 }
3412
John McCall6c9dd522011-01-18 07:41:22 +00003413 // Otherwise, recurse on the array's element type.
3414 QualType elementType = AT->getElementType();
3415 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3416
3417 // If that didn't change the element type, AT has no qualifiers, so we
3418 // can just use the results in splitType.
3419 if (elementType == unqualElementType) {
3420 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003421 quals = splitType.Quals;
3422 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003423 }
3424
3425 // Otherwise, add in the qualifiers from the outermost type, then
3426 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003427 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003428
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003429 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003430 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003431 CAT->getSizeModifier(), 0);
3432 }
3433
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003434 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003435 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003436 }
3437
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003438 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003439 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003440 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003441 VAT->getSizeModifier(),
3442 VAT->getIndexTypeCVRQualifiers(),
3443 VAT->getBracketsRange());
3444 }
3445
3446 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003447 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003448 DSAT->getSizeModifier(), 0,
3449 SourceRange());
3450}
3451
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003452/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3453/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3454/// they point to and return true. If T1 and T2 aren't pointer types
3455/// or pointer-to-member types, or if they are not similar at this
3456/// level, returns false and leaves T1 and T2 unchanged. Top-level
3457/// qualifiers on T1 and T2 are ignored. This function will typically
3458/// be called in a loop that successively "unwraps" pointer and
3459/// pointer-to-member types to compare them at each level.
3460bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3461 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3462 *T2PtrType = T2->getAs<PointerType>();
3463 if (T1PtrType && T2PtrType) {
3464 T1 = T1PtrType->getPointeeType();
3465 T2 = T2PtrType->getPointeeType();
3466 return true;
3467 }
3468
3469 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3470 *T2MPType = T2->getAs<MemberPointerType>();
3471 if (T1MPType && T2MPType &&
3472 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3473 QualType(T2MPType->getClass(), 0))) {
3474 T1 = T1MPType->getPointeeType();
3475 T2 = T2MPType->getPointeeType();
3476 return true;
3477 }
3478
David Blaikiebbafb8a2012-03-11 07:00:24 +00003479 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003480 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3481 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3482 if (T1OPType && T2OPType) {
3483 T1 = T1OPType->getPointeeType();
3484 T2 = T2OPType->getPointeeType();
3485 return true;
3486 }
3487 }
3488
3489 // FIXME: Block pointers, too?
3490
3491 return false;
3492}
3493
Jay Foad39c79802011-01-12 09:06:06 +00003494DeclarationNameInfo
3495ASTContext::getNameForTemplate(TemplateName Name,
3496 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003497 switch (Name.getKind()) {
3498 case TemplateName::QualifiedTemplate:
3499 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003500 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003501 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3502 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003503
John McCalld9dfe3a2011-06-30 08:33:18 +00003504 case TemplateName::OverloadedTemplate: {
3505 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3506 // DNInfo work in progress: CHECKME: what about DNLoc?
3507 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3508 }
3509
3510 case TemplateName::DependentTemplate: {
3511 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003512 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003513 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003514 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3515 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003516 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003517 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3518 // DNInfo work in progress: FIXME: source locations?
3519 DeclarationNameLoc DNLoc;
3520 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3521 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3522 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003523 }
3524 }
3525
John McCalld9dfe3a2011-06-30 08:33:18 +00003526 case TemplateName::SubstTemplateTemplateParm: {
3527 SubstTemplateTemplateParmStorage *subst
3528 = Name.getAsSubstTemplateTemplateParm();
3529 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3530 NameLoc);
3531 }
3532
3533 case TemplateName::SubstTemplateTemplateParmPack: {
3534 SubstTemplateTemplateParmPackStorage *subst
3535 = Name.getAsSubstTemplateTemplateParmPack();
3536 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3537 NameLoc);
3538 }
3539 }
3540
3541 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003542}
3543
Jay Foad39c79802011-01-12 09:06:06 +00003544TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003545 switch (Name.getKind()) {
3546 case TemplateName::QualifiedTemplate:
3547 case TemplateName::Template: {
3548 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003549 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003550 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003551 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3552
3553 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003554 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003555 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003556
John McCalld9dfe3a2011-06-30 08:33:18 +00003557 case TemplateName::OverloadedTemplate:
3558 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003559
John McCalld9dfe3a2011-06-30 08:33:18 +00003560 case TemplateName::DependentTemplate: {
3561 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3562 assert(DTN && "Non-dependent template names must refer to template decls.");
3563 return DTN->CanonicalTemplateName;
3564 }
3565
3566 case TemplateName::SubstTemplateTemplateParm: {
3567 SubstTemplateTemplateParmStorage *subst
3568 = Name.getAsSubstTemplateTemplateParm();
3569 return getCanonicalTemplateName(subst->getReplacement());
3570 }
3571
3572 case TemplateName::SubstTemplateTemplateParmPack: {
3573 SubstTemplateTemplateParmPackStorage *subst
3574 = Name.getAsSubstTemplateTemplateParmPack();
3575 TemplateTemplateParmDecl *canonParameter
3576 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3577 TemplateArgument canonArgPack
3578 = getCanonicalTemplateArgument(subst->getArgumentPack());
3579 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3580 }
3581 }
3582
3583 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003584}
3585
Douglas Gregoradee3e32009-11-11 23:06:43 +00003586bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3587 X = getCanonicalTemplateName(X);
3588 Y = getCanonicalTemplateName(Y);
3589 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3590}
3591
Mike Stump11289f42009-09-09 15:08:12 +00003592TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003593ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003594 switch (Arg.getKind()) {
3595 case TemplateArgument::Null:
3596 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003597
Douglas Gregora8e02e72009-07-28 23:00:59 +00003598 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003599 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003600
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003601 case TemplateArgument::Declaration: {
3602 if (Decl *D = Arg.getAsDecl())
3603 return TemplateArgument(D->getCanonicalDecl());
3604 return TemplateArgument((Decl*)0);
3605 }
Mike Stump11289f42009-09-09 15:08:12 +00003606
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003607 case TemplateArgument::Template:
3608 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003609
3610 case TemplateArgument::TemplateExpansion:
3611 return TemplateArgument(getCanonicalTemplateName(
3612 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003613 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003614
Douglas Gregora8e02e72009-07-28 23:00:59 +00003615 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00003616 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003617
Douglas Gregora8e02e72009-07-28 23:00:59 +00003618 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003619 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003620
Douglas Gregora8e02e72009-07-28 23:00:59 +00003621 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003622 if (Arg.pack_size() == 0)
3623 return Arg;
3624
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003625 TemplateArgument *CanonArgs
3626 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003627 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003628 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003629 AEnd = Arg.pack_end();
3630 A != AEnd; (void)++A, ++Idx)
3631 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003632
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003633 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003634 }
3635 }
3636
3637 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003638 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003639}
3640
Douglas Gregor333489b2009-03-27 23:10:48 +00003641NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003642ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003643 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003644 return 0;
3645
3646 switch (NNS->getKind()) {
3647 case NestedNameSpecifier::Identifier:
3648 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003649 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003650 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3651 NNS->getAsIdentifier());
3652
3653 case NestedNameSpecifier::Namespace:
3654 // A namespace is canonical; build a nested-name-specifier with
3655 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003656 return NestedNameSpecifier::Create(*this, 0,
3657 NNS->getAsNamespace()->getOriginalNamespace());
3658
3659 case NestedNameSpecifier::NamespaceAlias:
3660 // A namespace is canonical; build a nested-name-specifier with
3661 // this namespace and no prefix.
3662 return NestedNameSpecifier::Create(*this, 0,
3663 NNS->getAsNamespaceAlias()->getNamespace()
3664 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003665
3666 case NestedNameSpecifier::TypeSpec:
3667 case NestedNameSpecifier::TypeSpecWithTemplate: {
3668 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003669
3670 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3671 // break it apart into its prefix and identifier, then reconsititute those
3672 // as the canonical nested-name-specifier. This is required to canonicalize
3673 // a dependent nested-name-specifier involving typedefs of dependent-name
3674 // types, e.g.,
3675 // typedef typename T::type T1;
3676 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00003677 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3678 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00003679 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003680
Eli Friedman5358a0a2012-03-03 04:09:56 +00003681 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3682 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3683 // first place?
John McCall33ddac02011-01-19 10:06:00 +00003684 return NestedNameSpecifier::Create(*this, 0, false,
3685 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003686 }
3687
3688 case NestedNameSpecifier::Global:
3689 // The global specifier is canonical and unique.
3690 return NNS;
3691 }
3692
David Blaikie8a40f702012-01-17 06:56:22 +00003693 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00003694}
3695
Chris Lattner7adf0762008-08-04 07:31:14 +00003696
Jay Foad39c79802011-01-12 09:06:06 +00003697const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003698 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003699 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003700 // Handle the common positive case fast.
3701 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3702 return AT;
3703 }
Mike Stump11289f42009-09-09 15:08:12 +00003704
John McCall8ccfcb52009-09-24 19:53:00 +00003705 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003706 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003707 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003708
John McCall8ccfcb52009-09-24 19:53:00 +00003709 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003710 // implements C99 6.7.3p8: "If the specification of an array type includes
3711 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003712
Chris Lattner7adf0762008-08-04 07:31:14 +00003713 // If we get here, we either have type qualifiers on the type, or we have
3714 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003715 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003716
John McCall33ddac02011-01-19 10:06:00 +00003717 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003718 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00003719
Chris Lattner7adf0762008-08-04 07:31:14 +00003720 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00003721 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00003722 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003723 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003724
Chris Lattner7adf0762008-08-04 07:31:14 +00003725 // Otherwise, we have an array and we have qualifiers on it. Push the
3726 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003727 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003728
Chris Lattner7adf0762008-08-04 07:31:14 +00003729 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3730 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3731 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003732 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003733 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3734 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3735 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003736 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003737
Mike Stump11289f42009-09-09 15:08:12 +00003738 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003739 = dyn_cast<DependentSizedArrayType>(ATy))
3740 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003741 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003742 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003743 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003744 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003745 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003746
Chris Lattner7adf0762008-08-04 07:31:14 +00003747 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003748 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003749 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003750 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003751 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003752 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003753}
3754
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003755QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003756 // C99 6.7.5.3p7:
3757 // A declaration of a parameter as "array of type" shall be
3758 // adjusted to "qualified pointer to type", where the type
3759 // qualifiers (if any) are those specified within the [ and ] of
3760 // the array type derivation.
3761 if (T->isArrayType())
3762 return getArrayDecayedType(T);
3763
3764 // C99 6.7.5.3p8:
3765 // A declaration of a parameter as "function returning type"
3766 // shall be adjusted to "pointer to function returning type", as
3767 // in 6.3.2.1.
3768 if (T->isFunctionType())
3769 return getPointerType(T);
3770
3771 return T;
3772}
3773
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003774QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003775 T = getVariableArrayDecayedType(T);
3776 T = getAdjustedParameterType(T);
3777 return T.getUnqualifiedType();
3778}
3779
Chris Lattnera21ad802008-04-02 05:18:44 +00003780/// getArrayDecayedType - Return the properly qualified result of decaying the
3781/// specified array type to a pointer. This operation is non-trivial when
3782/// handling typedefs etc. The canonical type of "T" must be an array type,
3783/// this returns a pointer to a properly qualified element of the array.
3784///
3785/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003786QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003787 // Get the element type with 'getAsArrayType' so that we don't lose any
3788 // typedefs in the element type of the array. This also handles propagation
3789 // of type qualifiers from the array type into the element type if present
3790 // (C99 6.7.3p8).
3791 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3792 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003793
Chris Lattner7adf0762008-08-04 07:31:14 +00003794 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003795
3796 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003797 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003798}
3799
John McCall33ddac02011-01-19 10:06:00 +00003800QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3801 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003802}
3803
John McCall33ddac02011-01-19 10:06:00 +00003804QualType ASTContext::getBaseElementType(QualType type) const {
3805 Qualifiers qs;
3806 while (true) {
3807 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003808 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00003809 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003810
John McCall33ddac02011-01-19 10:06:00 +00003811 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00003812 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003813 }
Mike Stump11289f42009-09-09 15:08:12 +00003814
John McCall33ddac02011-01-19 10:06:00 +00003815 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003816}
3817
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003818/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003819uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003820ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3821 uint64_t ElementCount = 1;
3822 do {
3823 ElementCount *= CA->getSize().getZExtValue();
3824 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3825 } while (CA);
3826 return ElementCount;
3827}
3828
Steve Naroff0af91202007-04-27 21:51:21 +00003829/// getFloatingRank - Return a relative rank for floating point types.
3830/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003831static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003832 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003833 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003834
John McCall9dd450b2009-09-21 23:43:11 +00003835 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3836 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003837 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003838 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00003839 case BuiltinType::Float: return FloatRank;
3840 case BuiltinType::Double: return DoubleRank;
3841 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003842 }
3843}
3844
Mike Stump11289f42009-09-09 15:08:12 +00003845/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3846/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003847/// 'typeDomain' is a real floating point or complex type.
3848/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003849QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3850 QualType Domain) const {
3851 FloatingRank EltRank = getFloatingRank(Size);
3852 if (Domain->isComplexType()) {
3853 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003854 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00003855 case FloatRank: return FloatComplexTy;
3856 case DoubleRank: return DoubleComplexTy;
3857 case LongDoubleRank: return LongDoubleComplexTy;
3858 }
Steve Naroff0af91202007-04-27 21:51:21 +00003859 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003860
3861 assert(Domain->isRealFloatingType() && "Unknown domain!");
3862 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003863 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003864 case FloatRank: return FloatTy;
3865 case DoubleRank: return DoubleTy;
3866 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003867 }
David Blaikief47fa302012-01-17 02:30:50 +00003868 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00003869}
3870
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003871/// getFloatingTypeOrder - Compare the rank of the two specified floating
3872/// point types, ignoring the domain of the type (i.e. 'double' ==
3873/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003874/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003875int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003876 FloatingRank LHSR = getFloatingRank(LHS);
3877 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003878
Chris Lattnerb90739d2008-04-06 23:38:49 +00003879 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003880 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003881 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003882 return 1;
3883 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003884}
3885
Chris Lattner76a00cf2008-04-06 22:59:24 +00003886/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3887/// routine will assert if passed a built-in type that isn't an integer or enum,
3888/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003889unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003890 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003891
Chris Lattner76a00cf2008-04-06 22:59:24 +00003892 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003893 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003894 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003895 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003896 case BuiltinType::Char_S:
3897 case BuiltinType::Char_U:
3898 case BuiltinType::SChar:
3899 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003900 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003901 case BuiltinType::Short:
3902 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003903 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003904 case BuiltinType::Int:
3905 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003906 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003907 case BuiltinType::Long:
3908 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003909 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003910 case BuiltinType::LongLong:
3911 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003912 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003913 case BuiltinType::Int128:
3914 case BuiltinType::UInt128:
3915 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003916 }
3917}
3918
Eli Friedman629ffb92009-08-20 04:21:42 +00003919/// \brief Whether this is a promotable bitfield reference according
3920/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3921///
3922/// \returns the type this bit-field will promote to, or NULL if no
3923/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003924QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003925 if (E->isTypeDependent() || E->isValueDependent())
3926 return QualType();
3927
Eli Friedman629ffb92009-08-20 04:21:42 +00003928 FieldDecl *Field = E->getBitField();
3929 if (!Field)
3930 return QualType();
3931
3932 QualType FT = Field->getType();
3933
Richard Smithcaf33902011-10-10 18:28:20 +00003934 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00003935 uint64_t IntSize = getTypeSize(IntTy);
3936 // GCC extension compatibility: if the bit-field size is less than or equal
3937 // to the size of int, it gets promoted no matter what its type is.
3938 // For instance, unsigned long bf : 4 gets promoted to signed int.
3939 if (BitWidth < IntSize)
3940 return IntTy;
3941
3942 if (BitWidth == IntSize)
3943 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3944
3945 // Types bigger than int are not subject to promotions, and therefore act
3946 // like the base type.
3947 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3948 // is ridiculous.
3949 return QualType();
3950}
3951
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003952/// getPromotedIntegerType - Returns the type that Promotable will
3953/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3954/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003955QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003956 assert(!Promotable.isNull());
3957 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003958 if (const EnumType *ET = Promotable->getAs<EnumType>())
3959 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00003960
3961 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3962 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3963 // (3.9.1) can be converted to a prvalue of the first of the following
3964 // types that can represent all the values of its underlying type:
3965 // int, unsigned int, long int, unsigned long int, long long int, or
3966 // unsigned long long int [...]
3967 // FIXME: Is there some better way to compute this?
3968 if (BT->getKind() == BuiltinType::WChar_S ||
3969 BT->getKind() == BuiltinType::WChar_U ||
3970 BT->getKind() == BuiltinType::Char16 ||
3971 BT->getKind() == BuiltinType::Char32) {
3972 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3973 uint64_t FromSize = getTypeSize(BT);
3974 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3975 LongLongTy, UnsignedLongLongTy };
3976 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3977 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3978 if (FromSize < ToSize ||
3979 (FromSize == ToSize &&
3980 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3981 return PromoteTypes[Idx];
3982 }
3983 llvm_unreachable("char type should fit into long long");
3984 }
3985 }
3986
3987 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003988 if (Promotable->isSignedIntegerType())
3989 return IntTy;
3990 uint64_t PromotableSize = getTypeSize(Promotable);
3991 uint64_t IntSize = getTypeSize(IntTy);
3992 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3993 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3994}
3995
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003996/// \brief Recurses in pointer/array types until it finds an objc retainable
3997/// type and returns its ownership.
3998Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3999 while (!T.isNull()) {
4000 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4001 return T.getObjCLifetime();
4002 if (T->isArrayType())
4003 T = getBaseElementType(T);
4004 else if (const PointerType *PT = T->getAs<PointerType>())
4005 T = PT->getPointeeType();
4006 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004007 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004008 else
4009 break;
4010 }
4011
4012 return Qualifiers::OCL_None;
4013}
4014
Mike Stump11289f42009-09-09 15:08:12 +00004015/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004016/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004017/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004018int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004019 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4020 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004021 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004022
Chris Lattner76a00cf2008-04-06 22:59:24 +00004023 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4024 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004025
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004026 unsigned LHSRank = getIntegerRank(LHSC);
4027 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004028
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004029 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4030 if (LHSRank == RHSRank) return 0;
4031 return LHSRank > RHSRank ? 1 : -1;
4032 }
Mike Stump11289f42009-09-09 15:08:12 +00004033
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004034 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4035 if (LHSUnsigned) {
4036 // If the unsigned [LHS] type is larger, return it.
4037 if (LHSRank >= RHSRank)
4038 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004039
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004040 // If the signed type can represent all values of the unsigned type, it
4041 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004042 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004043 return -1;
4044 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004045
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004046 // If the unsigned [RHS] type is larger, return it.
4047 if (RHSRank >= LHSRank)
4048 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004049
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004050 // If the signed type can represent all values of the unsigned type, it
4051 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004052 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004053 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004054}
Anders Carlsson98f07902007-08-17 05:31:46 +00004055
Anders Carlsson6d417272009-11-14 21:45:58 +00004056static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004057CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4058 DeclContext *DC, IdentifierInfo *Id) {
4059 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004060 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004061 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004062 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004063 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004064}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004065
Mike Stump11289f42009-09-09 15:08:12 +00004066// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004067QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004068 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00004069 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004070 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004071 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00004072 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004073
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004074 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004075
Anders Carlsson98f07902007-08-17 05:31:46 +00004076 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004077 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004078 // int flags;
4079 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004080 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004081 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004082 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004083 FieldTypes[3] = LongTy;
4084
Anders Carlsson98f07902007-08-17 05:31:46 +00004085 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004086 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004087 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004088 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004089 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00004090 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00004091 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004092 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004093 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004094 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004095 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004096 }
4097
Douglas Gregord5058122010-02-11 01:19:42 +00004098 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004099 }
Mike Stump11289f42009-09-09 15:08:12 +00004100
Anders Carlsson98f07902007-08-17 05:31:46 +00004101 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004102}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004103
Douglas Gregor512b0772009-04-23 22:29:11 +00004104void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004105 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004106 assert(Rec && "Invalid CFConstantStringType");
4107 CFConstantStringTypeDecl = Rec->getDecl();
4108}
4109
Jay Foad39c79802011-01-12 09:06:06 +00004110QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004111 if (BlockDescriptorType)
4112 return getTagDeclType(BlockDescriptorType);
4113
4114 RecordDecl *T;
4115 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004116 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004117 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00004118 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004119
4120 QualType FieldTypes[] = {
4121 UnsignedLongTy,
4122 UnsignedLongTy,
4123 };
4124
4125 const char *FieldNames[] = {
4126 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004127 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004128 };
4129
4130 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004131 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00004132 SourceLocation(),
4133 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004134 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00004135 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004136 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004137 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004138 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00004139 T->addDecl(Field);
4140 }
4141
Douglas Gregord5058122010-02-11 01:19:42 +00004142 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004143
4144 BlockDescriptorType = T;
4145
4146 return getTagDeclType(BlockDescriptorType);
4147}
4148
Jay Foad39c79802011-01-12 09:06:06 +00004149QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004150 if (BlockDescriptorExtendedType)
4151 return getTagDeclType(BlockDescriptorExtendedType);
4152
4153 RecordDecl *T;
4154 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004155 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004156 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00004157 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004158
4159 QualType FieldTypes[] = {
4160 UnsignedLongTy,
4161 UnsignedLongTy,
4162 getPointerType(VoidPtrTy),
4163 getPointerType(VoidPtrTy)
4164 };
4165
4166 const char *FieldNames[] = {
4167 "reserved",
4168 "Size",
4169 "CopyFuncPtr",
4170 "DestroyFuncPtr"
4171 };
4172
4173 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004174 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004175 SourceLocation(),
4176 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004177 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004178 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004179 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004180 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004181 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004182 T->addDecl(Field);
4183 }
4184
Douglas Gregord5058122010-02-11 01:19:42 +00004185 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004186
4187 BlockDescriptorExtendedType = T;
4188
4189 return getTagDeclType(BlockDescriptorExtendedType);
4190}
4191
Jay Foad39c79802011-01-12 09:06:06 +00004192bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCall31168b02011-06-15 23:02:42 +00004193 if (Ty->isObjCRetainableType())
Mike Stump94967902009-10-21 18:16:27 +00004194 return true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004195 if (getLangOpts().CPlusPlus) {
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004196 if (const RecordType *RT = Ty->getAs<RecordType>()) {
4197 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntfcaeae42011-05-25 20:50:04 +00004198 return RD->hasConstCopyConstructor();
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004199
4200 }
4201 }
Mike Stump94967902009-10-21 18:16:27 +00004202 return false;
4203}
4204
Jay Foad39c79802011-01-12 09:06:06 +00004205QualType
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004206ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00004207 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00004208 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00004209 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00004210 // unsigned int __flags;
4211 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00004212 // void *__copy_helper; // as needed
4213 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00004214 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00004215 // } *
4216
Mike Stump94967902009-10-21 18:16:27 +00004217 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
4218
4219 // FIXME: Move up
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004220 SmallString<36> Name;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00004221 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
4222 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00004223 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004224 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00004225 T->startDefinition();
4226 QualType Int32Ty = IntTy;
4227 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
4228 QualType FieldTypes[] = {
4229 getPointerType(VoidPtrTy),
4230 getPointerType(getTagDeclType(T)),
4231 Int32Ty,
4232 Int32Ty,
4233 getPointerType(VoidPtrTy),
4234 getPointerType(VoidPtrTy),
4235 Ty
4236 };
4237
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004238 StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00004239 "__isa",
4240 "__forwarding",
4241 "__flags",
4242 "__size",
4243 "__copy_helper",
4244 "__destroy_helper",
4245 DeclName,
4246 };
4247
4248 for (size_t i = 0; i < 7; ++i) {
4249 if (!HasCopyAndDispose && i >=4 && i <= 5)
4250 continue;
4251 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00004252 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00004253 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004254 FieldTypes[i], /*TInfo=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004255 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004256 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004257 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00004258 T->addDecl(Field);
4259 }
4260
Douglas Gregord5058122010-02-11 01:19:42 +00004261 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00004262
4263 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00004264}
4265
Douglas Gregorbab8a962011-09-08 01:46:34 +00004266TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4267 if (!ObjCInstanceTypeDecl)
4268 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4269 getTranslationUnitDecl(),
4270 SourceLocation(),
4271 SourceLocation(),
4272 &Idents.get("instancetype"),
4273 getTrivialTypeSourceInfo(getObjCIdType()));
4274 return ObjCInstanceTypeDecl;
4275}
4276
Anders Carlsson18acd442007-10-29 06:33:42 +00004277// This returns true if a type has been typedefed to BOOL:
4278// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004279static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004280 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004281 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4282 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004283
Anders Carlssond8499822007-10-29 05:01:08 +00004284 return false;
4285}
4286
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004287/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004288/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004289CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004290 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4291 return CharUnits::Zero();
4292
Ken Dyck40775002010-01-11 17:06:35 +00004293 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004294
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004295 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004296 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004297 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004298 // Treat arrays as pointers, since that's how they're passed in.
4299 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004300 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004301 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004302}
4303
4304static inline
4305std::string charUnitsToString(const CharUnits &CU) {
4306 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004307}
4308
John McCall351762c2011-02-07 10:33:21 +00004309/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004310/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004311std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4312 std::string S;
4313
David Chisnall950a9512009-11-17 19:33:30 +00004314 const BlockDecl *Decl = Expr->getBlockDecl();
4315 QualType BlockTy =
4316 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4317 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00004318 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004319 // Compute size of all parameters.
4320 // Start with computing size of a pointer in number of bytes.
4321 // FIXME: There might(should) be a better way of doing this computation!
4322 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004323 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4324 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004325 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004326 E = Decl->param_end(); PI != E; ++PI) {
4327 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004328 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004329 if (sz.isZero())
4330 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004331 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004332 ParmOffset += sz;
4333 }
4334 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004335 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004336 // Block pointer and offset.
4337 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004338
4339 // Argument types.
4340 ParmOffset = PtrSize;
4341 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4342 Decl->param_end(); PI != E; ++PI) {
4343 ParmVarDecl *PVDecl = *PI;
4344 QualType PType = PVDecl->getOriginalType();
4345 if (const ArrayType *AT =
4346 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4347 // Use array's original type only if it has known number of
4348 // elements.
4349 if (!isa<ConstantArrayType>(AT))
4350 PType = PVDecl->getType();
4351 } else if (PType->isFunctionType())
4352 PType = PVDecl->getType();
4353 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004354 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004355 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004356 }
John McCall351762c2011-02-07 10:33:21 +00004357
4358 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004359}
4360
Douglas Gregora9d84932011-05-27 01:19:52 +00004361bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004362 std::string& S) {
4363 // Encode result type.
4364 getObjCEncodingForType(Decl->getResultType(), S);
4365 CharUnits ParmOffset;
4366 // Compute size of all parameters.
4367 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4368 E = Decl->param_end(); PI != E; ++PI) {
4369 QualType PType = (*PI)->getType();
4370 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004371 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004372 continue;
4373
David Chisnall50e4eba2010-12-30 14:05:53 +00004374 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004375 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004376 ParmOffset += sz;
4377 }
4378 S += charUnitsToString(ParmOffset);
4379 ParmOffset = CharUnits::Zero();
4380
4381 // Argument types.
4382 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4383 E = Decl->param_end(); PI != E; ++PI) {
4384 ParmVarDecl *PVDecl = *PI;
4385 QualType PType = PVDecl->getOriginalType();
4386 if (const ArrayType *AT =
4387 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4388 // Use array's original type only if it has known number of
4389 // elements.
4390 if (!isa<ConstantArrayType>(AT))
4391 PType = PVDecl->getType();
4392 } else if (PType->isFunctionType())
4393 PType = PVDecl->getType();
4394 getObjCEncodingForType(PType, S);
4395 S += charUnitsToString(ParmOffset);
4396 ParmOffset += getObjCEncodingTypeSize(PType);
4397 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004398
4399 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004400}
4401
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004402/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4403/// method parameter or return type. If Extended, include class names and
4404/// block object types.
4405void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4406 QualType T, std::string& S,
4407 bool Extended) const {
4408 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4409 getObjCEncodingForTypeQualifier(QT, S);
4410 // Encode parameter type.
4411 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4412 true /*OutermostType*/,
4413 false /*EncodingProperty*/,
4414 false /*StructField*/,
4415 Extended /*EncodeBlockParameters*/,
4416 Extended /*EncodeClassNames*/);
4417}
4418
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004419/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004420/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004421bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004422 std::string& S,
4423 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004424 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004425 // Encode return type.
4426 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4427 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004428 // Compute size of all parameters.
4429 // Start with computing size of a pointer in number of bytes.
4430 // FIXME: There might(should) be a better way of doing this computation!
4431 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004432 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004433 // The first two arguments (self and _cmd) are pointers; account for
4434 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004435 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004436 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004437 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004438 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004439 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004440 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004441 continue;
4442
Ken Dyck40775002010-01-11 17:06:35 +00004443 assert (sz.isPositive() &&
4444 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004445 ParmOffset += sz;
4446 }
Ken Dyck40775002010-01-11 17:06:35 +00004447 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004448 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004449 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004450
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004451 // Argument types.
4452 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004453 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004454 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004455 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004456 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004457 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004458 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4459 // Use array's original type only if it has known number of
4460 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004461 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004462 PType = PVDecl->getType();
4463 } else if (PType->isFunctionType())
4464 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004465 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4466 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004467 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004468 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004469 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004470
4471 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004472}
4473
Daniel Dunbar4932b362008-08-28 04:38:10 +00004474/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004475/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004476/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4477/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004478/// Property attributes are stored as a comma-delimited C string. The simple
4479/// attributes readonly and bycopy are encoded as single characters. The
4480/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4481/// encoded as single characters, followed by an identifier. Property types
4482/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004483/// these attributes are defined by the following enumeration:
4484/// @code
4485/// enum PropertyAttributes {
4486/// kPropertyReadOnly = 'R', // property is read-only.
4487/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4488/// kPropertyByref = '&', // property is a reference to the value last assigned
4489/// kPropertyDynamic = 'D', // property is dynamic
4490/// kPropertyGetter = 'G', // followed by getter selector name
4491/// kPropertySetter = 'S', // followed by setter selector name
4492/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004493/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004494/// kPropertyWeak = 'W' // 'weak' property
4495/// kPropertyStrong = 'P' // property GC'able
4496/// kPropertyNonAtomic = 'N' // property non-atomic
4497/// };
4498/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004499void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004500 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004501 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004502 // Collect information from the property implementation decl(s).
4503 bool Dynamic = false;
4504 ObjCPropertyImplDecl *SynthesizePID = 0;
4505
4506 // FIXME: Duplicated code due to poor abstraction.
4507 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004508 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004509 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4510 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004511 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004512 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004513 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004514 if (PID->getPropertyDecl() == PD) {
4515 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4516 Dynamic = true;
4517 } else {
4518 SynthesizePID = PID;
4519 }
4520 }
4521 }
4522 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004523 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004524 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004525 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004526 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004527 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004528 if (PID->getPropertyDecl() == PD) {
4529 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4530 Dynamic = true;
4531 } else {
4532 SynthesizePID = PID;
4533 }
4534 }
Mike Stump11289f42009-09-09 15:08:12 +00004535 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004536 }
4537 }
4538
4539 // FIXME: This is not very efficient.
4540 S = "T";
4541
4542 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004543 // GCC has some special rules regarding encoding of properties which
4544 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004545 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004546 true /* outermost type */,
4547 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004548
4549 if (PD->isReadOnly()) {
4550 S += ",R";
4551 } else {
4552 switch (PD->getSetterKind()) {
4553 case ObjCPropertyDecl::Assign: break;
4554 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004555 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004556 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004557 }
4558 }
4559
4560 // It really isn't clear at all what this means, since properties
4561 // are "dynamic by default".
4562 if (Dynamic)
4563 S += ",D";
4564
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004565 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4566 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004567
Daniel Dunbar4932b362008-08-28 04:38:10 +00004568 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4569 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004570 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004571 }
4572
4573 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4574 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004575 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004576 }
4577
4578 if (SynthesizePID) {
4579 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4580 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004581 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004582 }
4583
4584 // FIXME: OBJCGC: weak & strong
4585}
4586
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004587/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004588/// Another legacy compatibility encoding: 32-bit longs are encoded as
4589/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004590/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4591///
4592void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004593 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004594 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004595 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004596 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004597 else
Jay Foad39c79802011-01-12 09:06:06 +00004598 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004599 PointeeTy = IntTy;
4600 }
4601 }
4602}
4603
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004604void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004605 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004606 // We follow the behavior of gcc, expanding structures which are
4607 // directly pointed to, and expanding embedded structures. Note that
4608 // these rules are sufficient to prevent recursive encoding of the
4609 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004610 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004611 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004612}
4613
David Chisnallb190a2c2010-06-04 01:10:52 +00004614static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4615 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004616 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnallb190a2c2010-06-04 01:10:52 +00004617 case BuiltinType::Void: return 'v';
4618 case BuiltinType::Bool: return 'B';
4619 case BuiltinType::Char_U:
4620 case BuiltinType::UChar: return 'C';
4621 case BuiltinType::UShort: return 'S';
4622 case BuiltinType::UInt: return 'I';
4623 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004624 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004625 case BuiltinType::UInt128: return 'T';
4626 case BuiltinType::ULongLong: return 'Q';
4627 case BuiltinType::Char_S:
4628 case BuiltinType::SChar: return 'c';
4629 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004630 case BuiltinType::WChar_S:
4631 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004632 case BuiltinType::Int: return 'i';
4633 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004634 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004635 case BuiltinType::LongLong: return 'q';
4636 case BuiltinType::Int128: return 't';
4637 case BuiltinType::Float: return 'f';
4638 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004639 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004640 }
4641}
4642
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004643static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4644 EnumDecl *Enum = ET->getDecl();
4645
4646 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4647 if (!Enum->isFixed())
4648 return 'i';
4649
4650 // The encoding of a fixed enum type matches its fixed underlying type.
4651 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4652}
4653
Jay Foad39c79802011-01-12 09:06:06 +00004654static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004655 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00004656 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004657 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004658 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4659 // The GNU runtime requires more information; bitfields are encoded as b,
4660 // then the offset (in bits) of the first element, then the type of the
4661 // bitfield, then the size in bits. For example, in this structure:
4662 //
4663 // struct
4664 // {
4665 // int integer;
4666 // int flags:2;
4667 // };
4668 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4669 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4670 // information is not especially sensible, but we're stuck with it for
4671 // compatibility with GCC, although providing it breaks anything that
4672 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00004673 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004674 const RecordDecl *RD = FD->getParent();
4675 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004676 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004677 if (const EnumType *ET = T->getAs<EnumType>())
4678 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnall6f0a7d22010-12-26 20:12:30 +00004679 else
Jay Foad39c79802011-01-12 09:06:06 +00004680 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004681 }
Richard Smithcaf33902011-10-10 18:28:20 +00004682 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004683}
4684
Daniel Dunbar07d07852009-10-18 21:17:35 +00004685// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004686void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4687 bool ExpandPointedToStructures,
4688 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004689 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004690 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004691 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004692 bool StructField,
4693 bool EncodeBlockParameters,
4694 bool EncodeClassNames) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004695 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004696 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004697 return EncodeBitField(this, S, T, FD);
4698 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004699 return;
4700 }
Mike Stump11289f42009-09-09 15:08:12 +00004701
John McCall9dd450b2009-09-21 23:43:11 +00004702 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004703 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004704 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004705 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004706 return;
4707 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004708
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004709 // encoding for pointer or r3eference types.
4710 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004711 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004712 if (PT->isObjCSelType()) {
4713 S += ':';
4714 return;
4715 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004716 PointeeTy = PT->getPointeeType();
4717 }
4718 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4719 PointeeTy = RT->getPointeeType();
4720 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004721 bool isReadOnly = false;
4722 // For historical/compatibility reasons, the read-only qualifier of the
4723 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4724 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004725 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004726 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004727 if (OutermostType && T.isConstQualified()) {
4728 isReadOnly = true;
4729 S += 'r';
4730 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004731 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004732 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004733 while (P->getAs<PointerType>())
4734 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004735 if (P.isConstQualified()) {
4736 isReadOnly = true;
4737 S += 'r';
4738 }
4739 }
4740 if (isReadOnly) {
4741 // Another legacy compatibility encoding. Some ObjC qualifier and type
4742 // combinations need to be rearranged.
4743 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004744 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004745 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004746 }
Mike Stump11289f42009-09-09 15:08:12 +00004747
Anders Carlssond8499822007-10-29 05:01:08 +00004748 if (PointeeTy->isCharType()) {
4749 // char pointer types should be encoded as '*' unless it is a
4750 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004751 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004752 S += '*';
4753 return;
4754 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004755 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004756 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4757 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4758 S += '#';
4759 return;
4760 }
4761 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4762 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4763 S += '@';
4764 return;
4765 }
4766 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004767 }
Anders Carlssond8499822007-10-29 05:01:08 +00004768 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004769 getLegacyIntegralTypeEncoding(PointeeTy);
4770
Mike Stump11289f42009-09-09 15:08:12 +00004771 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004772 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004773 return;
4774 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004775
Chris Lattnere7cabb92009-07-13 00:10:46 +00004776 if (const ArrayType *AT =
4777 // Ignore type qualifiers etc.
4778 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004779 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004780 // Incomplete arrays are encoded as a pointer to the array element.
4781 S += '^';
4782
Mike Stump11289f42009-09-09 15:08:12 +00004783 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004784 false, ExpandStructures, FD);
4785 } else {
4786 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004787
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004788 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4789 if (getTypeSize(CAT->getElementType()) == 0)
4790 S += '0';
4791 else
4792 S += llvm::utostr(CAT->getSize().getZExtValue());
4793 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004794 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004795 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4796 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00004797 S += '0';
4798 }
Mike Stump11289f42009-09-09 15:08:12 +00004799
4800 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004801 false, ExpandStructures, FD);
4802 S += ']';
4803 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004804 return;
4805 }
Mike Stump11289f42009-09-09 15:08:12 +00004806
John McCall9dd450b2009-09-21 23:43:11 +00004807 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004808 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004809 return;
4810 }
Mike Stump11289f42009-09-09 15:08:12 +00004811
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004812 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004813 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004814 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004815 // Anonymous structures print as '?'
4816 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4817 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004818 if (ClassTemplateSpecializationDecl *Spec
4819 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4820 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4821 std::string TemplateArgsStr
4822 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004823 TemplateArgs.data(),
4824 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00004825 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004826
4827 S += TemplateArgsStr;
4828 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004829 } else {
4830 S += '?';
4831 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004832 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004833 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004834 if (!RDecl->isUnion()) {
4835 getObjCEncodingForStructureImpl(RDecl, S, FD);
4836 } else {
4837 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4838 FieldEnd = RDecl->field_end();
4839 Field != FieldEnd; ++Field) {
4840 if (FD) {
4841 S += '"';
4842 S += Field->getNameAsString();
4843 S += '"';
4844 }
Mike Stump11289f42009-09-09 15:08:12 +00004845
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004846 // Special case bit-fields.
4847 if (Field->isBitField()) {
4848 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00004849 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004850 } else {
4851 QualType qt = Field->getType();
4852 getLegacyIntegralTypeEncoding(qt);
4853 getObjCEncodingForTypeImpl(qt, S, false, true,
4854 FD, /*OutermostType*/false,
4855 /*EncodingProperty*/false,
4856 /*StructField*/true);
4857 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004858 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004859 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004860 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004861 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004862 return;
4863 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004864
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004865 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004866 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004867 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004868 else
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004869 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004870 return;
4871 }
Mike Stump11289f42009-09-09 15:08:12 +00004872
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004873 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004874 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004875 if (EncodeBlockParameters) {
4876 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4877
4878 S += '<';
4879 // Block return type
4880 getObjCEncodingForTypeImpl(FT->getResultType(), S,
4881 ExpandPointedToStructures, ExpandStructures,
4882 FD,
4883 false /* OutermostType */,
4884 EncodingProperty,
4885 false /* StructField */,
4886 EncodeBlockParameters,
4887 EncodeClassNames);
4888 // Block self
4889 S += "@?";
4890 // Block parameters
4891 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4892 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4893 E = FPT->arg_type_end(); I && (I != E); ++I) {
4894 getObjCEncodingForTypeImpl(*I, S,
4895 ExpandPointedToStructures,
4896 ExpandStructures,
4897 FD,
4898 false /* OutermostType */,
4899 EncodingProperty,
4900 false /* StructField */,
4901 EncodeBlockParameters,
4902 EncodeClassNames);
4903 }
4904 }
4905 S += '>';
4906 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004907 return;
4908 }
Mike Stump11289f42009-09-09 15:08:12 +00004909
John McCall8b07ec22010-05-15 11:32:37 +00004910 // Ignore protocol qualifiers when mangling at this level.
4911 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4912 T = OT->getBaseType();
4913
John McCall8ccfcb52009-09-24 19:53:00 +00004914 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004915 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004916 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004917 S += '{';
4918 const IdentifierInfo *II = OI->getIdentifier();
4919 S += II->getName();
4920 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00004921 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004922 DeepCollectObjCIvars(OI, true, Ivars);
4923 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004924 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004925 if (Field->isBitField())
4926 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004927 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004928 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004929 }
4930 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004931 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004932 }
Mike Stump11289f42009-09-09 15:08:12 +00004933
John McCall9dd450b2009-09-21 23:43:11 +00004934 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004935 if (OPT->isObjCIdType()) {
4936 S += '@';
4937 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004938 }
Mike Stump11289f42009-09-09 15:08:12 +00004939
Steve Narofff0c86112009-10-28 22:03:49 +00004940 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4941 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4942 // Since this is a binary compatibility issue, need to consult with runtime
4943 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004944 S += '#';
4945 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004946 }
Mike Stump11289f42009-09-09 15:08:12 +00004947
Chris Lattnere7cabb92009-07-13 00:10:46 +00004948 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004949 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004950 ExpandPointedToStructures,
4951 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004952 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004953 // Note that we do extended encoding of protocol qualifer list
4954 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004955 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004956 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4957 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004958 S += '<';
4959 S += (*I)->getNameAsString();
4960 S += '>';
4961 }
4962 S += '"';
4963 }
4964 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004965 }
Mike Stump11289f42009-09-09 15:08:12 +00004966
Chris Lattnere7cabb92009-07-13 00:10:46 +00004967 QualType PointeeTy = OPT->getPointeeType();
4968 if (!EncodingProperty &&
4969 isa<TypedefType>(PointeeTy.getTypePtr())) {
4970 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004971 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004972 // {...};
4973 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004974 getObjCEncodingForTypeImpl(PointeeTy, S,
4975 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004976 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004977 return;
4978 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004979
4980 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004981 if (OPT->getInterfaceDecl() &&
4982 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004983 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004984 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004985 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4986 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004987 S += '<';
4988 S += (*I)->getNameAsString();
4989 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004990 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004991 S += '"';
4992 }
4993 return;
4994 }
Mike Stump11289f42009-09-09 15:08:12 +00004995
John McCalla9e6e8d2010-05-17 23:56:34 +00004996 // gcc just blithely ignores member pointers.
4997 // TODO: maybe there should be a mangling for these
4998 if (T->getAs<MemberPointerType>())
4999 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005000
5001 if (T->isVectorType()) {
5002 // This matches gcc's encoding, even though technically it is
5003 // insufficient.
5004 // FIXME. We should do a better job than gcc.
5005 return;
5006 }
5007
David Blaikie83d382b2011-09-23 05:06:16 +00005008 llvm_unreachable("@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00005009}
5010
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005011void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5012 std::string &S,
5013 const FieldDecl *FD,
5014 bool includeVBases) const {
5015 assert(RDecl && "Expected non-null RecordDecl");
5016 assert(!RDecl->isUnion() && "Should not be called for unions");
5017 if (!RDecl->getDefinition())
5018 return;
5019
5020 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5021 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5022 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5023
5024 if (CXXRec) {
5025 for (CXXRecordDecl::base_class_iterator
5026 BI = CXXRec->bases_begin(),
5027 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5028 if (!BI->isVirtual()) {
5029 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005030 if (base->isEmpty())
5031 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005032 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005033 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5034 std::make_pair(offs, base));
5035 }
5036 }
5037 }
5038
5039 unsigned i = 0;
5040 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5041 FieldEnd = RDecl->field_end();
5042 Field != FieldEnd; ++Field, ++i) {
5043 uint64_t offs = layout.getFieldOffset(i);
5044 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00005045 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005046 }
5047
5048 if (CXXRec && includeVBases) {
5049 for (CXXRecordDecl::base_class_iterator
5050 BI = CXXRec->vbases_begin(),
5051 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5052 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005053 if (base->isEmpty())
5054 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005055 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005056 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5057 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5058 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005059 }
5060 }
5061
5062 CharUnits size;
5063 if (CXXRec) {
5064 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5065 } else {
5066 size = layout.getSize();
5067 }
5068
5069 uint64_t CurOffs = 0;
5070 std::multimap<uint64_t, NamedDecl *>::iterator
5071 CurLayObj = FieldOrBaseOffsets.begin();
5072
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005073 if (CXXRec && CXXRec->isDynamicClass() &&
5074 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005075 if (FD) {
5076 S += "\"_vptr$";
5077 std::string recname = CXXRec->getNameAsString();
5078 if (recname.empty()) recname = "?";
5079 S += recname;
5080 S += '"';
5081 }
5082 S += "^^?";
5083 CurOffs += getTypeSize(VoidPtrTy);
5084 }
5085
5086 if (!RDecl->hasFlexibleArrayMember()) {
5087 // Mark the end of the structure.
5088 uint64_t offs = toBits(size);
5089 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5090 std::make_pair(offs, (NamedDecl*)0));
5091 }
5092
5093 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5094 assert(CurOffs <= CurLayObj->first);
5095
5096 if (CurOffs < CurLayObj->first) {
5097 uint64_t padding = CurLayObj->first - CurOffs;
5098 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5099 // packing/alignment of members is different that normal, in which case
5100 // the encoding will be out-of-sync with the real layout.
5101 // If the runtime switches to just consider the size of types without
5102 // taking into account alignment, we could make padding explicit in the
5103 // encoding (e.g. using arrays of chars). The encoding strings would be
5104 // longer then though.
5105 CurOffs += padding;
5106 }
5107
5108 NamedDecl *dcl = CurLayObj->second;
5109 if (dcl == 0)
5110 break; // reached end of structure.
5111
5112 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5113 // We expand the bases without their virtual bases since those are going
5114 // in the initial structure. Note that this differs from gcc which
5115 // expands virtual bases each time one is encountered in the hierarchy,
5116 // making the encoding type bigger than it really is.
5117 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005118 assert(!base->isEmpty());
5119 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005120 } else {
5121 FieldDecl *field = cast<FieldDecl>(dcl);
5122 if (FD) {
5123 S += '"';
5124 S += field->getNameAsString();
5125 S += '"';
5126 }
5127
5128 if (field->isBitField()) {
5129 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00005130 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005131 } else {
5132 QualType qt = field->getType();
5133 getLegacyIntegralTypeEncoding(qt);
5134 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5135 /*OutermostType*/false,
5136 /*EncodingProperty*/false,
5137 /*StructField*/true);
5138 CurOffs += getTypeSize(field->getType());
5139 }
5140 }
5141 }
5142}
5143
Mike Stump11289f42009-09-09 15:08:12 +00005144void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005145 std::string& S) const {
5146 if (QT & Decl::OBJC_TQ_In)
5147 S += 'n';
5148 if (QT & Decl::OBJC_TQ_Inout)
5149 S += 'N';
5150 if (QT & Decl::OBJC_TQ_Out)
5151 S += 'o';
5152 if (QT & Decl::OBJC_TQ_Bycopy)
5153 S += 'O';
5154 if (QT & Decl::OBJC_TQ_Byref)
5155 S += 'R';
5156 if (QT & Decl::OBJC_TQ_Oneway)
5157 S += 'V';
5158}
5159
Douglas Gregor3ea72692011-08-12 05:46:01 +00005160TypedefDecl *ASTContext::getObjCIdDecl() const {
5161 if (!ObjCIdDecl) {
5162 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5163 T = getObjCObjectPointerType(T);
5164 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5165 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5166 getTranslationUnitDecl(),
5167 SourceLocation(), SourceLocation(),
5168 &Idents.get("id"), IdInfo);
5169 }
5170
5171 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005172}
5173
Douglas Gregor52e02802011-08-12 06:17:30 +00005174TypedefDecl *ASTContext::getObjCSelDecl() const {
5175 if (!ObjCSelDecl) {
5176 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5177 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5178 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5179 getTranslationUnitDecl(),
5180 SourceLocation(), SourceLocation(),
5181 &Idents.get("SEL"), SelInfo);
5182 }
5183 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005184}
5185
Douglas Gregor0a586182011-08-12 05:59:41 +00005186TypedefDecl *ASTContext::getObjCClassDecl() const {
5187 if (!ObjCClassDecl) {
5188 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5189 T = getObjCObjectPointerType(T);
5190 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5191 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5192 getTranslationUnitDecl(),
5193 SourceLocation(), SourceLocation(),
5194 &Idents.get("Class"), ClassInfo);
5195 }
5196
5197 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005198}
5199
Douglas Gregord53ae832012-01-17 18:09:05 +00005200ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5201 if (!ObjCProtocolClassDecl) {
5202 ObjCProtocolClassDecl
5203 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5204 SourceLocation(),
5205 &Idents.get("Protocol"),
5206 /*PrevDecl=*/0,
5207 SourceLocation(), true);
5208 }
5209
5210 return ObjCProtocolClassDecl;
5211}
5212
Meador Inge5d3fb222012-06-16 03:34:49 +00005213//===----------------------------------------------------------------------===//
5214// __builtin_va_list Construction Functions
5215//===----------------------------------------------------------------------===//
5216
5217static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5218 // typedef char* __builtin_va_list;
5219 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5220 TypeSourceInfo *TInfo
5221 = Context->getTrivialTypeSourceInfo(CharPtrType);
5222
5223 TypedefDecl *VaListTypeDecl
5224 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5225 Context->getTranslationUnitDecl(),
5226 SourceLocation(), SourceLocation(),
5227 &Context->Idents.get("__builtin_va_list"),
5228 TInfo);
5229 return VaListTypeDecl;
5230}
5231
5232static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5233 // typedef void* __builtin_va_list;
5234 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5235 TypeSourceInfo *TInfo
5236 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5237
5238 TypedefDecl *VaListTypeDecl
5239 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5240 Context->getTranslationUnitDecl(),
5241 SourceLocation(), SourceLocation(),
5242 &Context->Idents.get("__builtin_va_list"),
5243 TInfo);
5244 return VaListTypeDecl;
5245}
5246
5247static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5248 // typedef struct __va_list_tag {
5249 RecordDecl *VaListTagDecl;
5250
5251 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5252 Context->getTranslationUnitDecl(),
5253 &Context->Idents.get("__va_list_tag"));
5254 VaListTagDecl->startDefinition();
5255
5256 const size_t NumFields = 5;
5257 QualType FieldTypes[NumFields];
5258 const char *FieldNames[NumFields];
5259
5260 // unsigned char gpr;
5261 FieldTypes[0] = Context->UnsignedCharTy;
5262 FieldNames[0] = "gpr";
5263
5264 // unsigned char fpr;
5265 FieldTypes[1] = Context->UnsignedCharTy;
5266 FieldNames[1] = "fpr";
5267
5268 // unsigned short reserved;
5269 FieldTypes[2] = Context->UnsignedShortTy;
5270 FieldNames[2] = "reserved";
5271
5272 // void* overflow_arg_area;
5273 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5274 FieldNames[3] = "overflow_arg_area";
5275
5276 // void* reg_save_area;
5277 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5278 FieldNames[4] = "reg_save_area";
5279
5280 // Create fields
5281 for (unsigned i = 0; i < NumFields; ++i) {
5282 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5283 SourceLocation(),
5284 SourceLocation(),
5285 &Context->Idents.get(FieldNames[i]),
5286 FieldTypes[i], /*TInfo=*/0,
5287 /*BitWidth=*/0,
5288 /*Mutable=*/false,
5289 ICIS_NoInit);
5290 Field->setAccess(AS_public);
5291 VaListTagDecl->addDecl(Field);
5292 }
5293 VaListTagDecl->completeDefinition();
5294 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005295 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005296
5297 // } __va_list_tag;
5298 TypedefDecl *VaListTagTypedefDecl
5299 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5300 Context->getTranslationUnitDecl(),
5301 SourceLocation(), SourceLocation(),
5302 &Context->Idents.get("__va_list_tag"),
5303 Context->getTrivialTypeSourceInfo(VaListTagType));
5304 QualType VaListTagTypedefType =
5305 Context->getTypedefType(VaListTagTypedefDecl);
5306
5307 // typedef __va_list_tag __builtin_va_list[1];
5308 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5309 QualType VaListTagArrayType
5310 = Context->getConstantArrayType(VaListTagTypedefType,
5311 Size, ArrayType::Normal, 0);
5312 TypeSourceInfo *TInfo
5313 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5314 TypedefDecl *VaListTypedefDecl
5315 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5316 Context->getTranslationUnitDecl(),
5317 SourceLocation(), SourceLocation(),
5318 &Context->Idents.get("__builtin_va_list"),
5319 TInfo);
5320
5321 return VaListTypedefDecl;
5322}
5323
5324static TypedefDecl *
5325CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5326 // typedef struct __va_list_tag {
5327 RecordDecl *VaListTagDecl;
5328 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5329 Context->getTranslationUnitDecl(),
5330 &Context->Idents.get("__va_list_tag"));
5331 VaListTagDecl->startDefinition();
5332
5333 const size_t NumFields = 4;
5334 QualType FieldTypes[NumFields];
5335 const char *FieldNames[NumFields];
5336
5337 // unsigned gp_offset;
5338 FieldTypes[0] = Context->UnsignedIntTy;
5339 FieldNames[0] = "gp_offset";
5340
5341 // unsigned fp_offset;
5342 FieldTypes[1] = Context->UnsignedIntTy;
5343 FieldNames[1] = "fp_offset";
5344
5345 // void* overflow_arg_area;
5346 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5347 FieldNames[2] = "overflow_arg_area";
5348
5349 // void* reg_save_area;
5350 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5351 FieldNames[3] = "reg_save_area";
5352
5353 // Create fields
5354 for (unsigned i = 0; i < NumFields; ++i) {
5355 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5356 VaListTagDecl,
5357 SourceLocation(),
5358 SourceLocation(),
5359 &Context->Idents.get(FieldNames[i]),
5360 FieldTypes[i], /*TInfo=*/0,
5361 /*BitWidth=*/0,
5362 /*Mutable=*/false,
5363 ICIS_NoInit);
5364 Field->setAccess(AS_public);
5365 VaListTagDecl->addDecl(Field);
5366 }
5367 VaListTagDecl->completeDefinition();
5368 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005369 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005370
5371 // } __va_list_tag;
5372 TypedefDecl *VaListTagTypedefDecl
5373 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5374 Context->getTranslationUnitDecl(),
5375 SourceLocation(), SourceLocation(),
5376 &Context->Idents.get("__va_list_tag"),
5377 Context->getTrivialTypeSourceInfo(VaListTagType));
5378 QualType VaListTagTypedefType =
5379 Context->getTypedefType(VaListTagTypedefDecl);
5380
5381 // typedef __va_list_tag __builtin_va_list[1];
5382 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5383 QualType VaListTagArrayType
5384 = Context->getConstantArrayType(VaListTagTypedefType,
5385 Size, ArrayType::Normal,0);
5386 TypeSourceInfo *TInfo
5387 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5388 TypedefDecl *VaListTypedefDecl
5389 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5390 Context->getTranslationUnitDecl(),
5391 SourceLocation(), SourceLocation(),
5392 &Context->Idents.get("__builtin_va_list"),
5393 TInfo);
5394
5395 return VaListTypedefDecl;
5396}
5397
5398static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5399 // typedef int __builtin_va_list[4];
5400 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5401 QualType IntArrayType
5402 = Context->getConstantArrayType(Context->IntTy,
5403 Size, ArrayType::Normal, 0);
5404 TypedefDecl *VaListTypedefDecl
5405 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5406 Context->getTranslationUnitDecl(),
5407 SourceLocation(), SourceLocation(),
5408 &Context->Idents.get("__builtin_va_list"),
5409 Context->getTrivialTypeSourceInfo(IntArrayType));
5410
5411 return VaListTypedefDecl;
5412}
5413
5414static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5415 TargetInfo::BuiltinVaListKind Kind) {
5416 switch (Kind) {
5417 case TargetInfo::CharPtrBuiltinVaList:
5418 return CreateCharPtrBuiltinVaListDecl(Context);
5419 case TargetInfo::VoidPtrBuiltinVaList:
5420 return CreateVoidPtrBuiltinVaListDecl(Context);
5421 case TargetInfo::PowerABIBuiltinVaList:
5422 return CreatePowerABIBuiltinVaListDecl(Context);
5423 case TargetInfo::X86_64ABIBuiltinVaList:
5424 return CreateX86_64ABIBuiltinVaListDecl(Context);
5425 case TargetInfo::PNaClABIBuiltinVaList:
5426 return CreatePNaClABIBuiltinVaListDecl(Context);
5427 }
5428
5429 llvm_unreachable("Unhandled __builtin_va_list type kind");
5430}
5431
5432TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5433 if (!BuiltinVaListDecl)
5434 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5435
5436 return BuiltinVaListDecl;
5437}
5438
Meador Ingecfb60902012-07-01 15:57:25 +00005439QualType ASTContext::getVaListTagType() const {
5440 // Force the creation of VaListTagTy by building the __builtin_va_list
5441 // declaration.
5442 if (VaListTagTy.isNull())
5443 (void) getBuiltinVaListDecl();
5444
5445 return VaListTagTy;
5446}
5447
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005448void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00005449 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00005450 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00005451
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005452 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00005453}
5454
John McCalld28ae272009-12-02 08:04:21 +00005455/// \brief Retrieve the template name that corresponds to a non-empty
5456/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00005457TemplateName
5458ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5459 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00005460 unsigned size = End - Begin;
5461 assert(size > 1 && "set is not overloaded!");
5462
5463 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5464 size * sizeof(FunctionTemplateDecl*));
5465 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5466
5467 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00005468 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00005469 NamedDecl *D = *I;
5470 assert(isa<FunctionTemplateDecl>(D) ||
5471 (isa<UsingShadowDecl>(D) &&
5472 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5473 *Storage++ = D;
5474 }
5475
5476 return TemplateName(OT);
5477}
5478
Douglas Gregordc572a32009-03-30 22:58:21 +00005479/// \brief Retrieve the template name that represents a qualified
5480/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00005481TemplateName
5482ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5483 bool TemplateKeyword,
5484 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00005485 assert(NNS && "Missing nested-name-specifier in qualified template name");
5486
Douglas Gregorc42075a2010-02-04 18:10:26 +00005487 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00005488 llvm::FoldingSetNodeID ID;
5489 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5490
5491 void *InsertPos = 0;
5492 QualifiedTemplateName *QTN =
5493 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5494 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00005495 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
5496 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00005497 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5498 }
5499
5500 return TemplateName(QTN);
5501}
5502
5503/// \brief Retrieve the template name that represents a dependent
5504/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00005505TemplateName
5506ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5507 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00005508 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00005509 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00005510
5511 llvm::FoldingSetNodeID ID;
5512 DependentTemplateName::Profile(ID, NNS, Name);
5513
5514 void *InsertPos = 0;
5515 DependentTemplateName *QTN =
5516 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5517
5518 if (QTN)
5519 return TemplateName(QTN);
5520
5521 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5522 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00005523 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5524 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00005525 } else {
5526 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00005527 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5528 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005529 DependentTemplateName *CheckQTN =
5530 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5531 assert(!CheckQTN && "Dependent type name canonicalization broken");
5532 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00005533 }
5534
5535 DependentTemplateNames.InsertNode(QTN, InsertPos);
5536 return TemplateName(QTN);
5537}
5538
Douglas Gregor71395fa2009-11-04 00:56:37 +00005539/// \brief Retrieve the template name that represents a dependent
5540/// template name such as \c MetaFun::template operator+.
5541TemplateName
5542ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00005543 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00005544 assert((!NNS || NNS->isDependent()) &&
5545 "Nested name specifier must be dependent");
5546
5547 llvm::FoldingSetNodeID ID;
5548 DependentTemplateName::Profile(ID, NNS, Operator);
5549
5550 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00005551 DependentTemplateName *QTN
5552 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005553
5554 if (QTN)
5555 return TemplateName(QTN);
5556
5557 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5558 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00005559 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5560 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005561 } else {
5562 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00005563 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5564 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005565
5566 DependentTemplateName *CheckQTN
5567 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5568 assert(!CheckQTN && "Dependent template name canonicalization broken");
5569 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00005570 }
5571
5572 DependentTemplateNames.InsertNode(QTN, InsertPos);
5573 return TemplateName(QTN);
5574}
5575
Douglas Gregor5590be02011-01-15 06:45:20 +00005576TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00005577ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5578 TemplateName replacement) const {
5579 llvm::FoldingSetNodeID ID;
5580 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5581
5582 void *insertPos = 0;
5583 SubstTemplateTemplateParmStorage *subst
5584 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5585
5586 if (!subst) {
5587 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5588 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5589 }
5590
5591 return TemplateName(subst);
5592}
5593
5594TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00005595ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5596 const TemplateArgument &ArgPack) const {
5597 ASTContext &Self = const_cast<ASTContext &>(*this);
5598 llvm::FoldingSetNodeID ID;
5599 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5600
5601 void *InsertPos = 0;
5602 SubstTemplateTemplateParmPackStorage *Subst
5603 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5604
5605 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00005606 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00005607 ArgPack.pack_size(),
5608 ArgPack.pack_begin());
5609 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5610 }
5611
5612 return TemplateName(Subst);
5613}
5614
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005615/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00005616/// TargetInfo, produce the corresponding type. The unsigned @p Type
5617/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00005618CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005619 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00005620 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005621 case TargetInfo::SignedShort: return ShortTy;
5622 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5623 case TargetInfo::SignedInt: return IntTy;
5624 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5625 case TargetInfo::SignedLong: return LongTy;
5626 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5627 case TargetInfo::SignedLongLong: return LongLongTy;
5628 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5629 }
5630
David Blaikie83d382b2011-09-23 05:06:16 +00005631 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005632}
Ted Kremenek77c51b22008-07-24 23:58:27 +00005633
5634//===----------------------------------------------------------------------===//
5635// Type Predicates.
5636//===----------------------------------------------------------------------===//
5637
Fariborz Jahanian96207692009-02-18 21:49:28 +00005638/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5639/// garbage collection attribute.
5640///
John McCall553d45a2011-01-12 00:34:59 +00005641Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005642 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00005643 return Qualifiers::GCNone;
5644
David Blaikiebbafb8a2012-03-11 07:00:24 +00005645 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00005646 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5647
5648 // Default behaviour under objective-C's gc is for ObjC pointers
5649 // (or pointers to them) be treated as though they were declared
5650 // as __strong.
5651 if (GCAttrs == Qualifiers::GCNone) {
5652 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5653 return Qualifiers::Strong;
5654 else if (Ty->isPointerType())
5655 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5656 } else {
5657 // It's not valid to set GC attributes on anything that isn't a
5658 // pointer.
5659#ifndef NDEBUG
5660 QualType CT = Ty->getCanonicalTypeInternal();
5661 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5662 CT = AT->getElementType();
5663 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5664#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00005665 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00005666 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00005667}
5668
Chris Lattner49af6a42008-04-07 06:51:04 +00005669//===----------------------------------------------------------------------===//
5670// Type Compatibility Testing
5671//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00005672
Mike Stump11289f42009-09-09 15:08:12 +00005673/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005674/// compatible.
5675static bool areCompatVectorTypes(const VectorType *LHS,
5676 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00005677 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00005678 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00005679 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00005680}
5681
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005682bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5683 QualType SecondVec) {
5684 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5685 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5686
5687 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5688 return true;
5689
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005690 // Treat Neon vector types and most AltiVec vector types as if they are the
5691 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005692 const VectorType *First = FirstVec->getAs<VectorType>();
5693 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005694 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005695 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005696 First->getVectorKind() != VectorType::AltiVecPixel &&
5697 First->getVectorKind() != VectorType::AltiVecBool &&
5698 Second->getVectorKind() != VectorType::AltiVecPixel &&
5699 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005700 return true;
5701
5702 return false;
5703}
5704
Steve Naroff8e6aee52009-07-23 01:01:38 +00005705//===----------------------------------------------------------------------===//
5706// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5707//===----------------------------------------------------------------------===//
5708
5709/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5710/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00005711bool
5712ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5713 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00005714 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005715 return true;
5716 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5717 E = rProto->protocol_end(); PI != E; ++PI)
5718 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5719 return true;
5720 return false;
5721}
5722
Steve Naroff8e6aee52009-07-23 01:01:38 +00005723/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5724/// return true if lhs's protocols conform to rhs's protocol; false
5725/// otherwise.
5726bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5727 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5728 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5729 return false;
5730}
5731
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005732/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5733/// Class<p1, ...>.
5734bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5735 QualType rhs) {
5736 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5737 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5738 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5739
5740 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5741 E = lhsQID->qual_end(); I != E; ++I) {
5742 bool match = false;
5743 ObjCProtocolDecl *lhsProto = *I;
5744 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5745 E = rhsOPT->qual_end(); J != E; ++J) {
5746 ObjCProtocolDecl *rhsProto = *J;
5747 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5748 match = true;
5749 break;
5750 }
5751 }
5752 if (!match)
5753 return false;
5754 }
5755 return true;
5756}
5757
Steve Naroff8e6aee52009-07-23 01:01:38 +00005758/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5759/// ObjCQualifiedIDType.
5760bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5761 bool compare) {
5762 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00005763 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005764 lhs->isObjCIdType() || lhs->isObjCClassType())
5765 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005766 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005767 rhs->isObjCIdType() || rhs->isObjCClassType())
5768 return true;
5769
5770 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00005771 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005772
Steve Naroff8e6aee52009-07-23 01:01:38 +00005773 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00005774
Steve Naroff8e6aee52009-07-23 01:01:38 +00005775 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005776 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005777 // make sure we check the class hierarchy.
5778 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5779 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5780 E = lhsQID->qual_end(); I != E; ++I) {
5781 // when comparing an id<P> on lhs with a static type on rhs,
5782 // see if static class implements all of id's protocols, directly or
5783 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005784 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005785 return false;
5786 }
5787 }
5788 // If there are no qualifiers and no interface, we have an 'id'.
5789 return true;
5790 }
Mike Stump11289f42009-09-09 15:08:12 +00005791 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005792 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5793 E = lhsQID->qual_end(); I != E; ++I) {
5794 ObjCProtocolDecl *lhsProto = *I;
5795 bool match = false;
5796
5797 // when comparing an id<P> on lhs with a static type on rhs,
5798 // see if static class implements all of id's protocols, directly or
5799 // through its super class and categories.
5800 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5801 E = rhsOPT->qual_end(); J != E; ++J) {
5802 ObjCProtocolDecl *rhsProto = *J;
5803 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5804 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5805 match = true;
5806 break;
5807 }
5808 }
Mike Stump11289f42009-09-09 15:08:12 +00005809 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005810 // make sure we check the class hierarchy.
5811 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5812 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5813 E = lhsQID->qual_end(); I != E; ++I) {
5814 // when comparing an id<P> on lhs with a static type on rhs,
5815 // see if static class implements all of id's protocols, directly or
5816 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005817 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005818 match = true;
5819 break;
5820 }
5821 }
5822 }
5823 if (!match)
5824 return false;
5825 }
Mike Stump11289f42009-09-09 15:08:12 +00005826
Steve Naroff8e6aee52009-07-23 01:01:38 +00005827 return true;
5828 }
Mike Stump11289f42009-09-09 15:08:12 +00005829
Steve Naroff8e6aee52009-07-23 01:01:38 +00005830 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5831 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5832
Mike Stump11289f42009-09-09 15:08:12 +00005833 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00005834 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005835 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005836 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5837 E = lhsOPT->qual_end(); I != E; ++I) {
5838 ObjCProtocolDecl *lhsProto = *I;
5839 bool match = false;
5840
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005841 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00005842 // see if static class implements all of id's protocols, directly or
5843 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005844 // First, lhs protocols in the qualifier list must be found, direct
5845 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005846 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5847 E = rhsQID->qual_end(); J != E; ++J) {
5848 ObjCProtocolDecl *rhsProto = *J;
5849 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5850 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5851 match = true;
5852 break;
5853 }
5854 }
5855 if (!match)
5856 return false;
5857 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005858
5859 // Static class's protocols, or its super class or category protocols
5860 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5861 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5862 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5863 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5864 // This is rather dubious but matches gcc's behavior. If lhs has
5865 // no type qualifier and its class has no static protocol(s)
5866 // assume that it is mismatch.
5867 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5868 return false;
5869 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5870 LHSInheritedProtocols.begin(),
5871 E = LHSInheritedProtocols.end(); I != E; ++I) {
5872 bool match = false;
5873 ObjCProtocolDecl *lhsProto = (*I);
5874 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5875 E = rhsQID->qual_end(); J != E; ++J) {
5876 ObjCProtocolDecl *rhsProto = *J;
5877 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5878 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5879 match = true;
5880 break;
5881 }
5882 }
5883 if (!match)
5884 return false;
5885 }
5886 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00005887 return true;
5888 }
5889 return false;
5890}
5891
Eli Friedman47f77112008-08-22 00:56:42 +00005892/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005893/// compatible for assignment from RHS to LHS. This handles validation of any
5894/// protocol qualifiers on the LHS or RHS.
5895///
Steve Naroff7cae42b2009-07-10 23:34:53 +00005896bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5897 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00005898 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5899 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5900
Steve Naroff1329fa02009-07-15 18:40:39 +00005901 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00005902 if (LHS->isObjCUnqualifiedIdOrClass() ||
5903 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00005904 return true;
5905
John McCall8b07ec22010-05-15 11:32:37 +00005906 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00005907 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5908 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00005909 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005910
5911 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5912 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5913 QualType(RHSOPT,0));
5914
John McCall8b07ec22010-05-15 11:32:37 +00005915 // If we have 2 user-defined types, fall into that path.
5916 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00005917 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005918
Steve Naroff8e6aee52009-07-23 01:01:38 +00005919 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005920}
5921
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005922/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00005923/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005924/// arguments in block literals. When passed as arguments, passing 'A*' where
5925/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5926/// not OK. For the return type, the opposite is not OK.
5927bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5928 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005929 const ObjCObjectPointerType *RHSOPT,
5930 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005931 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005932 return true;
5933
5934 if (LHSOPT->isObjCBuiltinType()) {
5935 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5936 }
5937
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005938 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005939 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5940 QualType(RHSOPT,0),
5941 false);
5942
5943 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5944 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5945 if (LHS && RHS) { // We have 2 user-defined types.
5946 if (LHS != RHS) {
5947 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005948 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005949 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005950 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005951 }
5952 else
5953 return true;
5954 }
5955 return false;
5956}
5957
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005958/// getIntersectionOfProtocols - This routine finds the intersection of set
5959/// of protocols inherited from two distinct objective-c pointer objects.
5960/// It is used to build composite qualifier list of the composite type of
5961/// the conditional expression involving two objective-c pointer objects.
5962static
5963void getIntersectionOfProtocols(ASTContext &Context,
5964 const ObjCObjectPointerType *LHSOPT,
5965 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005966 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005967
John McCall8b07ec22010-05-15 11:32:37 +00005968 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5969 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5970 assert(LHS->getInterface() && "LHS must have an interface base");
5971 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005972
5973 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5974 unsigned LHSNumProtocols = LHS->getNumProtocols();
5975 if (LHSNumProtocols > 0)
5976 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5977 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005978 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005979 Context.CollectInheritedProtocols(LHS->getInterface(),
5980 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005981 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5982 LHSInheritedProtocols.end());
5983 }
5984
5985 unsigned RHSNumProtocols = RHS->getNumProtocols();
5986 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00005987 ObjCProtocolDecl **RHSProtocols =
5988 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005989 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5990 if (InheritedProtocolSet.count(RHSProtocols[i]))
5991 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00005992 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005993 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005994 Context.CollectInheritedProtocols(RHS->getInterface(),
5995 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005996 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5997 RHSInheritedProtocols.begin(),
5998 E = RHSInheritedProtocols.end(); I != E; ++I)
5999 if (InheritedProtocolSet.count((*I)))
6000 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006001 }
6002}
6003
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006004/// areCommonBaseCompatible - Returns common base class of the two classes if
6005/// one found. Note that this is O'2 algorithm. But it will be called as the
6006/// last type comparison in a ?-exp of ObjC pointer types before a
6007/// warning is issued. So, its invokation is extremely rare.
6008QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006009 const ObjCObjectPointerType *Lptr,
6010 const ObjCObjectPointerType *Rptr) {
6011 const ObjCObjectType *LHS = Lptr->getObjectType();
6012 const ObjCObjectType *RHS = Rptr->getObjectType();
6013 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6014 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006015 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006016 return QualType();
6017
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006018 do {
John McCall8b07ec22010-05-15 11:32:37 +00006019 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006020 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006021 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006022 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6023
6024 QualType Result = QualType(LHS, 0);
6025 if (!Protocols.empty())
6026 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6027 Result = getObjCObjectPointerType(Result);
6028 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006029 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006030 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006031
6032 return QualType();
6033}
6034
John McCall8b07ec22010-05-15 11:32:37 +00006035bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6036 const ObjCObjectType *RHS) {
6037 assert(LHS->getInterface() && "LHS is not an interface type");
6038 assert(RHS->getInterface() && "RHS is not an interface type");
6039
Chris Lattner49af6a42008-04-07 06:51:04 +00006040 // Verify that the base decls are compatible: the RHS must be a subclass of
6041 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006042 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006043 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006044
Chris Lattner49af6a42008-04-07 06:51:04 +00006045 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6046 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006047 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006048 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006049
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006050 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6051 // more detailed analysis is required.
6052 if (RHS->getNumProtocols() == 0) {
6053 // OK, if LHS is a superclass of RHS *and*
6054 // this superclass is assignment compatible with LHS.
6055 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006056 bool IsSuperClass =
6057 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6058 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006059 // OK if conversion of LHS to SuperClass results in narrowing of types
6060 // ; i.e., SuperClass may implement at least one of the protocols
6061 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6062 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6063 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006064 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006065 // If super class has no protocols, it is not a match.
6066 if (SuperClassInheritedProtocols.empty())
6067 return false;
6068
6069 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6070 LHSPE = LHS->qual_end();
6071 LHSPI != LHSPE; LHSPI++) {
6072 bool SuperImplementsProtocol = false;
6073 ObjCProtocolDecl *LHSProto = (*LHSPI);
6074
6075 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6076 SuperClassInheritedProtocols.begin(),
6077 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6078 ObjCProtocolDecl *SuperClassProto = (*I);
6079 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6080 SuperImplementsProtocol = true;
6081 break;
6082 }
6083 }
6084 if (!SuperImplementsProtocol)
6085 return false;
6086 }
6087 return true;
6088 }
6089 return false;
6090 }
Mike Stump11289f42009-09-09 15:08:12 +00006091
John McCall8b07ec22010-05-15 11:32:37 +00006092 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6093 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00006094 LHSPI != LHSPE; LHSPI++) {
6095 bool RHSImplementsProtocol = false;
6096
6097 // If the RHS doesn't implement the protocol on the left, the types
6098 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00006099 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6100 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00006101 RHSPI != RHSPE; RHSPI++) {
6102 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006103 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00006104 break;
6105 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006106 }
6107 // FIXME: For better diagnostics, consider passing back the protocol name.
6108 if (!RHSImplementsProtocol)
6109 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006110 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006111 // The RHS implements all protocols listed on the LHS.
6112 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006113}
6114
Steve Naroffb7605152009-02-12 17:52:19 +00006115bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6116 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006117 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6118 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006119
Steve Naroff7cae42b2009-07-10 23:34:53 +00006120 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006121 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006122
6123 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6124 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006125}
6126
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006127bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6128 return canAssignObjCInterfaces(
6129 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6130 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6131}
6132
Mike Stump11289f42009-09-09 15:08:12 +00006133/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006134/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006135/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006136/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006137bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6138 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006139 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006140 return hasSameType(LHS, RHS);
6141
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006142 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006143}
6144
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006145bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006146 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006147}
6148
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006149bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6150 return !mergeTypes(LHS, RHS, true).isNull();
6151}
6152
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006153/// mergeTransparentUnionType - if T is a transparent union type and a member
6154/// of T is compatible with SubType, return the merged type, else return
6155/// QualType()
6156QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6157 bool OfBlockPointer,
6158 bool Unqualified) {
6159 if (const RecordType *UT = T->getAsUnionType()) {
6160 RecordDecl *UD = UT->getDecl();
6161 if (UD->hasAttr<TransparentUnionAttr>()) {
6162 for (RecordDecl::field_iterator it = UD->field_begin(),
6163 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00006164 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006165 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6166 if (!MT.isNull())
6167 return MT;
6168 }
6169 }
6170 }
6171
6172 return QualType();
6173}
6174
6175/// mergeFunctionArgumentTypes - merge two types which appear as function
6176/// argument types
6177QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6178 bool OfBlockPointer,
6179 bool Unqualified) {
6180 // GNU extension: two types are compatible if they appear as a function
6181 // argument, one of the types is a transparent union type and the other
6182 // type is compatible with a union member
6183 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6184 Unqualified);
6185 if (!lmerge.isNull())
6186 return lmerge;
6187
6188 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6189 Unqualified);
6190 if (!rmerge.isNull())
6191 return rmerge;
6192
6193 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6194}
6195
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006196QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006197 bool OfBlockPointer,
6198 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006199 const FunctionType *lbase = lhs->getAs<FunctionType>();
6200 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006201 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6202 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006203 bool allLTypes = true;
6204 bool allRTypes = true;
6205
6206 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006207 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006208 if (OfBlockPointer) {
6209 QualType RHS = rbase->getResultType();
6210 QualType LHS = lbase->getResultType();
6211 bool UnqualifiedResult = Unqualified;
6212 if (!UnqualifiedResult)
6213 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006214 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006215 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006216 else
John McCall8c6b56f2010-12-15 01:06:38 +00006217 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6218 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006219 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006220
6221 if (Unqualified)
6222 retType = retType.getUnqualifiedType();
6223
6224 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6225 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6226 if (Unqualified) {
6227 LRetType = LRetType.getUnqualifiedType();
6228 RRetType = RRetType.getUnqualifiedType();
6229 }
6230
6231 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006232 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006233 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006234 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006235
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006236 // FIXME: double check this
6237 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6238 // rbase->getRegParmAttr() != 0 &&
6239 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006240 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6241 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006242
Douglas Gregor8c940862010-01-18 17:14:39 +00006243 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00006244 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00006245 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006246
John McCall8c6b56f2010-12-15 01:06:38 +00006247 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006248 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6249 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006250 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6251 return QualType();
6252
John McCall31168b02011-06-15 23:02:42 +00006253 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6254 return QualType();
6255
Fariborz Jahanian48c69102011-10-05 00:05:34 +00006256 // functypes which return are preferred over those that do not.
6257 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
6258 allLTypes = false;
6259 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
6260 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006261 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6262 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006263
John McCall31168b02011-06-15 23:02:42 +00006264 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006265
Eli Friedman47f77112008-08-22 00:56:42 +00006266 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006267 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6268 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006269 unsigned lproto_nargs = lproto->getNumArgs();
6270 unsigned rproto_nargs = rproto->getNumArgs();
6271
6272 // Compatible functions must have the same number of arguments
6273 if (lproto_nargs != rproto_nargs)
6274 return QualType();
6275
6276 // Variadic and non-variadic functions aren't compatible
6277 if (lproto->isVariadic() != rproto->isVariadic())
6278 return QualType();
6279
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006280 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6281 return QualType();
6282
Fariborz Jahanian97676972011-09-28 21:52:05 +00006283 if (LangOpts.ObjCAutoRefCount &&
6284 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6285 return QualType();
6286
Eli Friedman47f77112008-08-22 00:56:42 +00006287 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006288 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00006289 for (unsigned i = 0; i < lproto_nargs; i++) {
6290 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6291 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006292 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6293 OfBlockPointer,
6294 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006295 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006296
6297 if (Unqualified)
6298 argtype = argtype.getUnqualifiedType();
6299
Eli Friedman47f77112008-08-22 00:56:42 +00006300 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006301 if (Unqualified) {
6302 largtype = largtype.getUnqualifiedType();
6303 rargtype = rargtype.getUnqualifiedType();
6304 }
6305
Chris Lattner465fa322008-10-05 17:34:18 +00006306 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6307 allLTypes = false;
6308 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6309 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006310 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006311
Eli Friedman47f77112008-08-22 00:56:42 +00006312 if (allLTypes) return lhs;
6313 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006314
6315 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6316 EPI.ExtInfo = einfo;
6317 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006318 }
6319
6320 if (lproto) allRTypes = false;
6321 if (rproto) allLTypes = false;
6322
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006323 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006324 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006325 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006326 if (proto->isVariadic()) return QualType();
6327 // Check that the types are compatible with the types that
6328 // would result from default argument promotions (C99 6.7.5.3p15).
6329 // The only types actually affected are promotable integer
6330 // types and floats, which would be passed as a different
6331 // type depending on whether the prototype is visible.
6332 unsigned proto_nargs = proto->getNumArgs();
6333 for (unsigned i = 0; i < proto_nargs; ++i) {
6334 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00006335
6336 // Look at the promotion type of enum types, since that is the type used
6337 // to pass enum values.
6338 if (const EnumType *Enum = argTy->getAs<EnumType>())
6339 argTy = Enum->getDecl()->getPromotionType();
6340
Eli Friedman47f77112008-08-22 00:56:42 +00006341 if (argTy->isPromotableIntegerType() ||
6342 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6343 return QualType();
6344 }
6345
6346 if (allLTypes) return lhs;
6347 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006348
6349 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6350 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00006351 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006352 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006353 }
6354
6355 if (allLTypes) return lhs;
6356 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00006357 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00006358}
6359
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006360QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006361 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006362 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00006363 // C++ [expr]: If an expression initially has the type "reference to T", the
6364 // type is adjusted to "T" prior to any further analysis, the expression
6365 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006366 // expression is an lvalue unless the reference is an rvalue reference and
6367 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00006368 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6369 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006370
6371 if (Unqualified) {
6372 LHS = LHS.getUnqualifiedType();
6373 RHS = RHS.getUnqualifiedType();
6374 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00006375
Eli Friedman47f77112008-08-22 00:56:42 +00006376 QualType LHSCan = getCanonicalType(LHS),
6377 RHSCan = getCanonicalType(RHS);
6378
6379 // If two types are identical, they are compatible.
6380 if (LHSCan == RHSCan)
6381 return LHS;
6382
John McCall8ccfcb52009-09-24 19:53:00 +00006383 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006384 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6385 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00006386 if (LQuals != RQuals) {
6387 // If any of these qualifiers are different, we have a type
6388 // mismatch.
6389 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00006390 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6391 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00006392 return QualType();
6393
6394 // Exactly one GC qualifier difference is allowed: __strong is
6395 // okay if the other type has no GC qualifier but is an Objective
6396 // C object pointer (i.e. implicitly strong by default). We fix
6397 // this by pretending that the unqualified type was actually
6398 // qualified __strong.
6399 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6400 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6401 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6402
6403 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6404 return QualType();
6405
6406 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6407 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6408 }
6409 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6410 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6411 }
Eli Friedman47f77112008-08-22 00:56:42 +00006412 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00006413 }
6414
6415 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00006416
Eli Friedmandcca6332009-06-01 01:22:52 +00006417 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6418 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00006419
Chris Lattnerfd652912008-01-14 05:45:46 +00006420 // We want to consider the two function types to be the same for these
6421 // comparisons, just force one to the other.
6422 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6423 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00006424
6425 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00006426 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6427 LHSClass = Type::ConstantArray;
6428 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6429 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00006430
John McCall8b07ec22010-05-15 11:32:37 +00006431 // ObjCInterfaces are just specialized ObjCObjects.
6432 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6433 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6434
Nate Begemance4d7fc2008-04-18 23:10:10 +00006435 // Canonicalize ExtVector -> Vector.
6436 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6437 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00006438
Chris Lattner95554662008-04-07 05:43:21 +00006439 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006440 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00006441 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00006442 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00006443 // Compatibility is based on the underlying type, not the promotion
6444 // type.
John McCall9dd450b2009-09-21 23:43:11 +00006445 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006446 QualType TINT = ETy->getDecl()->getIntegerType();
6447 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006448 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006449 }
John McCall9dd450b2009-09-21 23:43:11 +00006450 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006451 QualType TINT = ETy->getDecl()->getIntegerType();
6452 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006453 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006454 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006455 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00006456 if (OfBlockPointer && !BlockReturnType) {
6457 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6458 return LHS;
6459 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6460 return RHS;
6461 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006462
Eli Friedman47f77112008-08-22 00:56:42 +00006463 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00006464 }
Eli Friedman47f77112008-08-22 00:56:42 +00006465
Steve Naroffc6edcbd2008-01-09 22:43:08 +00006466 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006467 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006468#define TYPE(Class, Base)
6469#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00006470#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006471#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6472#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6473#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00006474 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006475
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006476 case Type::LValueReference:
6477 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006478 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00006479 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006480
John McCall8b07ec22010-05-15 11:32:37 +00006481 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006482 case Type::IncompleteArray:
6483 case Type::VariableArray:
6484 case Type::FunctionProto:
6485 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00006486 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006487
Chris Lattnerfd652912008-01-14 05:45:46 +00006488 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00006489 {
6490 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006491 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6492 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006493 if (Unqualified) {
6494 LHSPointee = LHSPointee.getUnqualifiedType();
6495 RHSPointee = RHSPointee.getUnqualifiedType();
6496 }
6497 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6498 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006499 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00006500 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006501 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00006502 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006503 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006504 return getPointerType(ResultType);
6505 }
Steve Naroff68e167d2008-12-10 17:49:55 +00006506 case Type::BlockPointer:
6507 {
6508 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006509 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6510 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006511 if (Unqualified) {
6512 LHSPointee = LHSPointee.getUnqualifiedType();
6513 RHSPointee = RHSPointee.getUnqualifiedType();
6514 }
6515 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6516 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00006517 if (ResultType.isNull()) return QualType();
6518 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6519 return LHS;
6520 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6521 return RHS;
6522 return getBlockPointerType(ResultType);
6523 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00006524 case Type::Atomic:
6525 {
6526 // Merge two pointer types, while trying to preserve typedef info
6527 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6528 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6529 if (Unqualified) {
6530 LHSValue = LHSValue.getUnqualifiedType();
6531 RHSValue = RHSValue.getUnqualifiedType();
6532 }
6533 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6534 Unqualified);
6535 if (ResultType.isNull()) return QualType();
6536 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6537 return LHS;
6538 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6539 return RHS;
6540 return getAtomicType(ResultType);
6541 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006542 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00006543 {
6544 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6545 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6546 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6547 return QualType();
6548
6549 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6550 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006551 if (Unqualified) {
6552 LHSElem = LHSElem.getUnqualifiedType();
6553 RHSElem = RHSElem.getUnqualifiedType();
6554 }
6555
6556 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006557 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00006558 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6559 return LHS;
6560 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6561 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00006562 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6563 ArrayType::ArraySizeModifier(), 0);
6564 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6565 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006566 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6567 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00006568 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6569 return LHS;
6570 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6571 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006572 if (LVAT) {
6573 // FIXME: This isn't correct! But tricky to implement because
6574 // the array's size has to be the size of LHS, but the type
6575 // has to be different.
6576 return LHS;
6577 }
6578 if (RVAT) {
6579 // FIXME: This isn't correct! But tricky to implement because
6580 // the array's size has to be the size of RHS, but the type
6581 // has to be different.
6582 return RHS;
6583 }
Eli Friedman3e62c212008-08-22 01:48:21 +00006584 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6585 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00006586 return getIncompleteArrayType(ResultType,
6587 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006588 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006589 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006590 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006591 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006592 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00006593 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00006594 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006595 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00006596 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00006597 case Type::Complex:
6598 // Distinct complex types are incompatible.
6599 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006600 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00006601 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00006602 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6603 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00006604 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00006605 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00006606 case Type::ObjCObject: {
6607 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00006608 // FIXME: This should be type compatibility, e.g. whether
6609 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00006610 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6611 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6612 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00006613 return LHS;
6614
Eli Friedman47f77112008-08-22 00:56:42 +00006615 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00006616 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006617 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006618 if (OfBlockPointer) {
6619 if (canAssignObjCInterfacesInBlockPointer(
6620 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006621 RHS->getAs<ObjCObjectPointerType>(),
6622 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00006623 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006624 return QualType();
6625 }
John McCall9dd450b2009-09-21 23:43:11 +00006626 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6627 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006628 return LHS;
6629
Steve Naroffc68cfcf2008-12-10 22:14:21 +00006630 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00006631 }
Steve Naroff32e44c02007-10-15 20:41:53 +00006632 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006633
David Blaikie8a40f702012-01-17 06:56:22 +00006634 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00006635}
Ted Kremenekfc581a92007-10-31 17:10:13 +00006636
Fariborz Jahanian97676972011-09-28 21:52:05 +00006637bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6638 const FunctionProtoType *FromFunctionType,
6639 const FunctionProtoType *ToFunctionType) {
6640 if (FromFunctionType->hasAnyConsumedArgs() !=
6641 ToFunctionType->hasAnyConsumedArgs())
6642 return false;
6643 FunctionProtoType::ExtProtoInfo FromEPI =
6644 FromFunctionType->getExtProtoInfo();
6645 FunctionProtoType::ExtProtoInfo ToEPI =
6646 ToFunctionType->getExtProtoInfo();
6647 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6648 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6649 ArgIdx != NumArgs; ++ArgIdx) {
6650 if (FromEPI.ConsumedArguments[ArgIdx] !=
6651 ToEPI.ConsumedArguments[ArgIdx])
6652 return false;
6653 }
6654 return true;
6655}
6656
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006657/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6658/// 'RHS' attributes and returns the merged version; including for function
6659/// return types.
6660QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6661 QualType LHSCan = getCanonicalType(LHS),
6662 RHSCan = getCanonicalType(RHS);
6663 // If two types are identical, they are compatible.
6664 if (LHSCan == RHSCan)
6665 return LHS;
6666 if (RHSCan->isFunctionType()) {
6667 if (!LHSCan->isFunctionType())
6668 return QualType();
6669 QualType OldReturnType =
6670 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6671 QualType NewReturnType =
6672 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6673 QualType ResReturnType =
6674 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6675 if (ResReturnType.isNull())
6676 return QualType();
6677 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6678 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6679 // In either case, use OldReturnType to build the new function type.
6680 const FunctionType *F = LHS->getAs<FunctionType>();
6681 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00006682 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6683 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006684 QualType ResultType
6685 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006686 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006687 return ResultType;
6688 }
6689 }
6690 return QualType();
6691 }
6692
6693 // If the qualifiers are different, the types can still be merged.
6694 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6695 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6696 if (LQuals != RQuals) {
6697 // If any of these qualifiers are different, we have a type mismatch.
6698 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6699 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6700 return QualType();
6701
6702 // Exactly one GC qualifier difference is allowed: __strong is
6703 // okay if the other type has no GC qualifier but is an Objective
6704 // C object pointer (i.e. implicitly strong by default). We fix
6705 // this by pretending that the unqualified type was actually
6706 // qualified __strong.
6707 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6708 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6709 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6710
6711 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6712 return QualType();
6713
6714 if (GC_L == Qualifiers::Strong)
6715 return LHS;
6716 if (GC_R == Qualifiers::Strong)
6717 return RHS;
6718 return QualType();
6719 }
6720
6721 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6722 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6723 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6724 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6725 if (ResQT == LHSBaseQT)
6726 return LHS;
6727 if (ResQT == RHSBaseQT)
6728 return RHS;
6729 }
6730 return QualType();
6731}
6732
Chris Lattner4ba0cef2008-04-07 07:01:58 +00006733//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006734// Integer Predicates
6735//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00006736
Jay Foad39c79802011-01-12 09:06:06 +00006737unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00006738 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00006739 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00006740 if (T->isBooleanType())
6741 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00006742 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006743 return (unsigned)getTypeSize(T);
6744}
6745
6746QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006747 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00006748
6749 // Turn <4 x signed int> -> <4 x unsigned int>
6750 if (const VectorType *VTy = T->getAs<VectorType>())
6751 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00006752 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00006753
6754 // For enums, we return the unsigned version of the base type.
6755 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006756 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00006757
6758 const BuiltinType *BTy = T->getAs<BuiltinType>();
6759 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006760 switch (BTy->getKind()) {
6761 case BuiltinType::Char_S:
6762 case BuiltinType::SChar:
6763 return UnsignedCharTy;
6764 case BuiltinType::Short:
6765 return UnsignedShortTy;
6766 case BuiltinType::Int:
6767 return UnsignedIntTy;
6768 case BuiltinType::Long:
6769 return UnsignedLongTy;
6770 case BuiltinType::LongLong:
6771 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00006772 case BuiltinType::Int128:
6773 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006774 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006775 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006776 }
6777}
6778
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00006779ASTMutationListener::~ASTMutationListener() { }
6780
Chris Lattnerecd79c62009-06-14 00:45:47 +00006781
6782//===----------------------------------------------------------------------===//
6783// Builtin Type Computation
6784//===----------------------------------------------------------------------===//
6785
6786/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00006787/// pointer over the consumed characters. This returns the resultant type. If
6788/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6789/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6790/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006791///
6792/// RequiresICE is filled in on return to indicate whether the value is required
6793/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00006794static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00006795 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006796 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00006797 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00006798 // Modifiers.
6799 int HowLong = 0;
6800 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006801 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00006802
Chris Lattnerdc226c22010-10-01 22:42:38 +00006803 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00006804 bool Done = false;
6805 while (!Done) {
6806 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00006807 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00006808 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006809 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00006810 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006811 case 'S':
6812 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6813 assert(!Signed && "Can't use 'S' modifier multiple times!");
6814 Signed = true;
6815 break;
6816 case 'U':
6817 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6818 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6819 Unsigned = true;
6820 break;
6821 case 'L':
6822 assert(HowLong <= 2 && "Can't have LLLL modifier");
6823 ++HowLong;
6824 break;
6825 }
6826 }
6827
6828 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00006829
Chris Lattnerecd79c62009-06-14 00:45:47 +00006830 // Read the base type.
6831 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00006832 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006833 case 'v':
6834 assert(HowLong == 0 && !Signed && !Unsigned &&
6835 "Bad modifiers used with 'v'!");
6836 Type = Context.VoidTy;
6837 break;
6838 case 'f':
6839 assert(HowLong == 0 && !Signed && !Unsigned &&
6840 "Bad modifiers used with 'f'!");
6841 Type = Context.FloatTy;
6842 break;
6843 case 'd':
6844 assert(HowLong < 2 && !Signed && !Unsigned &&
6845 "Bad modifiers used with 'd'!");
6846 if (HowLong)
6847 Type = Context.LongDoubleTy;
6848 else
6849 Type = Context.DoubleTy;
6850 break;
6851 case 's':
6852 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6853 if (Unsigned)
6854 Type = Context.UnsignedShortTy;
6855 else
6856 Type = Context.ShortTy;
6857 break;
6858 case 'i':
6859 if (HowLong == 3)
6860 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6861 else if (HowLong == 2)
6862 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6863 else if (HowLong == 1)
6864 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6865 else
6866 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6867 break;
6868 case 'c':
6869 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6870 if (Signed)
6871 Type = Context.SignedCharTy;
6872 else if (Unsigned)
6873 Type = Context.UnsignedCharTy;
6874 else
6875 Type = Context.CharTy;
6876 break;
6877 case 'b': // boolean
6878 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6879 Type = Context.BoolTy;
6880 break;
6881 case 'z': // size_t.
6882 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6883 Type = Context.getSizeType();
6884 break;
6885 case 'F':
6886 Type = Context.getCFConstantStringType();
6887 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00006888 case 'G':
6889 Type = Context.getObjCIdType();
6890 break;
6891 case 'H':
6892 Type = Context.getObjCSelType();
6893 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006894 case 'a':
6895 Type = Context.getBuiltinVaListType();
6896 assert(!Type.isNull() && "builtin va list type not initialized!");
6897 break;
6898 case 'A':
6899 // This is a "reference" to a va_list; however, what exactly
6900 // this means depends on how va_list is defined. There are two
6901 // different kinds of va_list: ones passed by value, and ones
6902 // passed by reference. An example of a by-value va_list is
6903 // x86, where va_list is a char*. An example of by-ref va_list
6904 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6905 // we want this argument to be a char*&; for x86-64, we want
6906 // it to be a __va_list_tag*.
6907 Type = Context.getBuiltinVaListType();
6908 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006909 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00006910 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006911 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00006912 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006913 break;
6914 case 'V': {
6915 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006916 unsigned NumElements = strtoul(Str, &End, 10);
6917 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006918 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00006919
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006920 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6921 RequiresICE, false);
6922 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00006923
6924 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00006925 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00006926 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006927 break;
6928 }
Douglas Gregorfed66992012-06-07 18:08:25 +00006929 case 'E': {
6930 char *End;
6931
6932 unsigned NumElements = strtoul(Str, &End, 10);
6933 assert(End != Str && "Missing vector size");
6934
6935 Str = End;
6936
6937 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6938 false);
6939 Type = Context.getExtVectorType(ElementType, NumElements);
6940 break;
6941 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006942 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006943 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6944 false);
6945 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006946 Type = Context.getComplexType(ElementType);
6947 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00006948 }
6949 case 'Y' : {
6950 Type = Context.getPointerDiffType();
6951 break;
6952 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00006953 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00006954 Type = Context.getFILEType();
6955 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006956 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006957 return QualType();
6958 }
Mike Stump2adb4da2009-07-28 23:47:15 +00006959 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00006960 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00006961 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00006962 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00006963 else
6964 Type = Context.getjmp_bufType();
6965
Mike Stump2adb4da2009-07-28 23:47:15 +00006966 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006967 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00006968 return QualType();
6969 }
6970 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00006971 case 'K':
6972 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
6973 Type = Context.getucontext_tType();
6974
6975 if (Type.isNull()) {
6976 Error = ASTContext::GE_Missing_ucontext;
6977 return QualType();
6978 }
6979 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00006980 }
Mike Stump11289f42009-09-09 15:08:12 +00006981
Chris Lattnerdc226c22010-10-01 22:42:38 +00006982 // If there are modifiers and if we're allowed to parse them, go for it.
6983 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006984 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00006985 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006986 default: Done = true; --Str; break;
6987 case '*':
6988 case '&': {
6989 // Both pointers and references can have their pointee types
6990 // qualified with an address space.
6991 char *End;
6992 unsigned AddrSpace = strtoul(Str, &End, 10);
6993 if (End != Str && AddrSpace != 0) {
6994 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6995 Str = End;
6996 }
6997 if (c == '*')
6998 Type = Context.getPointerType(Type);
6999 else
7000 Type = Context.getLValueReferenceType(Type);
7001 break;
7002 }
7003 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7004 case 'C':
7005 Type = Type.withConst();
7006 break;
7007 case 'D':
7008 Type = Context.getVolatileType(Type);
7009 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007010 case 'R':
7011 Type = Type.withRestrict();
7012 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007013 }
7014 }
Chris Lattner84733392010-10-01 07:13:18 +00007015
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007016 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007017 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007018
Chris Lattnerecd79c62009-06-14 00:45:47 +00007019 return Type;
7020}
7021
7022/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007023QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007024 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007025 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007026 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007027
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007028 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007029
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007030 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007031 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007032 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7033 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007034 if (Error != GE_None)
7035 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007036
7037 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7038
Chris Lattnerecd79c62009-06-14 00:45:47 +00007039 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007040 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007041 if (Error != GE_None)
7042 return QualType();
7043
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007044 // If this argument is required to be an IntegerConstantExpression and the
7045 // caller cares, fill in the bitmask we return.
7046 if (RequiresICE && IntegerConstantArgs)
7047 *IntegerConstantArgs |= 1 << ArgTypes.size();
7048
Chris Lattnerecd79c62009-06-14 00:45:47 +00007049 // Do array -> pointer decay. The builtin should use the decayed type.
7050 if (Ty->isArrayType())
7051 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007052
Chris Lattnerecd79c62009-06-14 00:45:47 +00007053 ArgTypes.push_back(Ty);
7054 }
7055
7056 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7057 "'.' should only occur at end of builtin type list!");
7058
John McCall991eb4b2010-12-21 00:44:39 +00007059 FunctionType::ExtInfo EI;
7060 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7061
7062 bool Variadic = (TypeStr[0] == '.');
7063
7064 // We really shouldn't be making a no-proto type here, especially in C++.
7065 if (ArgTypes.empty() && Variadic)
7066 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007067
John McCalldb40c7f2010-12-14 08:05:40 +00007068 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007069 EPI.ExtInfo = EI;
7070 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007071
7072 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007073}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007074
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007075GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
7076 GVALinkage External = GVA_StrongExternal;
7077
7078 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007079 switch (L) {
7080 case NoLinkage:
7081 case InternalLinkage:
7082 case UniqueExternalLinkage:
7083 return GVA_Internal;
7084
7085 case ExternalLinkage:
7086 switch (FD->getTemplateSpecializationKind()) {
7087 case TSK_Undeclared:
7088 case TSK_ExplicitSpecialization:
7089 External = GVA_StrongExternal;
7090 break;
7091
7092 case TSK_ExplicitInstantiationDefinition:
7093 return GVA_ExplicitTemplateInstantiation;
7094
7095 case TSK_ExplicitInstantiationDeclaration:
7096 case TSK_ImplicitInstantiation:
7097 External = GVA_TemplateInstantiation;
7098 break;
7099 }
7100 }
7101
7102 if (!FD->isInlined())
7103 return External;
7104
David Blaikiebbafb8a2012-03-11 07:00:24 +00007105 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007106 // GNU or C99 inline semantics. Determine whether this symbol should be
7107 // externally visible.
7108 if (FD->isInlineDefinitionExternallyVisible())
7109 return External;
7110
7111 // C99 inline semantics, where the symbol is not externally visible.
7112 return GVA_C99Inline;
7113 }
7114
7115 // C++0x [temp.explicit]p9:
7116 // [ Note: The intent is that an inline function that is the subject of
7117 // an explicit instantiation declaration will still be implicitly
7118 // instantiated when used so that the body can be considered for
7119 // inlining, but that no out-of-line copy of the inline function would be
7120 // generated in the translation unit. -- end note ]
7121 if (FD->getTemplateSpecializationKind()
7122 == TSK_ExplicitInstantiationDeclaration)
7123 return GVA_C99Inline;
7124
7125 return GVA_CXXInline;
7126}
7127
7128GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7129 // If this is a static data member, compute the kind of template
7130 // specialization. Otherwise, this variable is not part of a
7131 // template.
7132 TemplateSpecializationKind TSK = TSK_Undeclared;
7133 if (VD->isStaticDataMember())
7134 TSK = VD->getTemplateSpecializationKind();
7135
7136 Linkage L = VD->getLinkage();
David Blaikiebbafb8a2012-03-11 07:00:24 +00007137 if (L == ExternalLinkage && getLangOpts().CPlusPlus &&
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007138 VD->getType()->getLinkage() == UniqueExternalLinkage)
7139 L = UniqueExternalLinkage;
7140
7141 switch (L) {
7142 case NoLinkage:
7143 case InternalLinkage:
7144 case UniqueExternalLinkage:
7145 return GVA_Internal;
7146
7147 case ExternalLinkage:
7148 switch (TSK) {
7149 case TSK_Undeclared:
7150 case TSK_ExplicitSpecialization:
7151 return GVA_StrongExternal;
7152
7153 case TSK_ExplicitInstantiationDeclaration:
7154 llvm_unreachable("Variable should not be instantiated");
7155 // Fall through to treat this like any other instantiation.
7156
7157 case TSK_ExplicitInstantiationDefinition:
7158 return GVA_ExplicitTemplateInstantiation;
7159
7160 case TSK_ImplicitInstantiation:
7161 return GVA_TemplateInstantiation;
7162 }
7163 }
7164
David Blaikie8a40f702012-01-17 06:56:22 +00007165 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007166}
7167
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007168bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007169 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7170 if (!VD->isFileVarDecl())
7171 return false;
Argyrios Kyrtzidisa98e8612011-09-13 21:35:00 +00007172 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007173 return false;
7174
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007175 // Weak references don't produce any output by themselves.
7176 if (D->hasAttr<WeakRefAttr>())
7177 return false;
7178
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007179 // Aliases and used decls are required.
7180 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7181 return true;
7182
7183 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7184 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007185 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007186 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007187
7188 // Constructors and destructors are required.
7189 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7190 return true;
7191
7192 // The key function for a class is required.
7193 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7194 const CXXRecordDecl *RD = MD->getParent();
7195 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7196 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
7197 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7198 return true;
7199 }
7200 }
7201
7202 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7203
7204 // static, static inline, always_inline, and extern inline functions can
7205 // always be deferred. Normal inline functions can be deferred in C99/C++.
7206 // Implicit template instantiations can also be deferred in C++.
7207 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007208 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007209 return false;
7210 return true;
7211 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007212
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007213 const VarDecl *VD = cast<VarDecl>(D);
7214 assert(VD->isFileVarDecl() && "Expected file scoped var");
7215
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007216 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7217 return false;
7218
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007219 // Structs that have non-trivial constructors or destructors are required.
7220
7221 // FIXME: Handle references.
Alexis Huntf479f1b2011-05-09 18:22:59 +00007222 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007223 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
7224 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Alexis Huntf479f1b2011-05-09 18:22:59 +00007225 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
7226 RD->hasTrivialCopyConstructor() &&
7227 RD->hasTrivialMoveConstructor() &&
7228 RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007229 return true;
7230 }
7231 }
7232
7233 GVALinkage L = GetGVALinkageForVariable(VD);
7234 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
7235 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
7236 return false;
7237 }
7238
7239 return true;
7240}
Charles Davis53c59df2010-08-16 03:33:14 +00007241
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007242CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davis99202b32010-11-09 18:04:24 +00007243 // Pass through to the C++ ABI object
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007244 return ABI->getDefaultMethodCallConv(isVariadic);
7245}
7246
7247CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
7248 if (CC == CC_C && !LangOpts.MRTD && getTargetInfo().getCXXABI() != CXXABI_Microsoft)
7249 return CC_Default;
7250 return CC;
Charles Davis99202b32010-11-09 18:04:24 +00007251}
7252
Jay Foad39c79802011-01-12 09:06:06 +00007253bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007254 // Pass through to the C++ ABI object
7255 return ABI->isNearlyEmpty(RD);
7256}
7257
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007258MangleContext *ASTContext::createMangleContext() {
Douglas Gregore8bbc122011-09-02 00:18:52 +00007259 switch (Target->getCXXABI()) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007260 case CXXABI_ARM:
7261 case CXXABI_Itanium:
7262 return createItaniumMangleContext(*this, getDiagnostics());
7263 case CXXABI_Microsoft:
7264 return createMicrosoftMangleContext(*this, getDiagnostics());
7265 }
David Blaikie83d382b2011-09-23 05:06:16 +00007266 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007267}
7268
Charles Davis53c59df2010-08-16 03:33:14 +00007269CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007270
7271size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00007272 return ASTRecordLayouts.getMemorySize()
7273 + llvm::capacity_in_bytes(ObjCLayouts)
7274 + llvm::capacity_in_bytes(KeyFunctions)
7275 + llvm::capacity_in_bytes(ObjCImpls)
7276 + llvm::capacity_in_bytes(BlockVarCopyInits)
7277 + llvm::capacity_in_bytes(DeclAttrs)
7278 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7279 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7280 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7281 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7282 + llvm::capacity_in_bytes(OverriddenMethods)
7283 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007284 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00007285 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007286}
Ted Kremenek540017e2011-10-06 05:00:56 +00007287
Douglas Gregor63798542012-02-20 19:44:39 +00007288unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7289 CXXRecordDecl *Lambda = CallOperator->getParent();
7290 return LambdaMangleContexts[Lambda->getDeclContext()]
7291 .getManglingNumber(CallOperator);
7292}
7293
7294
Ted Kremenek540017e2011-10-06 05:00:56 +00007295void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7296 ParamIndices[D] = index;
7297}
7298
7299unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7300 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7301 assert(I != ParamIndices.end() &&
7302 "ParmIndices lacks entry set by ParmVarDecl");
7303 return I->second;
7304}