1 //===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the ASTContext interface.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/AST/ASTContext.h"
15 #include "CXXABI.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/Comment.h"
20 #include "clang/AST/CommentCommandTraits.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExternalASTSource.h"
27 #include "clang/AST/Mangle.h"
28 #include "clang/AST/MangleNumberingContext.h"
29 #include "clang/AST/RecordLayout.h"
30 #include "clang/AST/RecursiveASTVisitor.h"
31 #include "clang/AST/TypeLoc.h"
32 #include "clang/Basic/Builtins.h"
33 #include "clang/Basic/SourceManager.h"
34 #include "clang/Basic/TargetInfo.h"
35 #include "llvm/ADT/SmallString.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/ADT/Triple.h"
38 #include "llvm/Support/Capacity.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include <map>
42
43 using namespace clang;
44
45 unsigned ASTContext::NumImplicitDefaultConstructors;
46 unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
47 unsigned ASTContext::NumImplicitCopyConstructors;
48 unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
49 unsigned ASTContext::NumImplicitMoveConstructors;
50 unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
51 unsigned ASTContext::NumImplicitCopyAssignmentOperators;
52 unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
53 unsigned ASTContext::NumImplicitMoveAssignmentOperators;
54 unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
55 unsigned ASTContext::NumImplicitDestructors;
56 unsigned ASTContext::NumImplicitDestructorsDeclared;
57
58 enum FloatingRank {
59 HalfRank, FloatRank, DoubleRank, LongDoubleRank
60 };
61
getRawCommentForDeclNoCache(const Decl * D) const62 RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
63 if (!CommentsLoaded && ExternalSource) {
64 ExternalSource->ReadComments();
65 CommentsLoaded = true;
66 }
67
68 assert(D);
69
70 // User can not attach documentation to implicit declarations.
71 if (D->isImplicit())
72 return NULL;
73
74 // User can not attach documentation to implicit instantiations.
75 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
76 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
77 return NULL;
78 }
79
80 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
81 if (VD->isStaticDataMember() &&
82 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
83 return NULL;
84 }
85
86 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
87 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
88 return NULL;
89 }
90
91 if (const ClassTemplateSpecializationDecl *CTSD =
92 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
93 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
94 if (TSK == TSK_ImplicitInstantiation ||
95 TSK == TSK_Undeclared)
96 return NULL;
97 }
98
99 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
100 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
101 return NULL;
102 }
103 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
104 // When tag declaration (but not definition!) is part of the
105 // decl-specifier-seq of some other declaration, it doesn't get comment
106 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
107 return NULL;
108 }
109 // TODO: handle comments for function parameters properly.
110 if (isa<ParmVarDecl>(D))
111 return NULL;
112
113 // TODO: we could look up template parameter documentation in the template
114 // documentation.
115 if (isa<TemplateTypeParmDecl>(D) ||
116 isa<NonTypeTemplateParmDecl>(D) ||
117 isa<TemplateTemplateParmDecl>(D))
118 return NULL;
119
120 ArrayRef<RawComment *> RawComments = Comments.getComments();
121
122 // If there are no comments anywhere, we won't find anything.
123 if (RawComments.empty())
124 return NULL;
125
126 // Find declaration location.
127 // For Objective-C declarations we generally don't expect to have multiple
128 // declarators, thus use declaration starting location as the "declaration
129 // location".
130 // For all other declarations multiple declarators are used quite frequently,
131 // so we use the location of the identifier as the "declaration location".
132 SourceLocation DeclLoc;
133 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
134 isa<ObjCPropertyDecl>(D) ||
135 isa<RedeclarableTemplateDecl>(D) ||
136 isa<ClassTemplateSpecializationDecl>(D))
137 DeclLoc = D->getLocStart();
138 else {
139 DeclLoc = D->getLocation();
140 // If location of the typedef name is in a macro, it is because being
141 // declared via a macro. Try using declaration's starting location
142 // as the "declaration location".
143 if (DeclLoc.isMacroID() && isa<TypedefDecl>(D))
144 DeclLoc = D->getLocStart();
145 }
146
147 // If the declaration doesn't map directly to a location in a file, we
148 // can't find the comment.
149 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
150 return NULL;
151
152 // Find the comment that occurs just after this declaration.
153 ArrayRef<RawComment *>::iterator Comment;
154 {
155 // When searching for comments during parsing, the comment we are looking
156 // for is usually among the last two comments we parsed -- check them
157 // first.
158 RawComment CommentAtDeclLoc(
159 SourceMgr, SourceRange(DeclLoc), false,
160 LangOpts.CommentOpts.ParseAllComments);
161 BeforeThanCompare<RawComment> Compare(SourceMgr);
162 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
163 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
164 if (!Found && RawComments.size() >= 2) {
165 MaybeBeforeDecl--;
166 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
167 }
168
169 if (Found) {
170 Comment = MaybeBeforeDecl + 1;
171 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
172 &CommentAtDeclLoc, Compare));
173 } else {
174 // Slow path.
175 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
176 &CommentAtDeclLoc, Compare);
177 }
178 }
179
180 // Decompose the location for the declaration and find the beginning of the
181 // file buffer.
182 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
183
184 // First check whether we have a trailing comment.
185 if (Comment != RawComments.end() &&
186 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
187 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
188 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
189 std::pair<FileID, unsigned> CommentBeginDecomp
190 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
191 // Check that Doxygen trailing comment comes after the declaration, starts
192 // on the same line and in the same file as the declaration.
193 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
194 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
195 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
196 CommentBeginDecomp.second)) {
197 return *Comment;
198 }
199 }
200
201 // The comment just after the declaration was not a trailing comment.
202 // Let's look at the previous comment.
203 if (Comment == RawComments.begin())
204 return NULL;
205 --Comment;
206
207 // Check that we actually have a non-member Doxygen comment.
208 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
209 return NULL;
210
211 // Decompose the end of the comment.
212 std::pair<FileID, unsigned> CommentEndDecomp
213 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
214
215 // If the comment and the declaration aren't in the same file, then they
216 // aren't related.
217 if (DeclLocDecomp.first != CommentEndDecomp.first)
218 return NULL;
219
220 // Get the corresponding buffer.
221 bool Invalid = false;
222 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
223 &Invalid).data();
224 if (Invalid)
225 return NULL;
226
227 // Extract text between the comment and declaration.
228 StringRef Text(Buffer + CommentEndDecomp.second,
229 DeclLocDecomp.second - CommentEndDecomp.second);
230
231 // There should be no other declarations or preprocessor directives between
232 // comment and declaration.
233 if (Text.find_first_of(";{}#@") != StringRef::npos)
234 return NULL;
235
236 return *Comment;
237 }
238
239 namespace {
240 /// If we have a 'templated' declaration for a template, adjust 'D' to
241 /// refer to the actual template.
242 /// If we have an implicit instantiation, adjust 'D' to refer to template.
adjustDeclToTemplate(const Decl * D)243 const Decl *adjustDeclToTemplate(const Decl *D) {
244 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
245 // Is this function declaration part of a function template?
246 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
247 return FTD;
248
249 // Nothing to do if function is not an implicit instantiation.
250 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
251 return D;
252
253 // Function is an implicit instantiation of a function template?
254 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
255 return FTD;
256
257 // Function is instantiated from a member definition of a class template?
258 if (const FunctionDecl *MemberDecl =
259 FD->getInstantiatedFromMemberFunction())
260 return MemberDecl;
261
262 return D;
263 }
264 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
265 // Static data member is instantiated from a member definition of a class
266 // template?
267 if (VD->isStaticDataMember())
268 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
269 return MemberDecl;
270
271 return D;
272 }
273 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
274 // Is this class declaration part of a class template?
275 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
276 return CTD;
277
278 // Class is an implicit instantiation of a class template or partial
279 // specialization?
280 if (const ClassTemplateSpecializationDecl *CTSD =
281 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
282 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
283 return D;
284 llvm::PointerUnion<ClassTemplateDecl *,
285 ClassTemplatePartialSpecializationDecl *>
286 PU = CTSD->getSpecializedTemplateOrPartial();
287 return PU.is<ClassTemplateDecl*>() ?
288 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
289 static_cast<const Decl*>(
290 PU.get<ClassTemplatePartialSpecializationDecl *>());
291 }
292
293 // Class is instantiated from a member definition of a class template?
294 if (const MemberSpecializationInfo *Info =
295 CRD->getMemberSpecializationInfo())
296 return Info->getInstantiatedFrom();
297
298 return D;
299 }
300 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
301 // Enum is instantiated from a member definition of a class template?
302 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
303 return MemberDecl;
304
305 return D;
306 }
307 // FIXME: Adjust alias templates?
308 return D;
309 }
310 } // unnamed namespace
311
getRawCommentForAnyRedecl(const Decl * D,const Decl ** OriginalDecl) const312 const RawComment *ASTContext::getRawCommentForAnyRedecl(
313 const Decl *D,
314 const Decl **OriginalDecl) const {
315 D = adjustDeclToTemplate(D);
316
317 // Check whether we have cached a comment for this declaration already.
318 {
319 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
320 RedeclComments.find(D);
321 if (Pos != RedeclComments.end()) {
322 const RawCommentAndCacheFlags &Raw = Pos->second;
323 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
324 if (OriginalDecl)
325 *OriginalDecl = Raw.getOriginalDecl();
326 return Raw.getRaw();
327 }
328 }
329 }
330
331 // Search for comments attached to declarations in the redeclaration chain.
332 const RawComment *RC = NULL;
333 const Decl *OriginalDeclForRC = NULL;
334 for (Decl::redecl_iterator I = D->redecls_begin(),
335 E = D->redecls_end();
336 I != E; ++I) {
337 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
338 RedeclComments.find(*I);
339 if (Pos != RedeclComments.end()) {
340 const RawCommentAndCacheFlags &Raw = Pos->second;
341 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
342 RC = Raw.getRaw();
343 OriginalDeclForRC = Raw.getOriginalDecl();
344 break;
345 }
346 } else {
347 RC = getRawCommentForDeclNoCache(*I);
348 OriginalDeclForRC = *I;
349 RawCommentAndCacheFlags Raw;
350 if (RC) {
351 Raw.setRaw(RC);
352 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
353 } else
354 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
355 Raw.setOriginalDecl(*I);
356 RedeclComments[*I] = Raw;
357 if (RC)
358 break;
359 }
360 }
361
362 // If we found a comment, it should be a documentation comment.
363 assert(!RC || RC->isDocumentation());
364
365 if (OriginalDecl)
366 *OriginalDecl = OriginalDeclForRC;
367
368 // Update cache for every declaration in the redeclaration chain.
369 RawCommentAndCacheFlags Raw;
370 Raw.setRaw(RC);
371 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
372 Raw.setOriginalDecl(OriginalDeclForRC);
373
374 for (Decl::redecl_iterator I = D->redecls_begin(),
375 E = D->redecls_end();
376 I != E; ++I) {
377 RawCommentAndCacheFlags &R = RedeclComments[*I];
378 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
379 R = Raw;
380 }
381
382 return RC;
383 }
384
addRedeclaredMethods(const ObjCMethodDecl * ObjCMethod,SmallVectorImpl<const NamedDecl * > & Redeclared)385 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
386 SmallVectorImpl<const NamedDecl *> &Redeclared) {
387 const DeclContext *DC = ObjCMethod->getDeclContext();
388 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
389 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
390 if (!ID)
391 return;
392 // Add redeclared method here.
393 for (ObjCInterfaceDecl::known_extensions_iterator
394 Ext = ID->known_extensions_begin(),
395 ExtEnd = ID->known_extensions_end();
396 Ext != ExtEnd; ++Ext) {
397 if (ObjCMethodDecl *RedeclaredMethod =
398 Ext->getMethod(ObjCMethod->getSelector(),
399 ObjCMethod->isInstanceMethod()))
400 Redeclared.push_back(RedeclaredMethod);
401 }
402 }
403 }
404
cloneFullComment(comments::FullComment * FC,const Decl * D) const405 comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
406 const Decl *D) const {
407 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
408 ThisDeclInfo->CommentDecl = D;
409 ThisDeclInfo->IsFilled = false;
410 ThisDeclInfo->fill();
411 ThisDeclInfo->CommentDecl = FC->getDecl();
412 comments::FullComment *CFC =
413 new (*this) comments::FullComment(FC->getBlocks(),
414 ThisDeclInfo);
415 return CFC;
416
417 }
418
getLocalCommentForDeclUncached(const Decl * D) const419 comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
420 const RawComment *RC = getRawCommentForDeclNoCache(D);
421 return RC ? RC->parse(*this, 0, D) : 0;
422 }
423
getCommentForDecl(const Decl * D,const Preprocessor * PP) const424 comments::FullComment *ASTContext::getCommentForDecl(
425 const Decl *D,
426 const Preprocessor *PP) const {
427 if (D->isInvalidDecl())
428 return NULL;
429 D = adjustDeclToTemplate(D);
430
431 const Decl *Canonical = D->getCanonicalDecl();
432 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
433 ParsedComments.find(Canonical);
434
435 if (Pos != ParsedComments.end()) {
436 if (Canonical != D) {
437 comments::FullComment *FC = Pos->second;
438 comments::FullComment *CFC = cloneFullComment(FC, D);
439 return CFC;
440 }
441 return Pos->second;
442 }
443
444 const Decl *OriginalDecl;
445
446 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
447 if (!RC) {
448 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
449 SmallVector<const NamedDecl*, 8> Overridden;
450 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
451 if (OMD && OMD->isPropertyAccessor())
452 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
453 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
454 return cloneFullComment(FC, D);
455 if (OMD)
456 addRedeclaredMethods(OMD, Overridden);
457 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
458 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
459 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
460 return cloneFullComment(FC, D);
461 }
462 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
463 // Attach any tag type's documentation to its typedef if latter
464 // does not have one of its own.
465 QualType QT = TD->getUnderlyingType();
466 if (const TagType *TT = QT->getAs<TagType>())
467 if (const Decl *TD = TT->getDecl())
468 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
469 return cloneFullComment(FC, D);
470 }
471 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
472 while (IC->getSuperClass()) {
473 IC = IC->getSuperClass();
474 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
475 return cloneFullComment(FC, D);
476 }
477 }
478 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
479 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
480 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
481 return cloneFullComment(FC, D);
482 }
483 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
484 if (!(RD = RD->getDefinition()))
485 return NULL;
486 // Check non-virtual bases.
487 for (CXXRecordDecl::base_class_const_iterator I =
488 RD->bases_begin(), E = RD->bases_end(); I != E; ++I) {
489 if (I->isVirtual() || (I->getAccessSpecifier() != AS_public))
490 continue;
491 QualType Ty = I->getType();
492 if (Ty.isNull())
493 continue;
494 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
495 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
496 continue;
497
498 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
499 return cloneFullComment(FC, D);
500 }
501 }
502 // Check virtual bases.
503 for (CXXRecordDecl::base_class_const_iterator I =
504 RD->vbases_begin(), E = RD->vbases_end(); I != E; ++I) {
505 if (I->getAccessSpecifier() != AS_public)
506 continue;
507 QualType Ty = I->getType();
508 if (Ty.isNull())
509 continue;
510 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
511 if (!(VirtualBase= VirtualBase->getDefinition()))
512 continue;
513 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
514 return cloneFullComment(FC, D);
515 }
516 }
517 }
518 return NULL;
519 }
520
521 // If the RawComment was attached to other redeclaration of this Decl, we
522 // should parse the comment in context of that other Decl. This is important
523 // because comments can contain references to parameter names which can be
524 // different across redeclarations.
525 if (D != OriginalDecl)
526 return getCommentForDecl(OriginalDecl, PP);
527
528 comments::FullComment *FC = RC->parse(*this, PP, D);
529 ParsedComments[Canonical] = FC;
530 return FC;
531 }
532
533 void
Profile(llvm::FoldingSetNodeID & ID,TemplateTemplateParmDecl * Parm)534 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
535 TemplateTemplateParmDecl *Parm) {
536 ID.AddInteger(Parm->getDepth());
537 ID.AddInteger(Parm->getPosition());
538 ID.AddBoolean(Parm->isParameterPack());
539
540 TemplateParameterList *Params = Parm->getTemplateParameters();
541 ID.AddInteger(Params->size());
542 for (TemplateParameterList::const_iterator P = Params->begin(),
543 PEnd = Params->end();
544 P != PEnd; ++P) {
545 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
546 ID.AddInteger(0);
547 ID.AddBoolean(TTP->isParameterPack());
548 continue;
549 }
550
551 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
552 ID.AddInteger(1);
553 ID.AddBoolean(NTTP->isParameterPack());
554 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
555 if (NTTP->isExpandedParameterPack()) {
556 ID.AddBoolean(true);
557 ID.AddInteger(NTTP->getNumExpansionTypes());
558 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
559 QualType T = NTTP->getExpansionType(I);
560 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
561 }
562 } else
563 ID.AddBoolean(false);
564 continue;
565 }
566
567 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
568 ID.AddInteger(2);
569 Profile(ID, TTP);
570 }
571 }
572
573 TemplateTemplateParmDecl *
getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl * TTP) const574 ASTContext::getCanonicalTemplateTemplateParmDecl(
575 TemplateTemplateParmDecl *TTP) const {
576 // Check if we already have a canonical template template parameter.
577 llvm::FoldingSetNodeID ID;
578 CanonicalTemplateTemplateParm::Profile(ID, TTP);
579 void *InsertPos = 0;
580 CanonicalTemplateTemplateParm *Canonical
581 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
582 if (Canonical)
583 return Canonical->getParam();
584
585 // Build a canonical template parameter list.
586 TemplateParameterList *Params = TTP->getTemplateParameters();
587 SmallVector<NamedDecl *, 4> CanonParams;
588 CanonParams.reserve(Params->size());
589 for (TemplateParameterList::const_iterator P = Params->begin(),
590 PEnd = Params->end();
591 P != PEnd; ++P) {
592 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
593 CanonParams.push_back(
594 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
595 SourceLocation(),
596 SourceLocation(),
597 TTP->getDepth(),
598 TTP->getIndex(), 0, false,
599 TTP->isParameterPack()));
600 else if (NonTypeTemplateParmDecl *NTTP
601 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
602 QualType T = getCanonicalType(NTTP->getType());
603 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
604 NonTypeTemplateParmDecl *Param;
605 if (NTTP->isExpandedParameterPack()) {
606 SmallVector<QualType, 2> ExpandedTypes;
607 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
608 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
609 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
610 ExpandedTInfos.push_back(
611 getTrivialTypeSourceInfo(ExpandedTypes.back()));
612 }
613
614 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
615 SourceLocation(),
616 SourceLocation(),
617 NTTP->getDepth(),
618 NTTP->getPosition(), 0,
619 T,
620 TInfo,
621 ExpandedTypes.data(),
622 ExpandedTypes.size(),
623 ExpandedTInfos.data());
624 } else {
625 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
626 SourceLocation(),
627 SourceLocation(),
628 NTTP->getDepth(),
629 NTTP->getPosition(), 0,
630 T,
631 NTTP->isParameterPack(),
632 TInfo);
633 }
634 CanonParams.push_back(Param);
635
636 } else
637 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
638 cast<TemplateTemplateParmDecl>(*P)));
639 }
640
641 TemplateTemplateParmDecl *CanonTTP
642 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
643 SourceLocation(), TTP->getDepth(),
644 TTP->getPosition(),
645 TTP->isParameterPack(),
646 0,
647 TemplateParameterList::Create(*this, SourceLocation(),
648 SourceLocation(),
649 CanonParams.data(),
650 CanonParams.size(),
651 SourceLocation()));
652
653 // Get the new insert position for the node we care about.
654 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
655 assert(Canonical == 0 && "Shouldn't be in the map!");
656 (void)Canonical;
657
658 // Create the canonical template template parameter entry.
659 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
660 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
661 return CanonTTP;
662 }
663
createCXXABI(const TargetInfo & T)664 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
665 if (!LangOpts.CPlusPlus) return 0;
666
667 switch (T.getCXXABI().getKind()) {
668 case TargetCXXABI::GenericARM:
669 case TargetCXXABI::iOS:
670 return CreateARMCXXABI(*this);
671 case TargetCXXABI::GenericAArch64: // Same as Itanium at this level
672 case TargetCXXABI::GenericItanium:
673 return CreateItaniumCXXABI(*this);
674 case TargetCXXABI::Microsoft:
675 return CreateMicrosoftCXXABI(*this);
676 }
677 llvm_unreachable("Invalid CXXABI type!");
678 }
679
getAddressSpaceMap(const TargetInfo & T,const LangOptions & LOpts)680 static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
681 const LangOptions &LOpts) {
682 if (LOpts.FakeAddressSpaceMap) {
683 // The fake address space map must have a distinct entry for each
684 // language-specific address space.
685 static const unsigned FakeAddrSpaceMap[] = {
686 1, // opencl_global
687 2, // opencl_local
688 3, // opencl_constant
689 4, // cuda_device
690 5, // cuda_constant
691 6 // cuda_shared
692 };
693 return &FakeAddrSpaceMap;
694 } else {
695 return &T.getAddressSpaceMap();
696 }
697 }
698
isAddrSpaceMapManglingEnabled(const TargetInfo & TI,const LangOptions & LangOpts)699 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
700 const LangOptions &LangOpts) {
701 switch (LangOpts.getAddressSpaceMapMangling()) {
702 case LangOptions::ASMM_Target:
703 return TI.useAddressSpaceMapMangling();
704 case LangOptions::ASMM_On:
705 return true;
706 case LangOptions::ASMM_Off:
707 return false;
708 }
709 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
710 }
711
ASTContext(LangOptions & LOpts,SourceManager & SM,const TargetInfo * t,IdentifierTable & idents,SelectorTable & sels,Builtin::Context & builtins,unsigned size_reserve,bool DelayInitialization)712 ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
713 const TargetInfo *t,
714 IdentifierTable &idents, SelectorTable &sels,
715 Builtin::Context &builtins,
716 unsigned size_reserve,
717 bool DelayInitialization)
718 : FunctionProtoTypes(this_()),
719 TemplateSpecializationTypes(this_()),
720 DependentTemplateSpecializationTypes(this_()),
721 SubstTemplateTemplateParmPacks(this_()),
722 GlobalNestedNameSpecifier(0),
723 Int128Decl(0), UInt128Decl(0), Float128StubDecl(0),
724 BuiltinVaListDecl(0),
725 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
726 BOOLDecl(0),
727 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
728 FILEDecl(0),
729 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
730 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
731 cudaConfigureCallDecl(0),
732 NullTypeSourceInfo(QualType()),
733 FirstLocalImport(), LastLocalImport(),
734 SourceMgr(SM), LangOpts(LOpts),
735 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
736 Idents(idents), Selectors(sels),
737 BuiltinInfo(builtins),
738 DeclarationNames(*this),
739 ExternalSource(0), Listener(0),
740 Comments(SM), CommentsLoaded(false),
741 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
742 LastSDM(0, 0)
743 {
744 if (size_reserve > 0) Types.reserve(size_reserve);
745 TUDecl = TranslationUnitDecl::Create(*this);
746
747 if (!DelayInitialization) {
748 assert(t && "No target supplied for ASTContext initialization");
749 InitBuiltinTypes(*t);
750 }
751 }
752
~ASTContext()753 ASTContext::~ASTContext() {
754 // Release the DenseMaps associated with DeclContext objects.
755 // FIXME: Is this the ideal solution?
756 ReleaseDeclContextMaps();
757
758 // Call all of the deallocation functions on all of their targets.
759 for (DeallocationMap::const_iterator I = Deallocations.begin(),
760 E = Deallocations.end(); I != E; ++I)
761 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
762 (I->first)((I->second)[J]);
763
764 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
765 // because they can contain DenseMaps.
766 for (llvm::DenseMap<const ObjCContainerDecl*,
767 const ASTRecordLayout*>::iterator
768 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
769 // Increment in loop to prevent using deallocated memory.
770 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
771 R->Destroy(*this);
772
773 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
774 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
775 // Increment in loop to prevent using deallocated memory.
776 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
777 R->Destroy(*this);
778 }
779
780 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
781 AEnd = DeclAttrs.end();
782 A != AEnd; ++A)
783 A->second->~AttrVec();
784
785 for (llvm::DenseMap<const DeclContext *, MangleNumberingContext *>::iterator
786 I = MangleNumberingContexts.begin(),
787 E = MangleNumberingContexts.end();
788 I != E; ++I)
789 delete I->second;
790 }
791
AddDeallocation(void (* Callback)(void *),void * Data)792 void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
793 Deallocations[Callback].push_back(Data);
794 }
795
796 void
setExternalSource(OwningPtr<ExternalASTSource> & Source)797 ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
798 ExternalSource.reset(Source.take());
799 }
800
PrintStats() const801 void ASTContext::PrintStats() const {
802 llvm::errs() << "\n*** AST Context Stats:\n";
803 llvm::errs() << " " << Types.size() << " types total.\n";
804
805 unsigned counts[] = {
806 #define TYPE(Name, Parent) 0,
807 #define ABSTRACT_TYPE(Name, Parent)
808 #include "clang/AST/TypeNodes.def"
809 0 // Extra
810 };
811
812 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
813 Type *T = Types[i];
814 counts[(unsigned)T->getTypeClass()]++;
815 }
816
817 unsigned Idx = 0;
818 unsigned TotalBytes = 0;
819 #define TYPE(Name, Parent) \
820 if (counts[Idx]) \
821 llvm::errs() << " " << counts[Idx] << " " << #Name \
822 << " types\n"; \
823 TotalBytes += counts[Idx] * sizeof(Name##Type); \
824 ++Idx;
825 #define ABSTRACT_TYPE(Name, Parent)
826 #include "clang/AST/TypeNodes.def"
827
828 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
829
830 // Implicit special member functions.
831 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
832 << NumImplicitDefaultConstructors
833 << " implicit default constructors created\n";
834 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
835 << NumImplicitCopyConstructors
836 << " implicit copy constructors created\n";
837 if (getLangOpts().CPlusPlus)
838 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
839 << NumImplicitMoveConstructors
840 << " implicit move constructors created\n";
841 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
842 << NumImplicitCopyAssignmentOperators
843 << " implicit copy assignment operators created\n";
844 if (getLangOpts().CPlusPlus)
845 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
846 << NumImplicitMoveAssignmentOperators
847 << " implicit move assignment operators created\n";
848 llvm::errs() << NumImplicitDestructorsDeclared << "/"
849 << NumImplicitDestructors
850 << " implicit destructors created\n";
851
852 if (ExternalSource.get()) {
853 llvm::errs() << "\n";
854 ExternalSource->PrintStats();
855 }
856
857 BumpAlloc.PrintStats();
858 }
859
getInt128Decl() const860 TypedefDecl *ASTContext::getInt128Decl() const {
861 if (!Int128Decl) {
862 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
863 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
864 getTranslationUnitDecl(),
865 SourceLocation(),
866 SourceLocation(),
867 &Idents.get("__int128_t"),
868 TInfo);
869 }
870
871 return Int128Decl;
872 }
873
getUInt128Decl() const874 TypedefDecl *ASTContext::getUInt128Decl() const {
875 if (!UInt128Decl) {
876 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
877 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
878 getTranslationUnitDecl(),
879 SourceLocation(),
880 SourceLocation(),
881 &Idents.get("__uint128_t"),
882 TInfo);
883 }
884
885 return UInt128Decl;
886 }
887
getFloat128StubType() const888 TypeDecl *ASTContext::getFloat128StubType() const {
889 assert(LangOpts.CPlusPlus && "should only be called for c++");
890 if (!Float128StubDecl) {
891 Float128StubDecl = CXXRecordDecl::Create(const_cast<ASTContext &>(*this),
892 TTK_Struct,
893 getTranslationUnitDecl(),
894 SourceLocation(),
895 SourceLocation(),
896 &Idents.get("__float128"));
897 }
898
899 return Float128StubDecl;
900 }
901
InitBuiltinType(CanQualType & R,BuiltinType::Kind K)902 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
903 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
904 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
905 Types.push_back(Ty);
906 }
907
InitBuiltinTypes(const TargetInfo & Target)908 void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
909 assert((!this->Target || this->Target == &Target) &&
910 "Incorrect target reinitialization");
911 assert(VoidTy.isNull() && "Context reinitialized?");
912
913 this->Target = &Target;
914
915 ABI.reset(createCXXABI(Target));
916 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
917 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
918
919 // C99 6.2.5p19.
920 InitBuiltinType(VoidTy, BuiltinType::Void);
921
922 // C99 6.2.5p2.
923 InitBuiltinType(BoolTy, BuiltinType::Bool);
924 // C99 6.2.5p3.
925 if (LangOpts.CharIsSigned)
926 InitBuiltinType(CharTy, BuiltinType::Char_S);
927 else
928 InitBuiltinType(CharTy, BuiltinType::Char_U);
929 // C99 6.2.5p4.
930 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
931 InitBuiltinType(ShortTy, BuiltinType::Short);
932 InitBuiltinType(IntTy, BuiltinType::Int);
933 InitBuiltinType(LongTy, BuiltinType::Long);
934 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
935
936 // C99 6.2.5p6.
937 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
938 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
939 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
940 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
941 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
942
943 // C99 6.2.5p10.
944 InitBuiltinType(FloatTy, BuiltinType::Float);
945 InitBuiltinType(DoubleTy, BuiltinType::Double);
946 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
947
948 // GNU extension, 128-bit integers.
949 InitBuiltinType(Int128Ty, BuiltinType::Int128);
950 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
951
952 // C++ 3.9.1p5
953 if (TargetInfo::isTypeSigned(Target.getWCharType()))
954 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
955 else // -fshort-wchar makes wchar_t be unsigned.
956 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
957 if (LangOpts.CPlusPlus && LangOpts.WChar)
958 WideCharTy = WCharTy;
959 else {
960 // C99 (or C++ using -fno-wchar).
961 WideCharTy = getFromTargetType(Target.getWCharType());
962 }
963
964 WIntTy = getFromTargetType(Target.getWIntType());
965
966 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
967 InitBuiltinType(Char16Ty, BuiltinType::Char16);
968 else // C99
969 Char16Ty = getFromTargetType(Target.getChar16Type());
970
971 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
972 InitBuiltinType(Char32Ty, BuiltinType::Char32);
973 else // C99
974 Char32Ty = getFromTargetType(Target.getChar32Type());
975
976 // Placeholder type for type-dependent expressions whose type is
977 // completely unknown. No code should ever check a type against
978 // DependentTy and users should never see it; however, it is here to
979 // help diagnose failures to properly check for type-dependent
980 // expressions.
981 InitBuiltinType(DependentTy, BuiltinType::Dependent);
982
983 // Placeholder type for functions.
984 InitBuiltinType(OverloadTy, BuiltinType::Overload);
985
986 // Placeholder type for bound members.
987 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
988
989 // Placeholder type for pseudo-objects.
990 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
991
992 // "any" type; useful for debugger-like clients.
993 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
994
995 // Placeholder type for unbridged ARC casts.
996 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
997
998 // Placeholder type for builtin functions.
999 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1000
1001 // C99 6.2.5p11.
1002 FloatComplexTy = getComplexType(FloatTy);
1003 DoubleComplexTy = getComplexType(DoubleTy);
1004 LongDoubleComplexTy = getComplexType(LongDoubleTy);
1005
1006 // Builtin types for 'id', 'Class', and 'SEL'.
1007 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1008 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1009 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1010
1011 if (LangOpts.OpenCL) {
1012 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1013 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1014 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1015 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1016 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
1017 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
1018
1019 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1020 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1021 }
1022
1023 // Builtin type for __objc_yes and __objc_no
1024 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1025 SignedCharTy : BoolTy);
1026
1027 ObjCConstantStringType = QualType();
1028
1029 ObjCSuperType = QualType();
1030
1031 // void * type
1032 VoidPtrTy = getPointerType(VoidTy);
1033
1034 // nullptr type (C++0x 2.14.7)
1035 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1036
1037 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1038 InitBuiltinType(HalfTy, BuiltinType::Half);
1039
1040 // Builtin type used to help define __builtin_va_list.
1041 VaListTagTy = QualType();
1042 }
1043
getDiagnostics() const1044 DiagnosticsEngine &ASTContext::getDiagnostics() const {
1045 return SourceMgr.getDiagnostics();
1046 }
1047
getDeclAttrs(const Decl * D)1048 AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1049 AttrVec *&Result = DeclAttrs[D];
1050 if (!Result) {
1051 void *Mem = Allocate(sizeof(AttrVec));
1052 Result = new (Mem) AttrVec;
1053 }
1054
1055 return *Result;
1056 }
1057
1058 /// \brief Erase the attributes corresponding to the given declaration.
eraseDeclAttrs(const Decl * D)1059 void ASTContext::eraseDeclAttrs(const Decl *D) {
1060 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1061 if (Pos != DeclAttrs.end()) {
1062 Pos->second->~AttrVec();
1063 DeclAttrs.erase(Pos);
1064 }
1065 }
1066
1067 // FIXME: Remove ?
1068 MemberSpecializationInfo *
getInstantiatedFromStaticDataMember(const VarDecl * Var)1069 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
1070 assert(Var->isStaticDataMember() && "Not a static data member");
1071 return getTemplateOrSpecializationInfo(Var)
1072 .dyn_cast<MemberSpecializationInfo *>();
1073 }
1074
1075 ASTContext::TemplateOrSpecializationInfo
getTemplateOrSpecializationInfo(const VarDecl * Var)1076 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1077 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1078 TemplateOrInstantiation.find(Var);
1079 if (Pos == TemplateOrInstantiation.end())
1080 return TemplateOrSpecializationInfo();
1081
1082 return Pos->second;
1083 }
1084
1085 void
setInstantiatedFromStaticDataMember(VarDecl * Inst,VarDecl * Tmpl,TemplateSpecializationKind TSK,SourceLocation PointOfInstantiation)1086 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1087 TemplateSpecializationKind TSK,
1088 SourceLocation PointOfInstantiation) {
1089 assert(Inst->isStaticDataMember() && "Not a static data member");
1090 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1091 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1092 Tmpl, TSK, PointOfInstantiation));
1093 }
1094
1095 void
setTemplateOrSpecializationInfo(VarDecl * Inst,TemplateOrSpecializationInfo TSI)1096 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1097 TemplateOrSpecializationInfo TSI) {
1098 assert(!TemplateOrInstantiation[Inst] &&
1099 "Already noted what the variable was instantiated from");
1100 TemplateOrInstantiation[Inst] = TSI;
1101 }
1102
getClassScopeSpecializationPattern(const FunctionDecl * FD)1103 FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1104 const FunctionDecl *FD){
1105 assert(FD && "Specialization is 0");
1106 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
1107 = ClassScopeSpecializationPattern.find(FD);
1108 if (Pos == ClassScopeSpecializationPattern.end())
1109 return 0;
1110
1111 return Pos->second;
1112 }
1113
setClassScopeSpecializationPattern(FunctionDecl * FD,FunctionDecl * Pattern)1114 void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1115 FunctionDecl *Pattern) {
1116 assert(FD && "Specialization is 0");
1117 assert(Pattern && "Class scope specialization pattern is 0");
1118 ClassScopeSpecializationPattern[FD] = Pattern;
1119 }
1120
1121 NamedDecl *
getInstantiatedFromUsingDecl(UsingDecl * UUD)1122 ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
1123 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
1124 = InstantiatedFromUsingDecl.find(UUD);
1125 if (Pos == InstantiatedFromUsingDecl.end())
1126 return 0;
1127
1128 return Pos->second;
1129 }
1130
1131 void
setInstantiatedFromUsingDecl(UsingDecl * Inst,NamedDecl * Pattern)1132 ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1133 assert((isa<UsingDecl>(Pattern) ||
1134 isa<UnresolvedUsingValueDecl>(Pattern) ||
1135 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1136 "pattern decl is not a using decl");
1137 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1138 InstantiatedFromUsingDecl[Inst] = Pattern;
1139 }
1140
1141 UsingShadowDecl *
getInstantiatedFromUsingShadowDecl(UsingShadowDecl * Inst)1142 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1143 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1144 = InstantiatedFromUsingShadowDecl.find(Inst);
1145 if (Pos == InstantiatedFromUsingShadowDecl.end())
1146 return 0;
1147
1148 return Pos->second;
1149 }
1150
1151 void
setInstantiatedFromUsingShadowDecl(UsingShadowDecl * Inst,UsingShadowDecl * Pattern)1152 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1153 UsingShadowDecl *Pattern) {
1154 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1155 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1156 }
1157
getInstantiatedFromUnnamedFieldDecl(FieldDecl * Field)1158 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1159 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1160 = InstantiatedFromUnnamedFieldDecl.find(Field);
1161 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1162 return 0;
1163
1164 return Pos->second;
1165 }
1166
setInstantiatedFromUnnamedFieldDecl(FieldDecl * Inst,FieldDecl * Tmpl)1167 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1168 FieldDecl *Tmpl) {
1169 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1170 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1171 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1172 "Already noted what unnamed field was instantiated from");
1173
1174 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1175 }
1176
1177 ASTContext::overridden_cxx_method_iterator
overridden_methods_begin(const CXXMethodDecl * Method) const1178 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1179 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1180 = OverriddenMethods.find(Method->getCanonicalDecl());
1181 if (Pos == OverriddenMethods.end())
1182 return 0;
1183
1184 return Pos->second.begin();
1185 }
1186
1187 ASTContext::overridden_cxx_method_iterator
overridden_methods_end(const CXXMethodDecl * Method) const1188 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1189 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1190 = OverriddenMethods.find(Method->getCanonicalDecl());
1191 if (Pos == OverriddenMethods.end())
1192 return 0;
1193
1194 return Pos->second.end();
1195 }
1196
1197 unsigned
overridden_methods_size(const CXXMethodDecl * Method) const1198 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1199 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1200 = OverriddenMethods.find(Method->getCanonicalDecl());
1201 if (Pos == OverriddenMethods.end())
1202 return 0;
1203
1204 return Pos->second.size();
1205 }
1206
addOverriddenMethod(const CXXMethodDecl * Method,const CXXMethodDecl * Overridden)1207 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1208 const CXXMethodDecl *Overridden) {
1209 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1210 OverriddenMethods[Method].push_back(Overridden);
1211 }
1212
getOverriddenMethods(const NamedDecl * D,SmallVectorImpl<const NamedDecl * > & Overridden) const1213 void ASTContext::getOverriddenMethods(
1214 const NamedDecl *D,
1215 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1216 assert(D);
1217
1218 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1219 Overridden.append(overridden_methods_begin(CXXMethod),
1220 overridden_methods_end(CXXMethod));
1221 return;
1222 }
1223
1224 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1225 if (!Method)
1226 return;
1227
1228 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1229 Method->getOverriddenMethods(OverDecls);
1230 Overridden.append(OverDecls.begin(), OverDecls.end());
1231 }
1232
addedLocalImportDecl(ImportDecl * Import)1233 void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1234 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1235 assert(!Import->isFromASTFile() && "Non-local import declaration");
1236 if (!FirstLocalImport) {
1237 FirstLocalImport = Import;
1238 LastLocalImport = Import;
1239 return;
1240 }
1241
1242 LastLocalImport->NextLocalImport = Import;
1243 LastLocalImport = Import;
1244 }
1245
1246 //===----------------------------------------------------------------------===//
1247 // Type Sizing and Analysis
1248 //===----------------------------------------------------------------------===//
1249
1250 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1251 /// scalar floating point type.
getFloatTypeSemantics(QualType T) const1252 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1253 const BuiltinType *BT = T->getAs<BuiltinType>();
1254 assert(BT && "Not a floating point type!");
1255 switch (BT->getKind()) {
1256 default: llvm_unreachable("Not a floating point type!");
1257 case BuiltinType::Half: return Target->getHalfFormat();
1258 case BuiltinType::Float: return Target->getFloatFormat();
1259 case BuiltinType::Double: return Target->getDoubleFormat();
1260 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
1261 }
1262 }
1263
getDeclAlign(const Decl * D,bool ForAlignof) const1264 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1265 unsigned Align = Target->getCharWidth();
1266
1267 bool UseAlignAttrOnly = false;
1268 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1269 Align = AlignFromAttr;
1270
1271 // __attribute__((aligned)) can increase or decrease alignment
1272 // *except* on a struct or struct member, where it only increases
1273 // alignment unless 'packed' is also specified.
1274 //
1275 // It is an error for alignas to decrease alignment, so we can
1276 // ignore that possibility; Sema should diagnose it.
1277 if (isa<FieldDecl>(D)) {
1278 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1279 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1280 } else {
1281 UseAlignAttrOnly = true;
1282 }
1283 }
1284 else if (isa<FieldDecl>(D))
1285 UseAlignAttrOnly =
1286 D->hasAttr<PackedAttr>() ||
1287 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1288
1289 // If we're using the align attribute only, just ignore everything
1290 // else about the declaration and its type.
1291 if (UseAlignAttrOnly) {
1292 // do nothing
1293
1294 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
1295 QualType T = VD->getType();
1296 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
1297 if (ForAlignof)
1298 T = RT->getPointeeType();
1299 else
1300 T = getPointerType(RT->getPointeeType());
1301 }
1302 if (!T->isIncompleteType() && !T->isFunctionType()) {
1303 // Adjust alignments of declarations with array type by the
1304 // large-array alignment on the target.
1305 if (const ArrayType *arrayType = getAsArrayType(T)) {
1306 unsigned MinWidth = Target->getLargeArrayMinWidth();
1307 if (!ForAlignof && MinWidth) {
1308 if (isa<VariableArrayType>(arrayType))
1309 Align = std::max(Align, Target->getLargeArrayAlign());
1310 else if (isa<ConstantArrayType>(arrayType) &&
1311 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1312 Align = std::max(Align, Target->getLargeArrayAlign());
1313 }
1314
1315 // Walk through any array types while we're at it.
1316 T = getBaseElementType(arrayType);
1317 }
1318 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1319 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1320 if (VD->hasGlobalStorage())
1321 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1322 }
1323 }
1324
1325 // Fields can be subject to extra alignment constraints, like if
1326 // the field is packed, the struct is packed, or the struct has a
1327 // a max-field-alignment constraint (#pragma pack). So calculate
1328 // the actual alignment of the field within the struct, and then
1329 // (as we're expected to) constrain that by the alignment of the type.
1330 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1331 const RecordDecl *Parent = Field->getParent();
1332 // We can only produce a sensible answer if the record is valid.
1333 if (!Parent->isInvalidDecl()) {
1334 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1335
1336 // Start with the record's overall alignment.
1337 unsigned FieldAlign = toBits(Layout.getAlignment());
1338
1339 // Use the GCD of that and the offset within the record.
1340 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1341 if (Offset > 0) {
1342 // Alignment is always a power of 2, so the GCD will be a power of 2,
1343 // which means we get to do this crazy thing instead of Euclid's.
1344 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1345 if (LowBitOfOffset < FieldAlign)
1346 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1347 }
1348
1349 Align = std::min(Align, FieldAlign);
1350 }
1351 }
1352 }
1353
1354 return toCharUnitsFromBits(Align);
1355 }
1356
1357 // getTypeInfoDataSizeInChars - Return the size of a type, in
1358 // chars. If the type is a record, its data size is returned. This is
1359 // the size of the memcpy that's performed when assigning this type
1360 // using a trivial copy/move assignment operator.
1361 std::pair<CharUnits, CharUnits>
getTypeInfoDataSizeInChars(QualType T) const1362 ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1363 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1364
1365 // In C++, objects can sometimes be allocated into the tail padding
1366 // of a base-class subobject. We decide whether that's possible
1367 // during class layout, so here we can just trust the layout results.
1368 if (getLangOpts().CPlusPlus) {
1369 if (const RecordType *RT = T->getAs<RecordType>()) {
1370 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1371 sizeAndAlign.first = layout.getDataSize();
1372 }
1373 }
1374
1375 return sizeAndAlign;
1376 }
1377
1378 /// getConstantArrayInfoInChars - Performing the computation in CharUnits
1379 /// instead of in bits prevents overflowing the uint64_t for some large arrays.
1380 std::pair<CharUnits, CharUnits>
getConstantArrayInfoInChars(const ASTContext & Context,const ConstantArrayType * CAT)1381 static getConstantArrayInfoInChars(const ASTContext &Context,
1382 const ConstantArrayType *CAT) {
1383 std::pair<CharUnits, CharUnits> EltInfo =
1384 Context.getTypeInfoInChars(CAT->getElementType());
1385 uint64_t Size = CAT->getSize().getZExtValue();
1386 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1387 (uint64_t)(-1)/Size) &&
1388 "Overflow in array type char size evaluation");
1389 uint64_t Width = EltInfo.first.getQuantity() * Size;
1390 unsigned Align = EltInfo.second.getQuantity();
1391 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1392 Context.getTargetInfo().getPointerWidth(0) == 64)
1393 Width = llvm::RoundUpToAlignment(Width, Align);
1394 return std::make_pair(CharUnits::fromQuantity(Width),
1395 CharUnits::fromQuantity(Align));
1396 }
1397
1398 std::pair<CharUnits, CharUnits>
getTypeInfoInChars(const Type * T) const1399 ASTContext::getTypeInfoInChars(const Type *T) const {
1400 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1401 return getConstantArrayInfoInChars(*this, CAT);
1402 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
1403 return std::make_pair(toCharUnitsFromBits(Info.first),
1404 toCharUnitsFromBits(Info.second));
1405 }
1406
1407 std::pair<CharUnits, CharUnits>
getTypeInfoInChars(QualType T) const1408 ASTContext::getTypeInfoInChars(QualType T) const {
1409 return getTypeInfoInChars(T.getTypePtr());
1410 }
1411
getTypeInfo(const Type * T) const1412 std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1413 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1414 if (it != MemoizedTypeInfo.end())
1415 return it->second;
1416
1417 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1418 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1419 return Info;
1420 }
1421
1422 /// getTypeInfoImpl - Return the size of the specified type, in bits. This
1423 /// method does not work on incomplete types.
1424 ///
1425 /// FIXME: Pointers into different addr spaces could have different sizes and
1426 /// alignment requirements: getPointerInfo should take an AddrSpace, this
1427 /// should take a QualType, &c.
1428 std::pair<uint64_t, unsigned>
getTypeInfoImpl(const Type * T) const1429 ASTContext::getTypeInfoImpl(const Type *T) const {
1430 uint64_t Width=0;
1431 unsigned Align=8;
1432 switch (T->getTypeClass()) {
1433 #define TYPE(Class, Base)
1434 #define ABSTRACT_TYPE(Class, Base)
1435 #define NON_CANONICAL_TYPE(Class, Base)
1436 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1437 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1438 case Type::Class: \
1439 assert(!T->isDependentType() && "should not see dependent types here"); \
1440 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1441 #include "clang/AST/TypeNodes.def"
1442 llvm_unreachable("Should not see dependent types");
1443
1444 case Type::FunctionNoProto:
1445 case Type::FunctionProto:
1446 // GCC extension: alignof(function) = 32 bits
1447 Width = 0;
1448 Align = 32;
1449 break;
1450
1451 case Type::IncompleteArray:
1452 case Type::VariableArray:
1453 Width = 0;
1454 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1455 break;
1456
1457 case Type::ConstantArray: {
1458 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
1459
1460 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
1461 uint64_t Size = CAT->getSize().getZExtValue();
1462 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1463 "Overflow in array type bit size evaluation");
1464 Width = EltInfo.first*Size;
1465 Align = EltInfo.second;
1466 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1467 getTargetInfo().getPointerWidth(0) == 64)
1468 Width = llvm::RoundUpToAlignment(Width, Align);
1469 break;
1470 }
1471 case Type::ExtVector:
1472 case Type::Vector: {
1473 const VectorType *VT = cast<VectorType>(T);
1474 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1475 Width = EltInfo.first*VT->getNumElements();
1476 Align = Width;
1477 // If the alignment is not a power of 2, round up to the next power of 2.
1478 // This happens for non-power-of-2 length vectors.
1479 if (Align & (Align-1)) {
1480 Align = llvm::NextPowerOf2(Align);
1481 Width = llvm::RoundUpToAlignment(Width, Align);
1482 }
1483 // Adjust the alignment based on the target max.
1484 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1485 if (TargetVectorAlign && TargetVectorAlign < Align)
1486 Align = TargetVectorAlign;
1487 break;
1488 }
1489
1490 case Type::Builtin:
1491 switch (cast<BuiltinType>(T)->getKind()) {
1492 default: llvm_unreachable("Unknown builtin type!");
1493 case BuiltinType::Void:
1494 // GCC extension: alignof(void) = 8 bits.
1495 Width = 0;
1496 Align = 8;
1497 break;
1498
1499 case BuiltinType::Bool:
1500 Width = Target->getBoolWidth();
1501 Align = Target->getBoolAlign();
1502 break;
1503 case BuiltinType::Char_S:
1504 case BuiltinType::Char_U:
1505 case BuiltinType::UChar:
1506 case BuiltinType::SChar:
1507 Width = Target->getCharWidth();
1508 Align = Target->getCharAlign();
1509 break;
1510 case BuiltinType::WChar_S:
1511 case BuiltinType::WChar_U:
1512 Width = Target->getWCharWidth();
1513 Align = Target->getWCharAlign();
1514 break;
1515 case BuiltinType::Char16:
1516 Width = Target->getChar16Width();
1517 Align = Target->getChar16Align();
1518 break;
1519 case BuiltinType::Char32:
1520 Width = Target->getChar32Width();
1521 Align = Target->getChar32Align();
1522 break;
1523 case BuiltinType::UShort:
1524 case BuiltinType::Short:
1525 Width = Target->getShortWidth();
1526 Align = Target->getShortAlign();
1527 break;
1528 case BuiltinType::UInt:
1529 case BuiltinType::Int:
1530 Width = Target->getIntWidth();
1531 Align = Target->getIntAlign();
1532 break;
1533 case BuiltinType::ULong:
1534 case BuiltinType::Long:
1535 Width = Target->getLongWidth();
1536 Align = Target->getLongAlign();
1537 break;
1538 case BuiltinType::ULongLong:
1539 case BuiltinType::LongLong:
1540 Width = Target->getLongLongWidth();
1541 Align = Target->getLongLongAlign();
1542 break;
1543 case BuiltinType::Int128:
1544 case BuiltinType::UInt128:
1545 Width = 128;
1546 Align = 128; // int128_t is 128-bit aligned on all targets.
1547 break;
1548 case BuiltinType::Half:
1549 Width = Target->getHalfWidth();
1550 Align = Target->getHalfAlign();
1551 break;
1552 case BuiltinType::Float:
1553 Width = Target->getFloatWidth();
1554 Align = Target->getFloatAlign();
1555 break;
1556 case BuiltinType::Double:
1557 Width = Target->getDoubleWidth();
1558 Align = Target->getDoubleAlign();
1559 break;
1560 case BuiltinType::LongDouble:
1561 Width = Target->getLongDoubleWidth();
1562 Align = Target->getLongDoubleAlign();
1563 break;
1564 case BuiltinType::NullPtr:
1565 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1566 Align = Target->getPointerAlign(0); // == sizeof(void*)
1567 break;
1568 case BuiltinType::ObjCId:
1569 case BuiltinType::ObjCClass:
1570 case BuiltinType::ObjCSel:
1571 Width = Target->getPointerWidth(0);
1572 Align = Target->getPointerAlign(0);
1573 break;
1574 case BuiltinType::OCLSampler:
1575 // Samplers are modeled as integers.
1576 Width = Target->getIntWidth();
1577 Align = Target->getIntAlign();
1578 break;
1579 case BuiltinType::OCLEvent:
1580 case BuiltinType::OCLImage1d:
1581 case BuiltinType::OCLImage1dArray:
1582 case BuiltinType::OCLImage1dBuffer:
1583 case BuiltinType::OCLImage2d:
1584 case BuiltinType::OCLImage2dArray:
1585 case BuiltinType::OCLImage3d:
1586 // Currently these types are pointers to opaque types.
1587 Width = Target->getPointerWidth(0);
1588 Align = Target->getPointerAlign(0);
1589 break;
1590 }
1591 break;
1592 case Type::ObjCObjectPointer:
1593 Width = Target->getPointerWidth(0);
1594 Align = Target->getPointerAlign(0);
1595 break;
1596 case Type::BlockPointer: {
1597 unsigned AS = getTargetAddressSpace(
1598 cast<BlockPointerType>(T)->getPointeeType());
1599 Width = Target->getPointerWidth(AS);
1600 Align = Target->getPointerAlign(AS);
1601 break;
1602 }
1603 case Type::LValueReference:
1604 case Type::RValueReference: {
1605 // alignof and sizeof should never enter this code path here, so we go
1606 // the pointer route.
1607 unsigned AS = getTargetAddressSpace(
1608 cast<ReferenceType>(T)->getPointeeType());
1609 Width = Target->getPointerWidth(AS);
1610 Align = Target->getPointerAlign(AS);
1611 break;
1612 }
1613 case Type::Pointer: {
1614 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
1615 Width = Target->getPointerWidth(AS);
1616 Align = Target->getPointerAlign(AS);
1617 break;
1618 }
1619 case Type::MemberPointer: {
1620 const MemberPointerType *MPT = cast<MemberPointerType>(T);
1621 llvm::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
1622 break;
1623 }
1624 case Type::Complex: {
1625 // Complex types have the same alignment as their elements, but twice the
1626 // size.
1627 std::pair<uint64_t, unsigned> EltInfo =
1628 getTypeInfo(cast<ComplexType>(T)->getElementType());
1629 Width = EltInfo.first*2;
1630 Align = EltInfo.second;
1631 break;
1632 }
1633 case Type::ObjCObject:
1634 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
1635 case Type::Decayed:
1636 return getTypeInfo(cast<DecayedType>(T)->getDecayedType().getTypePtr());
1637 case Type::ObjCInterface: {
1638 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
1639 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
1640 Width = toBits(Layout.getSize());
1641 Align = toBits(Layout.getAlignment());
1642 break;
1643 }
1644 case Type::Record:
1645 case Type::Enum: {
1646 const TagType *TT = cast<TagType>(T);
1647
1648 if (TT->getDecl()->isInvalidDecl()) {
1649 Width = 8;
1650 Align = 8;
1651 break;
1652 }
1653
1654 if (const EnumType *ET = dyn_cast<EnumType>(TT))
1655 return getTypeInfo(ET->getDecl()->getIntegerType());
1656
1657 const RecordType *RT = cast<RecordType>(TT);
1658 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
1659 Width = toBits(Layout.getSize());
1660 Align = toBits(Layout.getAlignment());
1661 break;
1662 }
1663
1664 case Type::SubstTemplateTypeParm:
1665 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1666 getReplacementType().getTypePtr());
1667
1668 case Type::Auto: {
1669 const AutoType *A = cast<AutoType>(T);
1670 assert(!A->getDeducedType().isNull() &&
1671 "cannot request the size of an undeduced or dependent auto type");
1672 return getTypeInfo(A->getDeducedType().getTypePtr());
1673 }
1674
1675 case Type::Paren:
1676 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1677
1678 case Type::Typedef: {
1679 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
1680 std::pair<uint64_t, unsigned> Info
1681 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
1682 // If the typedef has an aligned attribute on it, it overrides any computed
1683 // alignment we have. This violates the GCC documentation (which says that
1684 // attribute(aligned) can only round up) but matches its implementation.
1685 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1686 Align = AttrAlign;
1687 else
1688 Align = Info.second;
1689 Width = Info.first;
1690 break;
1691 }
1692
1693 case Type::Elaborated:
1694 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
1695
1696 case Type::Attributed:
1697 return getTypeInfo(
1698 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1699
1700 case Type::Atomic: {
1701 // Start with the base type information.
1702 std::pair<uint64_t, unsigned> Info
1703 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1704 Width = Info.first;
1705 Align = Info.second;
1706
1707 // If the size of the type doesn't exceed the platform's max
1708 // atomic promotion width, make the size and alignment more
1709 // favorable to atomic operations:
1710 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1711 // Round the size up to a power of 2.
1712 if (!llvm::isPowerOf2_64(Width))
1713 Width = llvm::NextPowerOf2(Width);
1714
1715 // Set the alignment equal to the size.
1716 Align = static_cast<unsigned>(Width);
1717 }
1718 }
1719
1720 }
1721
1722 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
1723 return std::make_pair(Width, Align);
1724 }
1725
1726 /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
toCharUnitsFromBits(int64_t BitSize) const1727 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1728 return CharUnits::fromQuantity(BitSize / getCharWidth());
1729 }
1730
1731 /// toBits - Convert a size in characters to a size in characters.
toBits(CharUnits CharSize) const1732 int64_t ASTContext::toBits(CharUnits CharSize) const {
1733 return CharSize.getQuantity() * getCharWidth();
1734 }
1735
1736 /// getTypeSizeInChars - Return the size of the specified type, in characters.
1737 /// This method does not work on incomplete types.
getTypeSizeInChars(QualType T) const1738 CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
1739 return getTypeInfoInChars(T).first;
1740 }
getTypeSizeInChars(const Type * T) const1741 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
1742 return getTypeInfoInChars(T).first;
1743 }
1744
1745 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
1746 /// characters. This method does not work on incomplete types.
getTypeAlignInChars(QualType T) const1747 CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
1748 return toCharUnitsFromBits(getTypeAlign(T));
1749 }
getTypeAlignInChars(const Type * T) const1750 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
1751 return toCharUnitsFromBits(getTypeAlign(T));
1752 }
1753
1754 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1755 /// type for the current target in bits. This can be different than the ABI
1756 /// alignment in cases where it is beneficial for performance to overalign
1757 /// a data type.
getPreferredTypeAlign(const Type * T) const1758 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
1759 unsigned ABIAlign = getTypeAlign(T);
1760
1761 if (Target->getTriple().getArch() == llvm::Triple::xcore)
1762 return ABIAlign; // Never overalign on XCore.
1763
1764 // Double and long long should be naturally aligned if possible.
1765 if (const ComplexType* CT = T->getAs<ComplexType>())
1766 T = CT->getElementType().getTypePtr();
1767 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1768 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1769 T->isSpecificBuiltinType(BuiltinType::ULongLong))
1770 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1771
1772 return ABIAlign;
1773 }
1774
1775 /// getAlignOfGlobalVar - Return the alignment in bits that should be given
1776 /// to a global variable of the specified type.
getAlignOfGlobalVar(QualType T) const1777 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1778 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1779 }
1780
1781 /// getAlignOfGlobalVarInChars - Return the alignment in characters that
1782 /// should be given to a global variable of the specified type.
getAlignOfGlobalVarInChars(QualType T) const1783 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1784 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1785 }
1786
1787 /// DeepCollectObjCIvars -
1788 /// This routine first collects all declared, but not synthesized, ivars in
1789 /// super class and then collects all ivars, including those synthesized for
1790 /// current class. This routine is used for implementation of current class
1791 /// when all ivars, declared and synthesized are known.
1792 ///
DeepCollectObjCIvars(const ObjCInterfaceDecl * OI,bool leafClass,SmallVectorImpl<const ObjCIvarDecl * > & Ivars) const1793 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1794 bool leafClass,
1795 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
1796 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1797 DeepCollectObjCIvars(SuperClass, false, Ivars);
1798 if (!leafClass) {
1799 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1800 E = OI->ivar_end(); I != E; ++I)
1801 Ivars.push_back(*I);
1802 } else {
1803 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
1804 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
1805 Iv= Iv->getNextIvar())
1806 Ivars.push_back(Iv);
1807 }
1808 }
1809
1810 /// CollectInheritedProtocols - Collect all protocols in current class and
1811 /// those inherited by it.
CollectInheritedProtocols(const Decl * CDecl,llvm::SmallPtrSet<ObjCProtocolDecl *,8> & Protocols)1812 void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
1813 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
1814 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1815 // We can use protocol_iterator here instead of
1816 // all_referenced_protocol_iterator since we are walking all categories.
1817 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1818 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
1819 ObjCProtocolDecl *Proto = (*P);
1820 Protocols.insert(Proto->getCanonicalDecl());
1821 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1822 PE = Proto->protocol_end(); P != PE; ++P) {
1823 Protocols.insert((*P)->getCanonicalDecl());
1824 CollectInheritedProtocols(*P, Protocols);
1825 }
1826 }
1827
1828 // Categories of this Interface.
1829 for (ObjCInterfaceDecl::visible_categories_iterator
1830 Cat = OI->visible_categories_begin(),
1831 CatEnd = OI->visible_categories_end();
1832 Cat != CatEnd; ++Cat) {
1833 CollectInheritedProtocols(*Cat, Protocols);
1834 }
1835
1836 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1837 while (SD) {
1838 CollectInheritedProtocols(SD, Protocols);
1839 SD = SD->getSuperClass();
1840 }
1841 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1842 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
1843 PE = OC->protocol_end(); P != PE; ++P) {
1844 ObjCProtocolDecl *Proto = (*P);
1845 Protocols.insert(Proto->getCanonicalDecl());
1846 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1847 PE = Proto->protocol_end(); P != PE; ++P)
1848 CollectInheritedProtocols(*P, Protocols);
1849 }
1850 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
1851 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1852 PE = OP->protocol_end(); P != PE; ++P) {
1853 ObjCProtocolDecl *Proto = (*P);
1854 Protocols.insert(Proto->getCanonicalDecl());
1855 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1856 PE = Proto->protocol_end(); P != PE; ++P)
1857 CollectInheritedProtocols(*P, Protocols);
1858 }
1859 }
1860 }
1861
CountNonClassIvars(const ObjCInterfaceDecl * OI) const1862 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
1863 unsigned count = 0;
1864 // Count ivars declared in class extension.
1865 for (ObjCInterfaceDecl::known_extensions_iterator
1866 Ext = OI->known_extensions_begin(),
1867 ExtEnd = OI->known_extensions_end();
1868 Ext != ExtEnd; ++Ext) {
1869 count += Ext->ivar_size();
1870 }
1871
1872 // Count ivar defined in this class's implementation. This
1873 // includes synthesized ivars.
1874 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
1875 count += ImplDecl->ivar_size();
1876
1877 return count;
1878 }
1879
isSentinelNullExpr(const Expr * E)1880 bool ASTContext::isSentinelNullExpr(const Expr *E) {
1881 if (!E)
1882 return false;
1883
1884 // nullptr_t is always treated as null.
1885 if (E->getType()->isNullPtrType()) return true;
1886
1887 if (E->getType()->isAnyPointerType() &&
1888 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1889 Expr::NPC_ValueDependentIsNull))
1890 return true;
1891
1892 // Unfortunately, __null has type 'int'.
1893 if (isa<GNUNullExpr>(E)) return true;
1894
1895 return false;
1896 }
1897
1898 /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
getObjCImplementation(ObjCInterfaceDecl * D)1899 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1900 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1901 I = ObjCImpls.find(D);
1902 if (I != ObjCImpls.end())
1903 return cast<ObjCImplementationDecl>(I->second);
1904 return 0;
1905 }
1906 /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
getObjCImplementation(ObjCCategoryDecl * D)1907 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1908 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1909 I = ObjCImpls.find(D);
1910 if (I != ObjCImpls.end())
1911 return cast<ObjCCategoryImplDecl>(I->second);
1912 return 0;
1913 }
1914
1915 /// \brief Set the implementation of ObjCInterfaceDecl.
setObjCImplementation(ObjCInterfaceDecl * IFaceD,ObjCImplementationDecl * ImplD)1916 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1917 ObjCImplementationDecl *ImplD) {
1918 assert(IFaceD && ImplD && "Passed null params");
1919 ObjCImpls[IFaceD] = ImplD;
1920 }
1921 /// \brief Set the implementation of ObjCCategoryDecl.
setObjCImplementation(ObjCCategoryDecl * CatD,ObjCCategoryImplDecl * ImplD)1922 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1923 ObjCCategoryImplDecl *ImplD) {
1924 assert(CatD && ImplD && "Passed null params");
1925 ObjCImpls[CatD] = ImplD;
1926 }
1927
getObjContainingInterface(const NamedDecl * ND) const1928 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1929 const NamedDecl *ND) const {
1930 if (const ObjCInterfaceDecl *ID =
1931 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1932 return ID;
1933 if (const ObjCCategoryDecl *CD =
1934 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1935 return CD->getClassInterface();
1936 if (const ObjCImplDecl *IMD =
1937 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1938 return IMD->getClassInterface();
1939
1940 return 0;
1941 }
1942
1943 /// \brief Get the copy initialization expression of VarDecl,or NULL if
1944 /// none exists.
getBlockVarCopyInits(const VarDecl * VD)1945 Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
1946 assert(VD && "Passed null params");
1947 assert(VD->hasAttr<BlocksAttr>() &&
1948 "getBlockVarCopyInits - not __block var");
1949 llvm::DenseMap<const VarDecl*, Expr*>::iterator
1950 I = BlockVarCopyInits.find(VD);
1951 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1952 }
1953
1954 /// \brief Set the copy inialization expression of a block var decl.
setBlockVarCopyInits(VarDecl * VD,Expr * Init)1955 void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1956 assert(VD && Init && "Passed null params");
1957 assert(VD->hasAttr<BlocksAttr>() &&
1958 "setBlockVarCopyInits - not __block var");
1959 BlockVarCopyInits[VD] = Init;
1960 }
1961
CreateTypeSourceInfo(QualType T,unsigned DataSize) const1962 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
1963 unsigned DataSize) const {
1964 if (!DataSize)
1965 DataSize = TypeLoc::getFullDataSizeForType(T);
1966 else
1967 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
1968 "incorrect data size provided to CreateTypeSourceInfo!");
1969
1970 TypeSourceInfo *TInfo =
1971 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1972 new (TInfo) TypeSourceInfo(T);
1973 return TInfo;
1974 }
1975
getTrivialTypeSourceInfo(QualType T,SourceLocation L) const1976 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
1977 SourceLocation L) const {
1978 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
1979 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
1980 return DI;
1981 }
1982
1983 const ASTRecordLayout &
getASTObjCInterfaceLayout(const ObjCInterfaceDecl * D) const1984 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
1985 return getObjCLayout(D, 0);
1986 }
1987
1988 const ASTRecordLayout &
getASTObjCImplementationLayout(const ObjCImplementationDecl * D) const1989 ASTContext::getASTObjCImplementationLayout(
1990 const ObjCImplementationDecl *D) const {
1991 return getObjCLayout(D->getClassInterface(), D);
1992 }
1993
1994 //===----------------------------------------------------------------------===//
1995 // Type creation/memoization methods
1996 //===----------------------------------------------------------------------===//
1997
1998 QualType
getExtQualType(const Type * baseType,Qualifiers quals) const1999 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2000 unsigned fastQuals = quals.getFastQualifiers();
2001 quals.removeFastQualifiers();
2002
2003 // Check if we've already instantiated this type.
2004 llvm::FoldingSetNodeID ID;
2005 ExtQuals::Profile(ID, baseType, quals);
2006 void *insertPos = 0;
2007 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2008 assert(eq->getQualifiers() == quals);
2009 return QualType(eq, fastQuals);
2010 }
2011
2012 // If the base type is not canonical, make the appropriate canonical type.
2013 QualType canon;
2014 if (!baseType->isCanonicalUnqualified()) {
2015 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
2016 canonSplit.Quals.addConsistentQualifiers(quals);
2017 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
2018
2019 // Re-find the insert position.
2020 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2021 }
2022
2023 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2024 ExtQualNodes.InsertNode(eq, insertPos);
2025 return QualType(eq, fastQuals);
2026 }
2027
2028 QualType
getAddrSpaceQualType(QualType T,unsigned AddressSpace) const2029 ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
2030 QualType CanT = getCanonicalType(T);
2031 if (CanT.getAddressSpace() == AddressSpace)
2032 return T;
2033
2034 // If we are composing extended qualifiers together, merge together
2035 // into one ExtQuals node.
2036 QualifierCollector Quals;
2037 const Type *TypeNode = Quals.strip(T);
2038
2039 // If this type already has an address space specified, it cannot get
2040 // another one.
2041 assert(!Quals.hasAddressSpace() &&
2042 "Type cannot be in multiple addr spaces!");
2043 Quals.addAddressSpace(AddressSpace);
2044
2045 return getExtQualType(TypeNode, Quals);
2046 }
2047
getObjCGCQualType(QualType T,Qualifiers::GC GCAttr) const2048 QualType ASTContext::getObjCGCQualType(QualType T,
2049 Qualifiers::GC GCAttr) const {
2050 QualType CanT = getCanonicalType(T);
2051 if (CanT.getObjCGCAttr() == GCAttr)
2052 return T;
2053
2054 if (const PointerType *ptr = T->getAs<PointerType>()) {
2055 QualType Pointee = ptr->getPointeeType();
2056 if (Pointee->isAnyPointerType()) {
2057 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2058 return getPointerType(ResultType);
2059 }
2060 }
2061
2062 // If we are composing extended qualifiers together, merge together
2063 // into one ExtQuals node.
2064 QualifierCollector Quals;
2065 const Type *TypeNode = Quals.strip(T);
2066
2067 // If this type already has an ObjCGC specified, it cannot get
2068 // another one.
2069 assert(!Quals.hasObjCGCAttr() &&
2070 "Type cannot have multiple ObjCGCs!");
2071 Quals.addObjCGCAttr(GCAttr);
2072
2073 return getExtQualType(TypeNode, Quals);
2074 }
2075
adjustFunctionType(const FunctionType * T,FunctionType::ExtInfo Info)2076 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2077 FunctionType::ExtInfo Info) {
2078 if (T->getExtInfo() == Info)
2079 return T;
2080
2081 QualType Result;
2082 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2083 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
2084 } else {
2085 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2086 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2087 EPI.ExtInfo = Info;
2088 Result = getFunctionType(FPT->getResultType(), FPT->getArgTypes(), EPI);
2089 }
2090
2091 return cast<FunctionType>(Result.getTypePtr());
2092 }
2093
adjustDeducedFunctionResultType(FunctionDecl * FD,QualType ResultType)2094 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2095 QualType ResultType) {
2096 FD = FD->getMostRecentDecl();
2097 while (true) {
2098 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2099 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2100 FD->setType(getFunctionType(ResultType, FPT->getArgTypes(), EPI));
2101 if (FunctionDecl *Next = FD->getPreviousDecl())
2102 FD = Next;
2103 else
2104 break;
2105 }
2106 if (ASTMutationListener *L = getASTMutationListener())
2107 L->DeducedReturnType(FD, ResultType);
2108 }
2109
2110 /// getComplexType - Return the uniqued reference to the type for a complex
2111 /// number with the specified element type.
getComplexType(QualType T) const2112 QualType ASTContext::getComplexType(QualType T) const {
2113 // Unique pointers, to guarantee there is only one pointer of a particular
2114 // structure.
2115 llvm::FoldingSetNodeID ID;
2116 ComplexType::Profile(ID, T);
2117
2118 void *InsertPos = 0;
2119 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2120 return QualType(CT, 0);
2121
2122 // If the pointee type isn't canonical, this won't be a canonical type either,
2123 // so fill in the canonical type field.
2124 QualType Canonical;
2125 if (!T.isCanonical()) {
2126 Canonical = getComplexType(getCanonicalType(T));
2127
2128 // Get the new insert position for the node we care about.
2129 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
2130 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2131 }
2132 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
2133 Types.push_back(New);
2134 ComplexTypes.InsertNode(New, InsertPos);
2135 return QualType(New, 0);
2136 }
2137
2138 /// getPointerType - Return the uniqued reference to the type for a pointer to
2139 /// the specified type.
getPointerType(QualType T) const2140 QualType ASTContext::getPointerType(QualType T) const {
2141 // Unique pointers, to guarantee there is only one pointer of a particular
2142 // structure.
2143 llvm::FoldingSetNodeID ID;
2144 PointerType::Profile(ID, T);
2145
2146 void *InsertPos = 0;
2147 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2148 return QualType(PT, 0);
2149
2150 // If the pointee type isn't canonical, this won't be a canonical type either,
2151 // so fill in the canonical type field.
2152 QualType Canonical;
2153 if (!T.isCanonical()) {
2154 Canonical = getPointerType(getCanonicalType(T));
2155
2156 // Get the new insert position for the node we care about.
2157 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2158 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2159 }
2160 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
2161 Types.push_back(New);
2162 PointerTypes.InsertNode(New, InsertPos);
2163 return QualType(New, 0);
2164 }
2165
getDecayedType(QualType T) const2166 QualType ASTContext::getDecayedType(QualType T) const {
2167 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2168
2169 llvm::FoldingSetNodeID ID;
2170 DecayedType::Profile(ID, T);
2171 void *InsertPos = 0;
2172 if (DecayedType *DT = DecayedTypes.FindNodeOrInsertPos(ID, InsertPos))
2173 return QualType(DT, 0);
2174
2175 QualType Decayed;
2176
2177 // C99 6.7.5.3p7:
2178 // A declaration of a parameter as "array of type" shall be
2179 // adjusted to "qualified pointer to type", where the type
2180 // qualifiers (if any) are those specified within the [ and ] of
2181 // the array type derivation.
2182 if (T->isArrayType())
2183 Decayed = getArrayDecayedType(T);
2184
2185 // C99 6.7.5.3p8:
2186 // A declaration of a parameter as "function returning type"
2187 // shall be adjusted to "pointer to function returning type", as
2188 // in 6.3.2.1.
2189 if (T->isFunctionType())
2190 Decayed = getPointerType(T);
2191
2192 QualType Canonical = getCanonicalType(Decayed);
2193
2194 // Get the new insert position for the node we care about.
2195 DecayedType *NewIP = DecayedTypes.FindNodeOrInsertPos(ID, InsertPos);
2196 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2197
2198 DecayedType *New =
2199 new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2200 Types.push_back(New);
2201 DecayedTypes.InsertNode(New, InsertPos);
2202 return QualType(New, 0);
2203 }
2204
2205 /// getBlockPointerType - Return the uniqued reference to the type for
2206 /// a pointer to the specified block.
getBlockPointerType(QualType T) const2207 QualType ASTContext::getBlockPointerType(QualType T) const {
2208 assert(T->isFunctionType() && "block of function types only");
2209 // Unique pointers, to guarantee there is only one block of a particular
2210 // structure.
2211 llvm::FoldingSetNodeID ID;
2212 BlockPointerType::Profile(ID, T);
2213
2214 void *InsertPos = 0;
2215 if (BlockPointerType *PT =
2216 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2217 return QualType(PT, 0);
2218
2219 // If the block pointee type isn't canonical, this won't be a canonical
2220 // type either so fill in the canonical type field.
2221 QualType Canonical;
2222 if (!T.isCanonical()) {
2223 Canonical = getBlockPointerType(getCanonicalType(T));
2224
2225 // Get the new insert position for the node we care about.
2226 BlockPointerType *NewIP =
2227 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2228 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2229 }
2230 BlockPointerType *New
2231 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
2232 Types.push_back(New);
2233 BlockPointerTypes.InsertNode(New, InsertPos);
2234 return QualType(New, 0);
2235 }
2236
2237 /// getLValueReferenceType - Return the uniqued reference to the type for an
2238 /// lvalue reference to the specified type.
2239 QualType
getLValueReferenceType(QualType T,bool SpelledAsLValue) const2240 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
2241 assert(getCanonicalType(T) != OverloadTy &&
2242 "Unresolved overloaded function type");
2243
2244 // Unique pointers, to guarantee there is only one pointer of a particular
2245 // structure.
2246 llvm::FoldingSetNodeID ID;
2247 ReferenceType::Profile(ID, T, SpelledAsLValue);
2248
2249 void *InsertPos = 0;
2250 if (LValueReferenceType *RT =
2251 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2252 return QualType(RT, 0);
2253
2254 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2255
2256 // If the referencee type isn't canonical, this won't be a canonical type
2257 // either, so fill in the canonical type field.
2258 QualType Canonical;
2259 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2260 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2261 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
2262
2263 // Get the new insert position for the node we care about.
2264 LValueReferenceType *NewIP =
2265 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2266 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2267 }
2268
2269 LValueReferenceType *New
2270 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2271 SpelledAsLValue);
2272 Types.push_back(New);
2273 LValueReferenceTypes.InsertNode(New, InsertPos);
2274
2275 return QualType(New, 0);
2276 }
2277
2278 /// getRValueReferenceType - Return the uniqued reference to the type for an
2279 /// rvalue reference to the specified type.
getRValueReferenceType(QualType T) const2280 QualType ASTContext::getRValueReferenceType(QualType T) const {
2281 // Unique pointers, to guarantee there is only one pointer of a particular
2282 // structure.
2283 llvm::FoldingSetNodeID ID;
2284 ReferenceType::Profile(ID, T, false);
2285
2286 void *InsertPos = 0;
2287 if (RValueReferenceType *RT =
2288 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2289 return QualType(RT, 0);
2290
2291 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2292
2293 // If the referencee type isn't canonical, this won't be a canonical type
2294 // either, so fill in the canonical type field.
2295 QualType Canonical;
2296 if (InnerRef || !T.isCanonical()) {
2297 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2298 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
2299
2300 // Get the new insert position for the node we care about.
2301 RValueReferenceType *NewIP =
2302 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2303 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2304 }
2305
2306 RValueReferenceType *New
2307 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
2308 Types.push_back(New);
2309 RValueReferenceTypes.InsertNode(New, InsertPos);
2310 return QualType(New, 0);
2311 }
2312
2313 /// getMemberPointerType - Return the uniqued reference to the type for a
2314 /// member pointer to the specified type, in the specified class.
getMemberPointerType(QualType T,const Type * Cls) const2315 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
2316 // Unique pointers, to guarantee there is only one pointer of a particular
2317 // structure.
2318 llvm::FoldingSetNodeID ID;
2319 MemberPointerType::Profile(ID, T, Cls);
2320
2321 void *InsertPos = 0;
2322 if (MemberPointerType *PT =
2323 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2324 return QualType(PT, 0);
2325
2326 // If the pointee or class type isn't canonical, this won't be a canonical
2327 // type either, so fill in the canonical type field.
2328 QualType Canonical;
2329 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
2330 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2331
2332 // Get the new insert position for the node we care about.
2333 MemberPointerType *NewIP =
2334 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2335 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2336 }
2337 MemberPointerType *New
2338 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
2339 Types.push_back(New);
2340 MemberPointerTypes.InsertNode(New, InsertPos);
2341 return QualType(New, 0);
2342 }
2343
2344 /// getConstantArrayType - Return the unique reference to the type for an
2345 /// array of the specified element type.
getConstantArrayType(QualType EltTy,const llvm::APInt & ArySizeIn,ArrayType::ArraySizeModifier ASM,unsigned IndexTypeQuals) const2346 QualType ASTContext::getConstantArrayType(QualType EltTy,
2347 const llvm::APInt &ArySizeIn,
2348 ArrayType::ArraySizeModifier ASM,
2349 unsigned IndexTypeQuals) const {
2350 assert((EltTy->isDependentType() ||
2351 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
2352 "Constant array of VLAs is illegal!");
2353
2354 // Convert the array size into a canonical width matching the pointer size for
2355 // the target.
2356 llvm::APInt ArySize(ArySizeIn);
2357 ArySize =
2358 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
2359
2360 llvm::FoldingSetNodeID ID;
2361 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
2362
2363 void *InsertPos = 0;
2364 if (ConstantArrayType *ATP =
2365 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
2366 return QualType(ATP, 0);
2367
2368 // If the element type isn't canonical or has qualifiers, this won't
2369 // be a canonical type either, so fill in the canonical type field.
2370 QualType Canon;
2371 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2372 SplitQualType canonSplit = getCanonicalType(EltTy).split();
2373 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
2374 ASM, IndexTypeQuals);
2375 Canon = getQualifiedType(Canon, canonSplit.Quals);
2376
2377 // Get the new insert position for the node we care about.
2378 ConstantArrayType *NewIP =
2379 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
2380 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2381 }
2382
2383 ConstantArrayType *New = new(*this,TypeAlignment)
2384 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
2385 ConstantArrayTypes.InsertNode(New, InsertPos);
2386 Types.push_back(New);
2387 return QualType(New, 0);
2388 }
2389
2390 /// getVariableArrayDecayedType - Turns the given type, which may be
2391 /// variably-modified, into the corresponding type with all the known
2392 /// sizes replaced with [*].
getVariableArrayDecayedType(QualType type) const2393 QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2394 // Vastly most common case.
2395 if (!type->isVariablyModifiedType()) return type;
2396
2397 QualType result;
2398
2399 SplitQualType split = type.getSplitDesugaredType();
2400 const Type *ty = split.Ty;
2401 switch (ty->getTypeClass()) {
2402 #define TYPE(Class, Base)
2403 #define ABSTRACT_TYPE(Class, Base)
2404 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2405 #include "clang/AST/TypeNodes.def"
2406 llvm_unreachable("didn't desugar past all non-canonical types?");
2407
2408 // These types should never be variably-modified.
2409 case Type::Builtin:
2410 case Type::Complex:
2411 case Type::Vector:
2412 case Type::ExtVector:
2413 case Type::DependentSizedExtVector:
2414 case Type::ObjCObject:
2415 case Type::ObjCInterface:
2416 case Type::ObjCObjectPointer:
2417 case Type::Record:
2418 case Type::Enum:
2419 case Type::UnresolvedUsing:
2420 case Type::TypeOfExpr:
2421 case Type::TypeOf:
2422 case Type::Decltype:
2423 case Type::UnaryTransform:
2424 case Type::DependentName:
2425 case Type::InjectedClassName:
2426 case Type::TemplateSpecialization:
2427 case Type::DependentTemplateSpecialization:
2428 case Type::TemplateTypeParm:
2429 case Type::SubstTemplateTypeParmPack:
2430 case Type::Auto:
2431 case Type::PackExpansion:
2432 llvm_unreachable("type should never be variably-modified");
2433
2434 // These types can be variably-modified but should never need to
2435 // further decay.
2436 case Type::FunctionNoProto:
2437 case Type::FunctionProto:
2438 case Type::BlockPointer:
2439 case Type::MemberPointer:
2440 return type;
2441
2442 // These types can be variably-modified. All these modifications
2443 // preserve structure except as noted by comments.
2444 // TODO: if we ever care about optimizing VLAs, there are no-op
2445 // optimizations available here.
2446 case Type::Pointer:
2447 result = getPointerType(getVariableArrayDecayedType(
2448 cast<PointerType>(ty)->getPointeeType()));
2449 break;
2450
2451 case Type::LValueReference: {
2452 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2453 result = getLValueReferenceType(
2454 getVariableArrayDecayedType(lv->getPointeeType()),
2455 lv->isSpelledAsLValue());
2456 break;
2457 }
2458
2459 case Type::RValueReference: {
2460 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2461 result = getRValueReferenceType(
2462 getVariableArrayDecayedType(lv->getPointeeType()));
2463 break;
2464 }
2465
2466 case Type::Atomic: {
2467 const AtomicType *at = cast<AtomicType>(ty);
2468 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2469 break;
2470 }
2471
2472 case Type::ConstantArray: {
2473 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2474 result = getConstantArrayType(
2475 getVariableArrayDecayedType(cat->getElementType()),
2476 cat->getSize(),
2477 cat->getSizeModifier(),
2478 cat->getIndexTypeCVRQualifiers());
2479 break;
2480 }
2481
2482 case Type::DependentSizedArray: {
2483 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2484 result = getDependentSizedArrayType(
2485 getVariableArrayDecayedType(dat->getElementType()),
2486 dat->getSizeExpr(),
2487 dat->getSizeModifier(),
2488 dat->getIndexTypeCVRQualifiers(),
2489 dat->getBracketsRange());
2490 break;
2491 }
2492
2493 // Turn incomplete types into [*] types.
2494 case Type::IncompleteArray: {
2495 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2496 result = getVariableArrayType(
2497 getVariableArrayDecayedType(iat->getElementType()),
2498 /*size*/ 0,
2499 ArrayType::Normal,
2500 iat->getIndexTypeCVRQualifiers(),
2501 SourceRange());
2502 break;
2503 }
2504
2505 // Turn VLA types into [*] types.
2506 case Type::VariableArray: {
2507 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2508 result = getVariableArrayType(
2509 getVariableArrayDecayedType(vat->getElementType()),
2510 /*size*/ 0,
2511 ArrayType::Star,
2512 vat->getIndexTypeCVRQualifiers(),
2513 vat->getBracketsRange());
2514 break;
2515 }
2516 }
2517
2518 // Apply the top-level qualifiers from the original.
2519 return getQualifiedType(result, split.Quals);
2520 }
2521
2522 /// getVariableArrayType - Returns a non-unique reference to the type for a
2523 /// variable array of the specified element type.
getVariableArrayType(QualType EltTy,Expr * NumElts,ArrayType::ArraySizeModifier ASM,unsigned IndexTypeQuals,SourceRange Brackets) const2524 QualType ASTContext::getVariableArrayType(QualType EltTy,
2525 Expr *NumElts,
2526 ArrayType::ArraySizeModifier ASM,
2527 unsigned IndexTypeQuals,
2528 SourceRange Brackets) const {
2529 // Since we don't unique expressions, it isn't possible to unique VLA's
2530 // that have an expression provided for their size.
2531 QualType Canon;
2532
2533 // Be sure to pull qualifiers off the element type.
2534 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2535 SplitQualType canonSplit = getCanonicalType(EltTy).split();
2536 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
2537 IndexTypeQuals, Brackets);
2538 Canon = getQualifiedType(Canon, canonSplit.Quals);
2539 }
2540
2541 VariableArrayType *New = new(*this, TypeAlignment)
2542 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
2543
2544 VariableArrayTypes.push_back(New);
2545 Types.push_back(New);
2546 return QualType(New, 0);
2547 }
2548
2549 /// getDependentSizedArrayType - Returns a non-unique reference to
2550 /// the type for a dependently-sized array of the specified element
2551 /// type.
getDependentSizedArrayType(QualType elementType,Expr * numElements,ArrayType::ArraySizeModifier ASM,unsigned elementTypeQuals,SourceRange brackets) const2552 QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2553 Expr *numElements,
2554 ArrayType::ArraySizeModifier ASM,
2555 unsigned elementTypeQuals,
2556 SourceRange brackets) const {
2557 assert((!numElements || numElements->isTypeDependent() ||
2558 numElements->isValueDependent()) &&
2559 "Size must be type- or value-dependent!");
2560
2561 // Dependently-sized array types that do not have a specified number
2562 // of elements will have their sizes deduced from a dependent
2563 // initializer. We do no canonicalization here at all, which is okay
2564 // because they can't be used in most locations.
2565 if (!numElements) {
2566 DependentSizedArrayType *newType
2567 = new (*this, TypeAlignment)
2568 DependentSizedArrayType(*this, elementType, QualType(),
2569 numElements, ASM, elementTypeQuals,
2570 brackets);
2571 Types.push_back(newType);
2572 return QualType(newType, 0);
2573 }
2574
2575 // Otherwise, we actually build a new type every time, but we
2576 // also build a canonical type.
2577
2578 SplitQualType canonElementType = getCanonicalType(elementType).split();
2579
2580 void *insertPos = 0;
2581 llvm::FoldingSetNodeID ID;
2582 DependentSizedArrayType::Profile(ID, *this,
2583 QualType(canonElementType.Ty, 0),
2584 ASM, elementTypeQuals, numElements);
2585
2586 // Look for an existing type with these properties.
2587 DependentSizedArrayType *canonTy =
2588 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2589
2590 // If we don't have one, build one.
2591 if (!canonTy) {
2592 canonTy = new (*this, TypeAlignment)
2593 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
2594 QualType(), numElements, ASM, elementTypeQuals,
2595 brackets);
2596 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2597 Types.push_back(canonTy);
2598 }
2599
2600 // Apply qualifiers from the element type to the array.
2601 QualType canon = getQualifiedType(QualType(canonTy,0),
2602 canonElementType.Quals);
2603
2604 // If we didn't need extra canonicalization for the element type,
2605 // then just use that as our result.
2606 if (QualType(canonElementType.Ty, 0) == elementType)
2607 return canon;
2608
2609 // Otherwise, we need to build a type which follows the spelling
2610 // of the element type.
2611 DependentSizedArrayType *sugaredType
2612 = new (*this, TypeAlignment)
2613 DependentSizedArrayType(*this, elementType, canon, numElements,
2614 ASM, elementTypeQuals, brackets);
2615 Types.push_back(sugaredType);
2616 return QualType(sugaredType, 0);
2617 }
2618
getIncompleteArrayType(QualType elementType,ArrayType::ArraySizeModifier ASM,unsigned elementTypeQuals) const2619 QualType ASTContext::getIncompleteArrayType(QualType elementType,
2620 ArrayType::ArraySizeModifier ASM,
2621 unsigned elementTypeQuals) const {
2622 llvm::FoldingSetNodeID ID;
2623 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
2624
2625 void *insertPos = 0;
2626 if (IncompleteArrayType *iat =
2627 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2628 return QualType(iat, 0);
2629
2630 // If the element type isn't canonical, this won't be a canonical type
2631 // either, so fill in the canonical type field. We also have to pull
2632 // qualifiers off the element type.
2633 QualType canon;
2634
2635 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2636 SplitQualType canonSplit = getCanonicalType(elementType).split();
2637 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
2638 ASM, elementTypeQuals);
2639 canon = getQualifiedType(canon, canonSplit.Quals);
2640
2641 // Get the new insert position for the node we care about.
2642 IncompleteArrayType *existing =
2643 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2644 assert(!existing && "Shouldn't be in the map!"); (void) existing;
2645 }
2646
2647 IncompleteArrayType *newType = new (*this, TypeAlignment)
2648 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
2649
2650 IncompleteArrayTypes.InsertNode(newType, insertPos);
2651 Types.push_back(newType);
2652 return QualType(newType, 0);
2653 }
2654
2655 /// getVectorType - Return the unique reference to a vector type of
2656 /// the specified element type and size. VectorType must be a built-in type.
getVectorType(QualType vecType,unsigned NumElts,VectorType::VectorKind VecKind) const2657 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
2658 VectorType::VectorKind VecKind) const {
2659 assert(vecType->isBuiltinType());
2660
2661 // Check if we've already instantiated a vector of this type.
2662 llvm::FoldingSetNodeID ID;
2663 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
2664
2665 void *InsertPos = 0;
2666 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2667 return QualType(VTP, 0);
2668
2669 // If the element type isn't canonical, this won't be a canonical type either,
2670 // so fill in the canonical type field.
2671 QualType Canonical;
2672 if (!vecType.isCanonical()) {
2673 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
2674
2675 // Get the new insert position for the node we care about.
2676 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2677 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2678 }
2679 VectorType *New = new (*this, TypeAlignment)
2680 VectorType(vecType, NumElts, Canonical, VecKind);
2681 VectorTypes.InsertNode(New, InsertPos);
2682 Types.push_back(New);
2683 return QualType(New, 0);
2684 }
2685
2686 /// getExtVectorType - Return the unique reference to an extended vector type of
2687 /// the specified element type and size. VectorType must be a built-in type.
2688 QualType
getExtVectorType(QualType vecType,unsigned NumElts) const2689 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
2690 assert(vecType->isBuiltinType() || vecType->isDependentType());
2691
2692 // Check if we've already instantiated a vector of this type.
2693 llvm::FoldingSetNodeID ID;
2694 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
2695 VectorType::GenericVector);
2696 void *InsertPos = 0;
2697 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2698 return QualType(VTP, 0);
2699
2700 // If the element type isn't canonical, this won't be a canonical type either,
2701 // so fill in the canonical type field.
2702 QualType Canonical;
2703 if (!vecType.isCanonical()) {
2704 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
2705
2706 // Get the new insert position for the node we care about.
2707 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2708 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2709 }
2710 ExtVectorType *New = new (*this, TypeAlignment)
2711 ExtVectorType(vecType, NumElts, Canonical);
2712 VectorTypes.InsertNode(New, InsertPos);
2713 Types.push_back(New);
2714 return QualType(New, 0);
2715 }
2716
2717 QualType
getDependentSizedExtVectorType(QualType vecType,Expr * SizeExpr,SourceLocation AttrLoc) const2718 ASTContext::getDependentSizedExtVectorType(QualType vecType,
2719 Expr *SizeExpr,
2720 SourceLocation AttrLoc) const {
2721 llvm::FoldingSetNodeID ID;
2722 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
2723 SizeExpr);
2724
2725 void *InsertPos = 0;
2726 DependentSizedExtVectorType *Canon
2727 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2728 DependentSizedExtVectorType *New;
2729 if (Canon) {
2730 // We already have a canonical version of this array type; use it as
2731 // the canonical type for a newly-built type.
2732 New = new (*this, TypeAlignment)
2733 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2734 SizeExpr, AttrLoc);
2735 } else {
2736 QualType CanonVecTy = getCanonicalType(vecType);
2737 if (CanonVecTy == vecType) {
2738 New = new (*this, TypeAlignment)
2739 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2740 AttrLoc);
2741
2742 DependentSizedExtVectorType *CanonCheck
2743 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2744 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2745 (void)CanonCheck;
2746 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2747 } else {
2748 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2749 SourceLocation());
2750 New = new (*this, TypeAlignment)
2751 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
2752 }
2753 }
2754
2755 Types.push_back(New);
2756 return QualType(New, 0);
2757 }
2758
2759 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
2760 ///
2761 QualType
getFunctionNoProtoType(QualType ResultTy,const FunctionType::ExtInfo & Info) const2762 ASTContext::getFunctionNoProtoType(QualType ResultTy,
2763 const FunctionType::ExtInfo &Info) const {
2764 const CallingConv CallConv = Info.getCC();
2765
2766 // Unique functions, to guarantee there is only one function of a particular
2767 // structure.
2768 llvm::FoldingSetNodeID ID;
2769 FunctionNoProtoType::Profile(ID, ResultTy, Info);
2770
2771 void *InsertPos = 0;
2772 if (FunctionNoProtoType *FT =
2773 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
2774 return QualType(FT, 0);
2775
2776 QualType Canonical;
2777 if (!ResultTy.isCanonical()) {
2778 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
2779
2780 // Get the new insert position for the node we care about.
2781 FunctionNoProtoType *NewIP =
2782 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
2783 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2784 }
2785
2786 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
2787 FunctionNoProtoType *New = new (*this, TypeAlignment)
2788 FunctionNoProtoType(ResultTy, Canonical, newInfo);
2789 Types.push_back(New);
2790 FunctionNoProtoTypes.InsertNode(New, InsertPos);
2791 return QualType(New, 0);
2792 }
2793
2794 /// \brief Determine whether \p T is canonical as the result type of a function.
isCanonicalResultType(QualType T)2795 static bool isCanonicalResultType(QualType T) {
2796 return T.isCanonical() &&
2797 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2798 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2799 }
2800
2801 /// getFunctionType - Return a normal function type with a typed argument
2802 /// list. isVariadic indicates whether the argument list includes '...'.
2803 QualType
getFunctionType(QualType ResultTy,ArrayRef<QualType> ArgArray,const FunctionProtoType::ExtProtoInfo & EPI) const2804 ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
2805 const FunctionProtoType::ExtProtoInfo &EPI) const {
2806 size_t NumArgs = ArgArray.size();
2807
2808 // Unique functions, to guarantee there is only one function of a particular
2809 // structure.
2810 llvm::FoldingSetNodeID ID;
2811 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2812 *this);
2813
2814 void *InsertPos = 0;
2815 if (FunctionProtoType *FTP =
2816 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
2817 return QualType(FTP, 0);
2818
2819 // Determine whether the type being created is already canonical or not.
2820 bool isCanonical =
2821 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
2822 !EPI.HasTrailingReturn;
2823 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
2824 if (!ArgArray[i].isCanonicalAsParam())
2825 isCanonical = false;
2826
2827 // If this type isn't canonical, get the canonical version of it.
2828 // The exception spec is not part of the canonical type.
2829 QualType Canonical;
2830 if (!isCanonical) {
2831 SmallVector<QualType, 16> CanonicalArgs;
2832 CanonicalArgs.reserve(NumArgs);
2833 for (unsigned i = 0; i != NumArgs; ++i)
2834 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
2835
2836 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
2837 CanonicalEPI.HasTrailingReturn = false;
2838 CanonicalEPI.ExceptionSpecType = EST_None;
2839 CanonicalEPI.NumExceptions = 0;
2840
2841 // Result types do not have ARC lifetime qualifiers.
2842 QualType CanResultTy = getCanonicalType(ResultTy);
2843 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2844 Qualifiers Qs = CanResultTy.getQualifiers();
2845 Qs.removeObjCLifetime();
2846 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2847 }
2848
2849 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
2850
2851 // Get the new insert position for the node we care about.
2852 FunctionProtoType *NewIP =
2853 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
2854 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2855 }
2856
2857 // FunctionProtoType objects are allocated with extra bytes after
2858 // them for three variable size arrays at the end:
2859 // - parameter types
2860 // - exception types
2861 // - consumed-arguments flags
2862 // Instead of the exception types, there could be a noexcept
2863 // expression, or information used to resolve the exception
2864 // specification.
2865 size_t Size = sizeof(FunctionProtoType) +
2866 NumArgs * sizeof(QualType);
2867 if (EPI.ExceptionSpecType == EST_Dynamic) {
2868 Size += EPI.NumExceptions * sizeof(QualType);
2869 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
2870 Size += sizeof(Expr*);
2871 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
2872 Size += 2 * sizeof(FunctionDecl*);
2873 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2874 Size += sizeof(FunctionDecl*);
2875 }
2876 if (EPI.ConsumedArguments)
2877 Size += NumArgs * sizeof(bool);
2878
2879 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
2880 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2881 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
2882 Types.push_back(FTP);
2883 FunctionProtoTypes.InsertNode(FTP, InsertPos);
2884 return QualType(FTP, 0);
2885 }
2886
2887 #ifndef NDEBUG
NeedsInjectedClassNameType(const RecordDecl * D)2888 static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2889 if (!isa<CXXRecordDecl>(D)) return false;
2890 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2891 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2892 return true;
2893 if (RD->getDescribedClassTemplate() &&
2894 !isa<ClassTemplateSpecializationDecl>(RD))
2895 return true;
2896 return false;
2897 }
2898 #endif
2899
2900 /// getInjectedClassNameType - Return the unique reference to the
2901 /// injected class name type for the specified templated declaration.
getInjectedClassNameType(CXXRecordDecl * Decl,QualType TST) const2902 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
2903 QualType TST) const {
2904 assert(NeedsInjectedClassNameType(Decl));
2905 if (Decl->TypeForDecl) {
2906 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2907 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
2908 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2909 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2910 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2911 } else {
2912 Type *newType =
2913 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
2914 Decl->TypeForDecl = newType;
2915 Types.push_back(newType);
2916 }
2917 return QualType(Decl->TypeForDecl, 0);
2918 }
2919
2920 /// getTypeDeclType - Return the unique reference to the type for the
2921 /// specified type declaration.
getTypeDeclTypeSlow(const TypeDecl * Decl) const2922 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
2923 assert(Decl && "Passed null for Decl param");
2924 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
2925
2926 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
2927 return getTypedefType(Typedef);
2928
2929 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2930 "Template type parameter types are always available.");
2931
2932 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
2933 assert(Record->isFirstDecl() && "struct/union has previous declaration");
2934 assert(!NeedsInjectedClassNameType(Record));
2935 return getRecordType(Record);
2936 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
2937 assert(Enum->isFirstDecl() && "enum has previous declaration");
2938 return getEnumType(Enum);
2939 } else if (const UnresolvedUsingTypenameDecl *Using =
2940 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
2941 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2942 Decl->TypeForDecl = newType;
2943 Types.push_back(newType);
2944 } else
2945 llvm_unreachable("TypeDecl without a type?");
2946
2947 return QualType(Decl->TypeForDecl, 0);
2948 }
2949
2950 /// getTypedefType - Return the unique reference to the type for the
2951 /// specified typedef name decl.
2952 QualType
getTypedefType(const TypedefNameDecl * Decl,QualType Canonical) const2953 ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2954 QualType Canonical) const {
2955 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2956
2957 if (Canonical.isNull())
2958 Canonical = getCanonicalType(Decl->getUnderlyingType());
2959 TypedefType *newType = new(*this, TypeAlignment)
2960 TypedefType(Type::Typedef, Decl, Canonical);
2961 Decl->TypeForDecl = newType;
2962 Types.push_back(newType);
2963 return QualType(newType, 0);
2964 }
2965
getRecordType(const RecordDecl * Decl) const2966 QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
2967 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2968
2969 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
2970 if (PrevDecl->TypeForDecl)
2971 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2972
2973 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2974 Decl->TypeForDecl = newType;
2975 Types.push_back(newType);
2976 return QualType(newType, 0);
2977 }
2978
getEnumType(const EnumDecl * Decl) const2979 QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
2980 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2981
2982 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
2983 if (PrevDecl->TypeForDecl)
2984 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2985
2986 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2987 Decl->TypeForDecl = newType;
2988 Types.push_back(newType);
2989 return QualType(newType, 0);
2990 }
2991
getAttributedType(AttributedType::Kind attrKind,QualType modifiedType,QualType equivalentType)2992 QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2993 QualType modifiedType,
2994 QualType equivalentType) {
2995 llvm::FoldingSetNodeID id;
2996 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2997
2998 void *insertPos = 0;
2999 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3000 if (type) return QualType(type, 0);
3001
3002 QualType canon = getCanonicalType(equivalentType);
3003 type = new (*this, TypeAlignment)
3004 AttributedType(canon, attrKind, modifiedType, equivalentType);
3005
3006 Types.push_back(type);
3007 AttributedTypes.InsertNode(type, insertPos);
3008
3009 return QualType(type, 0);
3010 }
3011
3012
3013 /// \brief Retrieve a substitution-result type.
3014 QualType
getSubstTemplateTypeParmType(const TemplateTypeParmType * Parm,QualType Replacement) const3015 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
3016 QualType Replacement) const {
3017 assert(Replacement.isCanonical()
3018 && "replacement types must always be canonical");
3019
3020 llvm::FoldingSetNodeID ID;
3021 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3022 void *InsertPos = 0;
3023 SubstTemplateTypeParmType *SubstParm
3024 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3025
3026 if (!SubstParm) {
3027 SubstParm = new (*this, TypeAlignment)
3028 SubstTemplateTypeParmType(Parm, Replacement);
3029 Types.push_back(SubstParm);
3030 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3031 }
3032
3033 return QualType(SubstParm, 0);
3034 }
3035
3036 /// \brief Retrieve a
getSubstTemplateTypeParmPackType(const TemplateTypeParmType * Parm,const TemplateArgument & ArgPack)3037 QualType ASTContext::getSubstTemplateTypeParmPackType(
3038 const TemplateTypeParmType *Parm,
3039 const TemplateArgument &ArgPack) {
3040 #ifndef NDEBUG
3041 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
3042 PEnd = ArgPack.pack_end();
3043 P != PEnd; ++P) {
3044 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3045 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
3046 }
3047 #endif
3048
3049 llvm::FoldingSetNodeID ID;
3050 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3051 void *InsertPos = 0;
3052 if (SubstTemplateTypeParmPackType *SubstParm
3053 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3054 return QualType(SubstParm, 0);
3055
3056 QualType Canon;
3057 if (!Parm->isCanonicalUnqualified()) {
3058 Canon = getCanonicalType(QualType(Parm, 0));
3059 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3060 ArgPack);
3061 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3062 }
3063
3064 SubstTemplateTypeParmPackType *SubstParm
3065 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3066 ArgPack);
3067 Types.push_back(SubstParm);
3068 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3069 return QualType(SubstParm, 0);
3070 }
3071
3072 /// \brief Retrieve the template type parameter type for a template
3073 /// parameter or parameter pack with the given depth, index, and (optionally)
3074 /// name.
getTemplateTypeParmType(unsigned Depth,unsigned Index,bool ParameterPack,TemplateTypeParmDecl * TTPDecl) const3075 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
3076 bool ParameterPack,
3077 TemplateTypeParmDecl *TTPDecl) const {
3078 llvm::FoldingSetNodeID ID;
3079 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
3080 void *InsertPos = 0;
3081 TemplateTypeParmType *TypeParm
3082 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3083
3084 if (TypeParm)
3085 return QualType(TypeParm, 0);
3086
3087 if (TTPDecl) {
3088 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
3089 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
3090
3091 TemplateTypeParmType *TypeCheck
3092 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3093 assert(!TypeCheck && "Template type parameter canonical type broken");
3094 (void)TypeCheck;
3095 } else
3096 TypeParm = new (*this, TypeAlignment)
3097 TemplateTypeParmType(Depth, Index, ParameterPack);
3098
3099 Types.push_back(TypeParm);
3100 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3101
3102 return QualType(TypeParm, 0);
3103 }
3104
3105 TypeSourceInfo *
getTemplateSpecializationTypeInfo(TemplateName Name,SourceLocation NameLoc,const TemplateArgumentListInfo & Args,QualType Underlying) const3106 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3107 SourceLocation NameLoc,
3108 const TemplateArgumentListInfo &Args,
3109 QualType Underlying) const {
3110 assert(!Name.getAsDependentTemplateName() &&
3111 "No dependent template names here!");
3112 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
3113
3114 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
3115 TemplateSpecializationTypeLoc TL =
3116 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
3117 TL.setTemplateKeywordLoc(SourceLocation());
3118 TL.setTemplateNameLoc(NameLoc);
3119 TL.setLAngleLoc(Args.getLAngleLoc());
3120 TL.setRAngleLoc(Args.getRAngleLoc());
3121 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3122 TL.setArgLocInfo(i, Args[i].getLocInfo());
3123 return DI;
3124 }
3125
3126 QualType
getTemplateSpecializationType(TemplateName Template,const TemplateArgumentListInfo & Args,QualType Underlying) const3127 ASTContext::getTemplateSpecializationType(TemplateName Template,
3128 const TemplateArgumentListInfo &Args,
3129 QualType Underlying) const {
3130 assert(!Template.getAsDependentTemplateName() &&
3131 "No dependent template names here!");
3132
3133 unsigned NumArgs = Args.size();
3134
3135 SmallVector<TemplateArgument, 4> ArgVec;
3136 ArgVec.reserve(NumArgs);
3137 for (unsigned i = 0; i != NumArgs; ++i)
3138 ArgVec.push_back(Args[i].getArgument());
3139
3140 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
3141 Underlying);
3142 }
3143
3144 #ifndef NDEBUG
hasAnyPackExpansions(const TemplateArgument * Args,unsigned NumArgs)3145 static bool hasAnyPackExpansions(const TemplateArgument *Args,
3146 unsigned NumArgs) {
3147 for (unsigned I = 0; I != NumArgs; ++I)
3148 if (Args[I].isPackExpansion())
3149 return true;
3150
3151 return true;
3152 }
3153 #endif
3154
3155 QualType
getTemplateSpecializationType(TemplateName Template,const TemplateArgument * Args,unsigned NumArgs,QualType Underlying) const3156 ASTContext::getTemplateSpecializationType(TemplateName Template,
3157 const TemplateArgument *Args,
3158 unsigned NumArgs,
3159 QualType Underlying) const {
3160 assert(!Template.getAsDependentTemplateName() &&
3161 "No dependent template names here!");
3162 // Look through qualified template names.
3163 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3164 Template = TemplateName(QTN->getTemplateDecl());
3165
3166 bool IsTypeAlias =
3167 Template.getAsTemplateDecl() &&
3168 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
3169 QualType CanonType;
3170 if (!Underlying.isNull())
3171 CanonType = getCanonicalType(Underlying);
3172 else {
3173 // We can get here with an alias template when the specialization contains
3174 // a pack expansion that does not match up with a parameter pack.
3175 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3176 "Caller must compute aliased type");
3177 IsTypeAlias = false;
3178 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3179 NumArgs);
3180 }
3181
3182 // Allocate the (non-canonical) template specialization type, but don't
3183 // try to unique it: these types typically have location information that
3184 // we don't unique and don't want to lose.
3185 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3186 sizeof(TemplateArgument) * NumArgs +
3187 (IsTypeAlias? sizeof(QualType) : 0),
3188 TypeAlignment);
3189 TemplateSpecializationType *Spec
3190 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3191 IsTypeAlias ? Underlying : QualType());
3192
3193 Types.push_back(Spec);
3194 return QualType(Spec, 0);
3195 }
3196
3197 QualType
getCanonicalTemplateSpecializationType(TemplateName Template,const TemplateArgument * Args,unsigned NumArgs) const3198 ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3199 const TemplateArgument *Args,
3200 unsigned NumArgs) const {
3201 assert(!Template.getAsDependentTemplateName() &&
3202 "No dependent template names here!");
3203
3204 // Look through qualified template names.
3205 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3206 Template = TemplateName(QTN->getTemplateDecl());
3207
3208 // Build the canonical template specialization type.
3209 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
3210 SmallVector<TemplateArgument, 4> CanonArgs;
3211 CanonArgs.reserve(NumArgs);
3212 for (unsigned I = 0; I != NumArgs; ++I)
3213 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3214
3215 // Determine whether this canonical template specialization type already
3216 // exists.
3217 llvm::FoldingSetNodeID ID;
3218 TemplateSpecializationType::Profile(ID, CanonTemplate,
3219 CanonArgs.data(), NumArgs, *this);
3220
3221 void *InsertPos = 0;
3222 TemplateSpecializationType *Spec
3223 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3224
3225 if (!Spec) {
3226 // Allocate a new canonical template specialization type.
3227 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3228 sizeof(TemplateArgument) * NumArgs),
3229 TypeAlignment);
3230 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3231 CanonArgs.data(), NumArgs,
3232 QualType(), QualType());
3233 Types.push_back(Spec);
3234 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3235 }
3236
3237 assert(Spec->isDependentType() &&
3238 "Non-dependent template-id type must have a canonical type");
3239 return QualType(Spec, 0);
3240 }
3241
3242 QualType
getElaboratedType(ElaboratedTypeKeyword Keyword,NestedNameSpecifier * NNS,QualType NamedType) const3243 ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3244 NestedNameSpecifier *NNS,
3245 QualType NamedType) const {
3246 llvm::FoldingSetNodeID ID;
3247 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
3248
3249 void *InsertPos = 0;
3250 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3251 if (T)
3252 return QualType(T, 0);
3253
3254 QualType Canon = NamedType;
3255 if (!Canon.isCanonical()) {
3256 Canon = getCanonicalType(NamedType);
3257 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3258 assert(!CheckT && "Elaborated canonical type broken");
3259 (void)CheckT;
3260 }
3261
3262 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
3263 Types.push_back(T);
3264 ElaboratedTypes.InsertNode(T, InsertPos);
3265 return QualType(T, 0);
3266 }
3267
3268 QualType
getParenType(QualType InnerType) const3269 ASTContext::getParenType(QualType InnerType) const {
3270 llvm::FoldingSetNodeID ID;
3271 ParenType::Profile(ID, InnerType);
3272
3273 void *InsertPos = 0;
3274 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3275 if (T)
3276 return QualType(T, 0);
3277
3278 QualType Canon = InnerType;
3279 if (!Canon.isCanonical()) {
3280 Canon = getCanonicalType(InnerType);
3281 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3282 assert(!CheckT && "Paren canonical type broken");
3283 (void)CheckT;
3284 }
3285
3286 T = new (*this) ParenType(InnerType, Canon);
3287 Types.push_back(T);
3288 ParenTypes.InsertNode(T, InsertPos);
3289 return QualType(T, 0);
3290 }
3291
getDependentNameType(ElaboratedTypeKeyword Keyword,NestedNameSpecifier * NNS,const IdentifierInfo * Name,QualType Canon) const3292 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3293 NestedNameSpecifier *NNS,
3294 const IdentifierInfo *Name,
3295 QualType Canon) const {
3296 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3297
3298 if (Canon.isNull()) {
3299 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3300 ElaboratedTypeKeyword CanonKeyword = Keyword;
3301 if (Keyword == ETK_None)
3302 CanonKeyword = ETK_Typename;
3303
3304 if (CanonNNS != NNS || CanonKeyword != Keyword)
3305 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
3306 }
3307
3308 llvm::FoldingSetNodeID ID;
3309 DependentNameType::Profile(ID, Keyword, NNS, Name);
3310
3311 void *InsertPos = 0;
3312 DependentNameType *T
3313 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
3314 if (T)
3315 return QualType(T, 0);
3316
3317 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
3318 Types.push_back(T);
3319 DependentNameTypes.InsertNode(T, InsertPos);
3320 return QualType(T, 0);
3321 }
3322
3323 QualType
getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,NestedNameSpecifier * NNS,const IdentifierInfo * Name,const TemplateArgumentListInfo & Args) const3324 ASTContext::getDependentTemplateSpecializationType(
3325 ElaboratedTypeKeyword Keyword,
3326 NestedNameSpecifier *NNS,
3327 const IdentifierInfo *Name,
3328 const TemplateArgumentListInfo &Args) const {
3329 // TODO: avoid this copy
3330 SmallVector<TemplateArgument, 16> ArgCopy;
3331 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3332 ArgCopy.push_back(Args[I].getArgument());
3333 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3334 ArgCopy.size(),
3335 ArgCopy.data());
3336 }
3337
3338 QualType
getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,NestedNameSpecifier * NNS,const IdentifierInfo * Name,unsigned NumArgs,const TemplateArgument * Args) const3339 ASTContext::getDependentTemplateSpecializationType(
3340 ElaboratedTypeKeyword Keyword,
3341 NestedNameSpecifier *NNS,
3342 const IdentifierInfo *Name,
3343 unsigned NumArgs,
3344 const TemplateArgument *Args) const {
3345 assert((!NNS || NNS->isDependent()) &&
3346 "nested-name-specifier must be dependent");
3347
3348 llvm::FoldingSetNodeID ID;
3349 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3350 Name, NumArgs, Args);
3351
3352 void *InsertPos = 0;
3353 DependentTemplateSpecializationType *T
3354 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3355 if (T)
3356 return QualType(T, 0);
3357
3358 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3359
3360 ElaboratedTypeKeyword CanonKeyword = Keyword;
3361 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3362
3363 bool AnyNonCanonArgs = false;
3364 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
3365 for (unsigned I = 0; I != NumArgs; ++I) {
3366 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3367 if (!CanonArgs[I].structurallyEquals(Args[I]))
3368 AnyNonCanonArgs = true;
3369 }
3370
3371 QualType Canon;
3372 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3373 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3374 Name, NumArgs,
3375 CanonArgs.data());
3376
3377 // Find the insert position again.
3378 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3379 }
3380
3381 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3382 sizeof(TemplateArgument) * NumArgs),
3383 TypeAlignment);
3384 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
3385 Name, NumArgs, Args, Canon);
3386 Types.push_back(T);
3387 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
3388 return QualType(T, 0);
3389 }
3390
getPackExpansionType(QualType Pattern,Optional<unsigned> NumExpansions)3391 QualType ASTContext::getPackExpansionType(QualType Pattern,
3392 Optional<unsigned> NumExpansions) {
3393 llvm::FoldingSetNodeID ID;
3394 PackExpansionType::Profile(ID, Pattern, NumExpansions);
3395
3396 assert(Pattern->containsUnexpandedParameterPack() &&
3397 "Pack expansions must expand one or more parameter packs");
3398 void *InsertPos = 0;
3399 PackExpansionType *T
3400 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3401 if (T)
3402 return QualType(T, 0);
3403
3404 QualType Canon;
3405 if (!Pattern.isCanonical()) {
3406 Canon = getCanonicalType(Pattern);
3407 // The canonical type might not contain an unexpanded parameter pack, if it
3408 // contains an alias template specialization which ignores one of its
3409 // parameters.
3410 if (Canon->containsUnexpandedParameterPack()) {
3411 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
3412
3413 // Find the insert position again, in case we inserted an element into
3414 // PackExpansionTypes and invalidated our insert position.
3415 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3416 }
3417 }
3418
3419 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
3420 Types.push_back(T);
3421 PackExpansionTypes.InsertNode(T, InsertPos);
3422 return QualType(T, 0);
3423 }
3424
3425 /// CmpProtocolNames - Comparison predicate for sorting protocols
3426 /// alphabetically.
CmpProtocolNames(const ObjCProtocolDecl * LHS,const ObjCProtocolDecl * RHS)3427 static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3428 const ObjCProtocolDecl *RHS) {
3429 return LHS->getDeclName() < RHS->getDeclName();
3430 }
3431
areSortedAndUniqued(ObjCProtocolDecl * const * Protocols,unsigned NumProtocols)3432 static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
3433 unsigned NumProtocols) {
3434 if (NumProtocols == 0) return true;
3435
3436 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3437 return false;
3438
3439 for (unsigned i = 1; i != NumProtocols; ++i)
3440 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3441 Protocols[i]->getCanonicalDecl() != Protocols[i])
3442 return false;
3443 return true;
3444 }
3445
SortAndUniqueProtocols(ObjCProtocolDecl ** Protocols,unsigned & NumProtocols)3446 static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
3447 unsigned &NumProtocols) {
3448 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
3449
3450 // Sort protocols, keyed by name.
3451 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3452
3453 // Canonicalize.
3454 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3455 Protocols[I] = Protocols[I]->getCanonicalDecl();
3456
3457 // Remove duplicates.
3458 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3459 NumProtocols = ProtocolsEnd-Protocols;
3460 }
3461
getObjCObjectType(QualType BaseType,ObjCProtocolDecl * const * Protocols,unsigned NumProtocols) const3462 QualType ASTContext::getObjCObjectType(QualType BaseType,
3463 ObjCProtocolDecl * const *Protocols,
3464 unsigned NumProtocols) const {
3465 // If the base type is an interface and there aren't any protocols
3466 // to add, then the interface type will do just fine.
3467 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3468 return BaseType;
3469
3470 // Look in the folding set for an existing type.
3471 llvm::FoldingSetNodeID ID;
3472 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
3473 void *InsertPos = 0;
3474 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3475 return QualType(QT, 0);
3476
3477 // Build the canonical type, which has the canonical base type and
3478 // a sorted-and-uniqued list of protocols.
3479 QualType Canonical;
3480 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3481 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3482 if (!ProtocolsSorted) {
3483 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
3484 Protocols + NumProtocols);
3485 unsigned UniqueCount = NumProtocols;
3486
3487 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
3488 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3489 &Sorted[0], UniqueCount);
3490 } else {
3491 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3492 Protocols, NumProtocols);
3493 }
3494
3495 // Regenerate InsertPos.
3496 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3497 }
3498
3499 unsigned Size = sizeof(ObjCObjectTypeImpl);
3500 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3501 void *Mem = Allocate(Size, TypeAlignment);
3502 ObjCObjectTypeImpl *T =
3503 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3504
3505 Types.push_back(T);
3506 ObjCObjectTypes.InsertNode(T, InsertPos);
3507 return QualType(T, 0);
3508 }
3509
3510 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3511 /// the given object type.
getObjCObjectPointerType(QualType ObjectT) const3512 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
3513 llvm::FoldingSetNodeID ID;
3514 ObjCObjectPointerType::Profile(ID, ObjectT);
3515
3516 void *InsertPos = 0;
3517 if (ObjCObjectPointerType *QT =
3518 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3519 return QualType(QT, 0);
3520
3521 // Find the canonical object type.
3522 QualType Canonical;
3523 if (!ObjectT.isCanonical()) {
3524 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3525
3526 // Regenerate InsertPos.
3527 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3528 }
3529
3530 // No match.
3531 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3532 ObjCObjectPointerType *QType =
3533 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
3534
3535 Types.push_back(QType);
3536 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
3537 return QualType(QType, 0);
3538 }
3539
3540 /// getObjCInterfaceType - Return the unique reference to the type for the
3541 /// specified ObjC interface decl. The list of protocols is optional.
getObjCInterfaceType(const ObjCInterfaceDecl * Decl,ObjCInterfaceDecl * PrevDecl) const3542 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3543 ObjCInterfaceDecl *PrevDecl) const {
3544 if (Decl->TypeForDecl)
3545 return QualType(Decl->TypeForDecl, 0);
3546
3547 if (PrevDecl) {
3548 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3549 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3550 return QualType(PrevDecl->TypeForDecl, 0);
3551 }
3552
3553 // Prefer the definition, if there is one.
3554 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3555 Decl = Def;
3556
3557 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3558 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3559 Decl->TypeForDecl = T;
3560 Types.push_back(T);
3561 return QualType(T, 0);
3562 }
3563
3564 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3565 /// TypeOfExprType AST's (since expression's are never shared). For example,
3566 /// multiple declarations that refer to "typeof(x)" all contain different
3567 /// DeclRefExpr's. This doesn't effect the type checker, since it operates
3568 /// on canonical type's (which are always unique).
getTypeOfExprType(Expr * tofExpr) const3569 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
3570 TypeOfExprType *toe;
3571 if (tofExpr->isTypeDependent()) {
3572 llvm::FoldingSetNodeID ID;
3573 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
3574
3575 void *InsertPos = 0;
3576 DependentTypeOfExprType *Canon
3577 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3578 if (Canon) {
3579 // We already have a "canonical" version of an identical, dependent
3580 // typeof(expr) type. Use that as our canonical type.
3581 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
3582 QualType((TypeOfExprType*)Canon, 0));
3583 } else {
3584 // Build a new, canonical typeof(expr) type.
3585 Canon
3586 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
3587 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3588 toe = Canon;
3589 }
3590 } else {
3591 QualType Canonical = getCanonicalType(tofExpr->getType());
3592 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
3593 }
3594 Types.push_back(toe);
3595 return QualType(toe, 0);
3596 }
3597
3598 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3599 /// TypeOfType AST's. The only motivation to unique these nodes would be
3600 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
3601 /// an issue. This doesn't effect the type checker, since it operates
3602 /// on canonical type's (which are always unique).
getTypeOfType(QualType tofType) const3603 QualType ASTContext::getTypeOfType(QualType tofType) const {
3604 QualType Canonical = getCanonicalType(tofType);
3605 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
3606 Types.push_back(tot);
3607 return QualType(tot, 0);
3608 }
3609
3610
3611 /// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3612 /// DecltypeType AST's. The only motivation to unique these nodes would be
3613 /// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
3614 /// an issue. This doesn't effect the type checker, since it operates
3615 /// on canonical types (which are always unique).
getDecltypeType(Expr * e,QualType UnderlyingType) const3616 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
3617 DecltypeType *dt;
3618
3619 // C++0x [temp.type]p2:
3620 // If an expression e involves a template parameter, decltype(e) denotes a
3621 // unique dependent type. Two such decltype-specifiers refer to the same
3622 // type only if their expressions are equivalent (14.5.6.1).
3623 if (e->isInstantiationDependent()) {
3624 llvm::FoldingSetNodeID ID;
3625 DependentDecltypeType::Profile(ID, *this, e);
3626
3627 void *InsertPos = 0;
3628 DependentDecltypeType *Canon
3629 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3630 if (Canon) {
3631 // We already have a "canonical" version of an equivalent, dependent
3632 // decltype type. Use that as our canonical type.
3633 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3634 QualType((DecltypeType*)Canon, 0));
3635 } else {
3636 // Build a new, canonical typeof(expr) type.
3637 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
3638 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3639 dt = Canon;
3640 }
3641 } else {
3642 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3643 getCanonicalType(UnderlyingType));
3644 }
3645 Types.push_back(dt);
3646 return QualType(dt, 0);
3647 }
3648
3649 /// getUnaryTransformationType - We don't unique these, since the memory
3650 /// savings are minimal and these are rare.
getUnaryTransformType(QualType BaseType,QualType UnderlyingType,UnaryTransformType::UTTKind Kind) const3651 QualType ASTContext::getUnaryTransformType(QualType BaseType,
3652 QualType UnderlyingType,
3653 UnaryTransformType::UTTKind Kind)
3654 const {
3655 UnaryTransformType *Ty =
3656 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3657 Kind,
3658 UnderlyingType->isDependentType() ?
3659 QualType() : getCanonicalType(UnderlyingType));
3660 Types.push_back(Ty);
3661 return QualType(Ty, 0);
3662 }
3663
3664 /// getAutoType - Return the uniqued reference to the 'auto' type which has been
3665 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3666 /// canonical deduced-but-dependent 'auto' type.
getAutoType(QualType DeducedType,bool IsDecltypeAuto,bool IsDependent) const3667 QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
3668 bool IsDependent) const {
3669 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
3670 return getAutoDeductType();
3671
3672 // Look in the folding set for an existing type.
3673 void *InsertPos = 0;
3674 llvm::FoldingSetNodeID ID;
3675 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
3676 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3677 return QualType(AT, 0);
3678
3679 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
3680 IsDecltypeAuto,
3681 IsDependent);
3682 Types.push_back(AT);
3683 if (InsertPos)
3684 AutoTypes.InsertNode(AT, InsertPos);
3685 return QualType(AT, 0);
3686 }
3687
3688 /// getAtomicType - Return the uniqued reference to the atomic type for
3689 /// the given value type.
getAtomicType(QualType T) const3690 QualType ASTContext::getAtomicType(QualType T) const {
3691 // Unique pointers, to guarantee there is only one pointer of a particular
3692 // structure.
3693 llvm::FoldingSetNodeID ID;
3694 AtomicType::Profile(ID, T);
3695
3696 void *InsertPos = 0;
3697 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3698 return QualType(AT, 0);
3699
3700 // If the atomic value type isn't canonical, this won't be a canonical type
3701 // either, so fill in the canonical type field.
3702 QualType Canonical;
3703 if (!T.isCanonical()) {
3704 Canonical = getAtomicType(getCanonicalType(T));
3705
3706 // Get the new insert position for the node we care about.
3707 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3708 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3709 }
3710 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3711 Types.push_back(New);
3712 AtomicTypes.InsertNode(New, InsertPos);
3713 return QualType(New, 0);
3714 }
3715
3716 /// getAutoDeductType - Get type pattern for deducing against 'auto'.
getAutoDeductType() const3717 QualType ASTContext::getAutoDeductType() const {
3718 if (AutoDeductTy.isNull())
3719 AutoDeductTy = QualType(
3720 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
3721 /*dependent*/false),
3722 0);
3723 return AutoDeductTy;
3724 }
3725
3726 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
getAutoRRefDeductType() const3727 QualType ASTContext::getAutoRRefDeductType() const {
3728 if (AutoRRefDeductTy.isNull())
3729 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3730 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3731 return AutoRRefDeductTy;
3732 }
3733
3734 /// getTagDeclType - Return the unique reference to the type for the
3735 /// specified TagDecl (struct/union/class/enum) decl.
getTagDeclType(const TagDecl * Decl) const3736 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
3737 assert (Decl);
3738 // FIXME: What is the design on getTagDeclType when it requires casting
3739 // away const? mutable?
3740 return getTypeDeclType(const_cast<TagDecl*>(Decl));
3741 }
3742
3743 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3744 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3745 /// needs to agree with the definition in <stddef.h>.
getSizeType() const3746 CanQualType ASTContext::getSizeType() const {
3747 return getFromTargetType(Target->getSizeType());
3748 }
3749
3750 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
getIntMaxType() const3751 CanQualType ASTContext::getIntMaxType() const {
3752 return getFromTargetType(Target->getIntMaxType());
3753 }
3754
3755 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
getUIntMaxType() const3756 CanQualType ASTContext::getUIntMaxType() const {
3757 return getFromTargetType(Target->getUIntMaxType());
3758 }
3759
3760 /// getSignedWCharType - Return the type of "signed wchar_t".
3761 /// Used when in C++, as a GCC extension.
getSignedWCharType() const3762 QualType ASTContext::getSignedWCharType() const {
3763 // FIXME: derive from "Target" ?
3764 return WCharTy;
3765 }
3766
3767 /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3768 /// Used when in C++, as a GCC extension.
getUnsignedWCharType() const3769 QualType ASTContext::getUnsignedWCharType() const {
3770 // FIXME: derive from "Target" ?
3771 return UnsignedIntTy;
3772 }
3773
getIntPtrType() const3774 QualType ASTContext::getIntPtrType() const {
3775 return getFromTargetType(Target->getIntPtrType());
3776 }
3777
getUIntPtrType() const3778 QualType ASTContext::getUIntPtrType() const {
3779 return getCorrespondingUnsignedType(getIntPtrType());
3780 }
3781
3782 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
3783 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
getPointerDiffType() const3784 QualType ASTContext::getPointerDiffType() const {
3785 return getFromTargetType(Target->getPtrDiffType(0));
3786 }
3787
3788 /// \brief Return the unique type for "pid_t" defined in
3789 /// <sys/types.h>. We need this to compute the correct type for vfork().
getProcessIDType() const3790 QualType ASTContext::getProcessIDType() const {
3791 return getFromTargetType(Target->getProcessIDType());
3792 }
3793
3794 //===----------------------------------------------------------------------===//
3795 // Type Operators
3796 //===----------------------------------------------------------------------===//
3797
getCanonicalParamType(QualType T) const3798 CanQualType ASTContext::getCanonicalParamType(QualType T) const {
3799 // Push qualifiers into arrays, and then discard any remaining
3800 // qualifiers.
3801 T = getCanonicalType(T);
3802 T = getVariableArrayDecayedType(T);
3803 const Type *Ty = T.getTypePtr();
3804 QualType Result;
3805 if (isa<ArrayType>(Ty)) {
3806 Result = getArrayDecayedType(QualType(Ty,0));
3807 } else if (isa<FunctionType>(Ty)) {
3808 Result = getPointerType(QualType(Ty, 0));
3809 } else {
3810 Result = QualType(Ty, 0);
3811 }
3812
3813 return CanQualType::CreateUnsafe(Result);
3814 }
3815
getUnqualifiedArrayType(QualType type,Qualifiers & quals)3816 QualType ASTContext::getUnqualifiedArrayType(QualType type,
3817 Qualifiers &quals) {
3818 SplitQualType splitType = type.getSplitUnqualifiedType();
3819
3820 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3821 // the unqualified desugared type and then drops it on the floor.
3822 // We then have to strip that sugar back off with
3823 // getUnqualifiedDesugaredType(), which is silly.
3824 const ArrayType *AT =
3825 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
3826
3827 // If we don't have an array, just use the results in splitType.
3828 if (!AT) {
3829 quals = splitType.Quals;
3830 return QualType(splitType.Ty, 0);
3831 }
3832
3833 // Otherwise, recurse on the array's element type.
3834 QualType elementType = AT->getElementType();
3835 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3836
3837 // If that didn't change the element type, AT has no qualifiers, so we
3838 // can just use the results in splitType.
3839 if (elementType == unqualElementType) {
3840 assert(quals.empty()); // from the recursive call
3841 quals = splitType.Quals;
3842 return QualType(splitType.Ty, 0);
3843 }
3844
3845 // Otherwise, add in the qualifiers from the outermost type, then
3846 // build the type back up.
3847 quals.addConsistentQualifiers(splitType.Quals);
3848
3849 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
3850 return getConstantArrayType(unqualElementType, CAT->getSize(),
3851 CAT->getSizeModifier(), 0);
3852 }
3853
3854 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
3855 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
3856 }
3857
3858 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
3859 return getVariableArrayType(unqualElementType,
3860 VAT->getSizeExpr(),
3861 VAT->getSizeModifier(),
3862 VAT->getIndexTypeCVRQualifiers(),
3863 VAT->getBracketsRange());
3864 }
3865
3866 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
3867 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
3868 DSAT->getSizeModifier(), 0,
3869 SourceRange());
3870 }
3871
3872 /// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3873 /// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3874 /// they point to and return true. If T1 and T2 aren't pointer types
3875 /// or pointer-to-member types, or if they are not similar at this
3876 /// level, returns false and leaves T1 and T2 unchanged. Top-level
3877 /// qualifiers on T1 and T2 are ignored. This function will typically
3878 /// be called in a loop that successively "unwraps" pointer and
3879 /// pointer-to-member types to compare them at each level.
UnwrapSimilarPointerTypes(QualType & T1,QualType & T2)3880 bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3881 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3882 *T2PtrType = T2->getAs<PointerType>();
3883 if (T1PtrType && T2PtrType) {
3884 T1 = T1PtrType->getPointeeType();
3885 T2 = T2PtrType->getPointeeType();
3886 return true;
3887 }
3888
3889 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3890 *T2MPType = T2->getAs<MemberPointerType>();
3891 if (T1MPType && T2MPType &&
3892 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3893 QualType(T2MPType->getClass(), 0))) {
3894 T1 = T1MPType->getPointeeType();
3895 T2 = T2MPType->getPointeeType();
3896 return true;
3897 }
3898
3899 if (getLangOpts().ObjC1) {
3900 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3901 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3902 if (T1OPType && T2OPType) {
3903 T1 = T1OPType->getPointeeType();
3904 T2 = T2OPType->getPointeeType();
3905 return true;
3906 }
3907 }
3908
3909 // FIXME: Block pointers, too?
3910
3911 return false;
3912 }
3913
3914 DeclarationNameInfo
getNameForTemplate(TemplateName Name,SourceLocation NameLoc) const3915 ASTContext::getNameForTemplate(TemplateName Name,
3916 SourceLocation NameLoc) const {
3917 switch (Name.getKind()) {
3918 case TemplateName::QualifiedTemplate:
3919 case TemplateName::Template:
3920 // DNInfo work in progress: CHECKME: what about DNLoc?
3921 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3922 NameLoc);
3923
3924 case TemplateName::OverloadedTemplate: {
3925 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3926 // DNInfo work in progress: CHECKME: what about DNLoc?
3927 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3928 }
3929
3930 case TemplateName::DependentTemplate: {
3931 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3932 DeclarationName DName;
3933 if (DTN->isIdentifier()) {
3934 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3935 return DeclarationNameInfo(DName, NameLoc);
3936 } else {
3937 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3938 // DNInfo work in progress: FIXME: source locations?
3939 DeclarationNameLoc DNLoc;
3940 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3941 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3942 return DeclarationNameInfo(DName, NameLoc, DNLoc);
3943 }
3944 }
3945
3946 case TemplateName::SubstTemplateTemplateParm: {
3947 SubstTemplateTemplateParmStorage *subst
3948 = Name.getAsSubstTemplateTemplateParm();
3949 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3950 NameLoc);
3951 }
3952
3953 case TemplateName::SubstTemplateTemplateParmPack: {
3954 SubstTemplateTemplateParmPackStorage *subst
3955 = Name.getAsSubstTemplateTemplateParmPack();
3956 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3957 NameLoc);
3958 }
3959 }
3960
3961 llvm_unreachable("bad template name kind!");
3962 }
3963
getCanonicalTemplateName(TemplateName Name) const3964 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
3965 switch (Name.getKind()) {
3966 case TemplateName::QualifiedTemplate:
3967 case TemplateName::Template: {
3968 TemplateDecl *Template = Name.getAsTemplateDecl();
3969 if (TemplateTemplateParmDecl *TTP
3970 = dyn_cast<TemplateTemplateParmDecl>(Template))
3971 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3972
3973 // The canonical template name is the canonical template declaration.
3974 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
3975 }
3976
3977 case TemplateName::OverloadedTemplate:
3978 llvm_unreachable("cannot canonicalize overloaded template");
3979
3980 case TemplateName::DependentTemplate: {
3981 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3982 assert(DTN && "Non-dependent template names must refer to template decls.");
3983 return DTN->CanonicalTemplateName;
3984 }
3985
3986 case TemplateName::SubstTemplateTemplateParm: {
3987 SubstTemplateTemplateParmStorage *subst
3988 = Name.getAsSubstTemplateTemplateParm();
3989 return getCanonicalTemplateName(subst->getReplacement());
3990 }
3991
3992 case TemplateName::SubstTemplateTemplateParmPack: {
3993 SubstTemplateTemplateParmPackStorage *subst
3994 = Name.getAsSubstTemplateTemplateParmPack();
3995 TemplateTemplateParmDecl *canonParameter
3996 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3997 TemplateArgument canonArgPack
3998 = getCanonicalTemplateArgument(subst->getArgumentPack());
3999 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4000 }
4001 }
4002
4003 llvm_unreachable("bad template name!");
4004 }
4005
hasSameTemplateName(TemplateName X,TemplateName Y)4006 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4007 X = getCanonicalTemplateName(X);
4008 Y = getCanonicalTemplateName(Y);
4009 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4010 }
4011
4012 TemplateArgument
getCanonicalTemplateArgument(const TemplateArgument & Arg) const4013 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
4014 switch (Arg.getKind()) {
4015 case TemplateArgument::Null:
4016 return Arg;
4017
4018 case TemplateArgument::Expression:
4019 return Arg;
4020
4021 case TemplateArgument::Declaration: {
4022 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4023 return TemplateArgument(D, Arg.isDeclForReferenceParam());
4024 }
4025
4026 case TemplateArgument::NullPtr:
4027 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4028 /*isNullPtr*/true);
4029
4030 case TemplateArgument::Template:
4031 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
4032
4033 case TemplateArgument::TemplateExpansion:
4034 return TemplateArgument(getCanonicalTemplateName(
4035 Arg.getAsTemplateOrTemplatePattern()),
4036 Arg.getNumTemplateExpansions());
4037
4038 case TemplateArgument::Integral:
4039 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
4040
4041 case TemplateArgument::Type:
4042 return TemplateArgument(getCanonicalType(Arg.getAsType()));
4043
4044 case TemplateArgument::Pack: {
4045 if (Arg.pack_size() == 0)
4046 return Arg;
4047
4048 TemplateArgument *CanonArgs
4049 = new (*this) TemplateArgument[Arg.pack_size()];
4050 unsigned Idx = 0;
4051 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
4052 AEnd = Arg.pack_end();
4053 A != AEnd; (void)++A, ++Idx)
4054 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
4055
4056 return TemplateArgument(CanonArgs, Arg.pack_size());
4057 }
4058 }
4059
4060 // Silence GCC warning
4061 llvm_unreachable("Unhandled template argument kind");
4062 }
4063
4064 NestedNameSpecifier *
getCanonicalNestedNameSpecifier(NestedNameSpecifier * NNS) const4065 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
4066 if (!NNS)
4067 return 0;
4068
4069 switch (NNS->getKind()) {
4070 case NestedNameSpecifier::Identifier:
4071 // Canonicalize the prefix but keep the identifier the same.
4072 return NestedNameSpecifier::Create(*this,
4073 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4074 NNS->getAsIdentifier());
4075
4076 case NestedNameSpecifier::Namespace:
4077 // A namespace is canonical; build a nested-name-specifier with
4078 // this namespace and no prefix.
4079 return NestedNameSpecifier::Create(*this, 0,
4080 NNS->getAsNamespace()->getOriginalNamespace());
4081
4082 case NestedNameSpecifier::NamespaceAlias:
4083 // A namespace is canonical; build a nested-name-specifier with
4084 // this namespace and no prefix.
4085 return NestedNameSpecifier::Create(*this, 0,
4086 NNS->getAsNamespaceAlias()->getNamespace()
4087 ->getOriginalNamespace());
4088
4089 case NestedNameSpecifier::TypeSpec:
4090 case NestedNameSpecifier::TypeSpecWithTemplate: {
4091 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
4092
4093 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4094 // break it apart into its prefix and identifier, then reconsititute those
4095 // as the canonical nested-name-specifier. This is required to canonicalize
4096 // a dependent nested-name-specifier involving typedefs of dependent-name
4097 // types, e.g.,
4098 // typedef typename T::type T1;
4099 // typedef typename T1::type T2;
4100 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4101 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
4102 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
4103
4104 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4105 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4106 // first place?
4107 return NestedNameSpecifier::Create(*this, 0, false,
4108 const_cast<Type*>(T.getTypePtr()));
4109 }
4110
4111 case NestedNameSpecifier::Global:
4112 // The global specifier is canonical and unique.
4113 return NNS;
4114 }
4115
4116 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
4117 }
4118
4119
getAsArrayType(QualType T) const4120 const ArrayType *ASTContext::getAsArrayType(QualType T) const {
4121 // Handle the non-qualified case efficiently.
4122 if (!T.hasLocalQualifiers()) {
4123 // Handle the common positive case fast.
4124 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4125 return AT;
4126 }
4127
4128 // Handle the common negative case fast.
4129 if (!isa<ArrayType>(T.getCanonicalType()))
4130 return 0;
4131
4132 // Apply any qualifiers from the array type to the element type. This
4133 // implements C99 6.7.3p8: "If the specification of an array type includes
4134 // any type qualifiers, the element type is so qualified, not the array type."
4135
4136 // If we get here, we either have type qualifiers on the type, or we have
4137 // sugar such as a typedef in the way. If we have type qualifiers on the type
4138 // we must propagate them down into the element type.
4139
4140 SplitQualType split = T.getSplitDesugaredType();
4141 Qualifiers qs = split.Quals;
4142
4143 // If we have a simple case, just return now.
4144 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
4145 if (ATy == 0 || qs.empty())
4146 return ATy;
4147
4148 // Otherwise, we have an array and we have qualifiers on it. Push the
4149 // qualifiers into the array element type and return a new array type.
4150 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
4151
4152 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4153 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4154 CAT->getSizeModifier(),
4155 CAT->getIndexTypeCVRQualifiers()));
4156 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4157 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4158 IAT->getSizeModifier(),
4159 IAT->getIndexTypeCVRQualifiers()));
4160
4161 if (const DependentSizedArrayType *DSAT
4162 = dyn_cast<DependentSizedArrayType>(ATy))
4163 return cast<ArrayType>(
4164 getDependentSizedArrayType(NewEltTy,
4165 DSAT->getSizeExpr(),
4166 DSAT->getSizeModifier(),
4167 DSAT->getIndexTypeCVRQualifiers(),
4168 DSAT->getBracketsRange()));
4169
4170 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
4171 return cast<ArrayType>(getVariableArrayType(NewEltTy,
4172 VAT->getSizeExpr(),
4173 VAT->getSizeModifier(),
4174 VAT->getIndexTypeCVRQualifiers(),
4175 VAT->getBracketsRange()));
4176 }
4177
getAdjustedParameterType(QualType T) const4178 QualType ASTContext::getAdjustedParameterType(QualType T) const {
4179 if (T->isArrayType() || T->isFunctionType())
4180 return getDecayedType(T);
4181 return T;
4182 }
4183
getSignatureParameterType(QualType T) const4184 QualType ASTContext::getSignatureParameterType(QualType T) const {
4185 T = getVariableArrayDecayedType(T);
4186 T = getAdjustedParameterType(T);
4187 return T.getUnqualifiedType();
4188 }
4189
4190 /// getArrayDecayedType - Return the properly qualified result of decaying the
4191 /// specified array type to a pointer. This operation is non-trivial when
4192 /// handling typedefs etc. The canonical type of "T" must be an array type,
4193 /// this returns a pointer to a properly qualified element of the array.
4194 ///
4195 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
getArrayDecayedType(QualType Ty) const4196 QualType ASTContext::getArrayDecayedType(QualType Ty) const {
4197 // Get the element type with 'getAsArrayType' so that we don't lose any
4198 // typedefs in the element type of the array. This also handles propagation
4199 // of type qualifiers from the array type into the element type if present
4200 // (C99 6.7.3p8).
4201 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4202 assert(PrettyArrayType && "Not an array type!");
4203
4204 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
4205
4206 // int x[restrict 4] -> int *restrict
4207 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
4208 }
4209
getBaseElementType(const ArrayType * array) const4210 QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4211 return getBaseElementType(array->getElementType());
4212 }
4213
getBaseElementType(QualType type) const4214 QualType ASTContext::getBaseElementType(QualType type) const {
4215 Qualifiers qs;
4216 while (true) {
4217 SplitQualType split = type.getSplitDesugaredType();
4218 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
4219 if (!array) break;
4220
4221 type = array->getElementType();
4222 qs.addConsistentQualifiers(split.Quals);
4223 }
4224
4225 return getQualifiedType(type, qs);
4226 }
4227
4228 /// getConstantArrayElementCount - Returns number of constant array elements.
4229 uint64_t
getConstantArrayElementCount(const ConstantArrayType * CA) const4230 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4231 uint64_t ElementCount = 1;
4232 do {
4233 ElementCount *= CA->getSize().getZExtValue();
4234 CA = dyn_cast_or_null<ConstantArrayType>(
4235 CA->getElementType()->getAsArrayTypeUnsafe());
4236 } while (CA);
4237 return ElementCount;
4238 }
4239
4240 /// getFloatingRank - Return a relative rank for floating point types.
4241 /// This routine will assert if passed a built-in type that isn't a float.
getFloatingRank(QualType T)4242 static FloatingRank getFloatingRank(QualType T) {
4243 if (const ComplexType *CT = T->getAs<ComplexType>())
4244 return getFloatingRank(CT->getElementType());
4245
4246 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4247 switch (T->getAs<BuiltinType>()->getKind()) {
4248 default: llvm_unreachable("getFloatingRank(): not a floating type");
4249 case BuiltinType::Half: return HalfRank;
4250 case BuiltinType::Float: return FloatRank;
4251 case BuiltinType::Double: return DoubleRank;
4252 case BuiltinType::LongDouble: return LongDoubleRank;
4253 }
4254 }
4255
4256 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4257 /// point or a complex type (based on typeDomain/typeSize).
4258 /// 'typeDomain' is a real floating point or complex type.
4259 /// 'typeSize' is a real floating point or complex type.
getFloatingTypeOfSizeWithinDomain(QualType Size,QualType Domain) const4260 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4261 QualType Domain) const {
4262 FloatingRank EltRank = getFloatingRank(Size);
4263 if (Domain->isComplexType()) {
4264 switch (EltRank) {
4265 case HalfRank: llvm_unreachable("Complex half is not supported");
4266 case FloatRank: return FloatComplexTy;
4267 case DoubleRank: return DoubleComplexTy;
4268 case LongDoubleRank: return LongDoubleComplexTy;
4269 }
4270 }
4271
4272 assert(Domain->isRealFloatingType() && "Unknown domain!");
4273 switch (EltRank) {
4274 case HalfRank: return HalfTy;
4275 case FloatRank: return FloatTy;
4276 case DoubleRank: return DoubleTy;
4277 case LongDoubleRank: return LongDoubleTy;
4278 }
4279 llvm_unreachable("getFloatingRank(): illegal value for rank");
4280 }
4281
4282 /// getFloatingTypeOrder - Compare the rank of the two specified floating
4283 /// point types, ignoring the domain of the type (i.e. 'double' ==
4284 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
4285 /// LHS < RHS, return -1.
getFloatingTypeOrder(QualType LHS,QualType RHS) const4286 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
4287 FloatingRank LHSR = getFloatingRank(LHS);
4288 FloatingRank RHSR = getFloatingRank(RHS);
4289
4290 if (LHSR == RHSR)
4291 return 0;
4292 if (LHSR > RHSR)
4293 return 1;
4294 return -1;
4295 }
4296
4297 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4298 /// routine will assert if passed a built-in type that isn't an integer or enum,
4299 /// or if it is not canonicalized.
getIntegerRank(const Type * T) const4300 unsigned ASTContext::getIntegerRank(const Type *T) const {
4301 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
4302
4303 switch (cast<BuiltinType>(T)->getKind()) {
4304 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
4305 case BuiltinType::Bool:
4306 return 1 + (getIntWidth(BoolTy) << 3);
4307 case BuiltinType::Char_S:
4308 case BuiltinType::Char_U:
4309 case BuiltinType::SChar:
4310 case BuiltinType::UChar:
4311 return 2 + (getIntWidth(CharTy) << 3);
4312 case BuiltinType::Short:
4313 case BuiltinType::UShort:
4314 return 3 + (getIntWidth(ShortTy) << 3);
4315 case BuiltinType::Int:
4316 case BuiltinType::UInt:
4317 return 4 + (getIntWidth(IntTy) << 3);
4318 case BuiltinType::Long:
4319 case BuiltinType::ULong:
4320 return 5 + (getIntWidth(LongTy) << 3);
4321 case BuiltinType::LongLong:
4322 case BuiltinType::ULongLong:
4323 return 6 + (getIntWidth(LongLongTy) << 3);
4324 case BuiltinType::Int128:
4325 case BuiltinType::UInt128:
4326 return 7 + (getIntWidth(Int128Ty) << 3);
4327 }
4328 }
4329
4330 /// \brief Whether this is a promotable bitfield reference according
4331 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4332 ///
4333 /// \returns the type this bit-field will promote to, or NULL if no
4334 /// promotion occurs.
isPromotableBitField(Expr * E) const4335 QualType ASTContext::isPromotableBitField(Expr *E) const {
4336 if (E->isTypeDependent() || E->isValueDependent())
4337 return QualType();
4338
4339 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
4340 if (!Field)
4341 return QualType();
4342
4343 QualType FT = Field->getType();
4344
4345 uint64_t BitWidth = Field->getBitWidthValue(*this);
4346 uint64_t IntSize = getTypeSize(IntTy);
4347 // GCC extension compatibility: if the bit-field size is less than or equal
4348 // to the size of int, it gets promoted no matter what its type is.
4349 // For instance, unsigned long bf : 4 gets promoted to signed int.
4350 if (BitWidth < IntSize)
4351 return IntTy;
4352
4353 if (BitWidth == IntSize)
4354 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4355
4356 // Types bigger than int are not subject to promotions, and therefore act
4357 // like the base type.
4358 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4359 // is ridiculous.
4360 return QualType();
4361 }
4362
4363 /// getPromotedIntegerType - Returns the type that Promotable will
4364 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4365 /// integer type.
getPromotedIntegerType(QualType Promotable) const4366 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
4367 assert(!Promotable.isNull());
4368 assert(Promotable->isPromotableIntegerType());
4369 if (const EnumType *ET = Promotable->getAs<EnumType>())
4370 return ET->getDecl()->getPromotionType();
4371
4372 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4373 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4374 // (3.9.1) can be converted to a prvalue of the first of the following
4375 // types that can represent all the values of its underlying type:
4376 // int, unsigned int, long int, unsigned long int, long long int, or
4377 // unsigned long long int [...]
4378 // FIXME: Is there some better way to compute this?
4379 if (BT->getKind() == BuiltinType::WChar_S ||
4380 BT->getKind() == BuiltinType::WChar_U ||
4381 BT->getKind() == BuiltinType::Char16 ||
4382 BT->getKind() == BuiltinType::Char32) {
4383 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4384 uint64_t FromSize = getTypeSize(BT);
4385 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4386 LongLongTy, UnsignedLongLongTy };
4387 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4388 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4389 if (FromSize < ToSize ||
4390 (FromSize == ToSize &&
4391 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4392 return PromoteTypes[Idx];
4393 }
4394 llvm_unreachable("char type should fit into long long");
4395 }
4396 }
4397
4398 // At this point, we should have a signed or unsigned integer type.
4399 if (Promotable->isSignedIntegerType())
4400 return IntTy;
4401 uint64_t PromotableSize = getIntWidth(Promotable);
4402 uint64_t IntSize = getIntWidth(IntTy);
4403 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4404 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4405 }
4406
4407 /// \brief Recurses in pointer/array types until it finds an objc retainable
4408 /// type and returns its ownership.
getInnerObjCOwnership(QualType T) const4409 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4410 while (!T.isNull()) {
4411 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4412 return T.getObjCLifetime();
4413 if (T->isArrayType())
4414 T = getBaseElementType(T);
4415 else if (const PointerType *PT = T->getAs<PointerType>())
4416 T = PT->getPointeeType();
4417 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4418 T = RT->getPointeeType();
4419 else
4420 break;
4421 }
4422
4423 return Qualifiers::OCL_None;
4424 }
4425
getIntegerTypeForEnum(const EnumType * ET)4426 static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4427 // Incomplete enum types are not treated as integer types.
4428 // FIXME: In C++, enum types are never integer types.
4429 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4430 return ET->getDecl()->getIntegerType().getTypePtr();
4431 return NULL;
4432 }
4433
4434 /// getIntegerTypeOrder - Returns the highest ranked integer type:
4435 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
4436 /// LHS < RHS, return -1.
getIntegerTypeOrder(QualType LHS,QualType RHS) const4437 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
4438 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4439 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
4440
4441 // Unwrap enums to their underlying type.
4442 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4443 LHSC = getIntegerTypeForEnum(ET);
4444 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4445 RHSC = getIntegerTypeForEnum(ET);
4446
4447 if (LHSC == RHSC) return 0;
4448
4449 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4450 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
4451
4452 unsigned LHSRank = getIntegerRank(LHSC);
4453 unsigned RHSRank = getIntegerRank(RHSC);
4454
4455 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4456 if (LHSRank == RHSRank) return 0;
4457 return LHSRank > RHSRank ? 1 : -1;
4458 }
4459
4460 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4461 if (LHSUnsigned) {
4462 // If the unsigned [LHS] type is larger, return it.
4463 if (LHSRank >= RHSRank)
4464 return 1;
4465
4466 // If the signed type can represent all values of the unsigned type, it
4467 // wins. Because we are dealing with 2's complement and types that are
4468 // powers of two larger than each other, this is always safe.
4469 return -1;
4470 }
4471
4472 // If the unsigned [RHS] type is larger, return it.
4473 if (RHSRank >= LHSRank)
4474 return -1;
4475
4476 // If the signed type can represent all values of the unsigned type, it
4477 // wins. Because we are dealing with 2's complement and types that are
4478 // powers of two larger than each other, this is always safe.
4479 return 1;
4480 }
4481
4482 static RecordDecl *
CreateRecordDecl(const ASTContext & Ctx,RecordDecl::TagKind TK,DeclContext * DC,IdentifierInfo * Id)4483 CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4484 DeclContext *DC, IdentifierInfo *Id) {
4485 SourceLocation Loc;
4486 if (Ctx.getLangOpts().CPlusPlus)
4487 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
4488 else
4489 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
4490 }
4491
4492 // getCFConstantStringType - Return the type used for constant CFStrings.
getCFConstantStringType() const4493 QualType ASTContext::getCFConstantStringType() const {
4494 if (!CFConstantStringTypeDecl) {
4495 CFConstantStringTypeDecl =
4496 CreateRecordDecl(*this, TTK_Struct, TUDecl,
4497 &Idents.get("NSConstantString"));
4498 CFConstantStringTypeDecl->startDefinition();
4499
4500 QualType FieldTypes[4];
4501
4502 // const int *isa;
4503 FieldTypes[0] = getPointerType(IntTy.withConst());
4504 // int flags;
4505 FieldTypes[1] = IntTy;
4506 // const char *str;
4507 FieldTypes[2] = getPointerType(CharTy.withConst());
4508 // long length;
4509 FieldTypes[3] = LongTy;
4510
4511 // Create fields
4512 for (unsigned i = 0; i < 4; ++i) {
4513 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
4514 SourceLocation(),
4515 SourceLocation(), 0,
4516 FieldTypes[i], /*TInfo=*/0,
4517 /*BitWidth=*/0,
4518 /*Mutable=*/false,
4519 ICIS_NoInit);
4520 Field->setAccess(AS_public);
4521 CFConstantStringTypeDecl->addDecl(Field);
4522 }
4523
4524 CFConstantStringTypeDecl->completeDefinition();
4525 }
4526
4527 return getTagDeclType(CFConstantStringTypeDecl);
4528 }
4529
getObjCSuperType() const4530 QualType ASTContext::getObjCSuperType() const {
4531 if (ObjCSuperType.isNull()) {
4532 RecordDecl *ObjCSuperTypeDecl =
4533 CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get("objc_super"));
4534 TUDecl->addDecl(ObjCSuperTypeDecl);
4535 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4536 }
4537 return ObjCSuperType;
4538 }
4539
setCFConstantStringType(QualType T)4540 void ASTContext::setCFConstantStringType(QualType T) {
4541 const RecordType *Rec = T->getAs<RecordType>();
4542 assert(Rec && "Invalid CFConstantStringType");
4543 CFConstantStringTypeDecl = Rec->getDecl();
4544 }
4545
getBlockDescriptorType() const4546 QualType ASTContext::getBlockDescriptorType() const {
4547 if (BlockDescriptorType)
4548 return getTagDeclType(BlockDescriptorType);
4549
4550 RecordDecl *T;
4551 // FIXME: Needs the FlagAppleBlock bit.
4552 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
4553 &Idents.get("__block_descriptor"));
4554 T->startDefinition();
4555
4556 QualType FieldTypes[] = {
4557 UnsignedLongTy,
4558 UnsignedLongTy,
4559 };
4560
4561 static const char *const FieldNames[] = {
4562 "reserved",
4563 "Size"
4564 };
4565
4566 for (size_t i = 0; i < 2; ++i) {
4567 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
4568 SourceLocation(),
4569 &Idents.get(FieldNames[i]),
4570 FieldTypes[i], /*TInfo=*/0,
4571 /*BitWidth=*/0,
4572 /*Mutable=*/false,
4573 ICIS_NoInit);
4574 Field->setAccess(AS_public);
4575 T->addDecl(Field);
4576 }
4577
4578 T->completeDefinition();
4579
4580 BlockDescriptorType = T;
4581
4582 return getTagDeclType(BlockDescriptorType);
4583 }
4584
getBlockDescriptorExtendedType() const4585 QualType ASTContext::getBlockDescriptorExtendedType() const {
4586 if (BlockDescriptorExtendedType)
4587 return getTagDeclType(BlockDescriptorExtendedType);
4588
4589 RecordDecl *T;
4590 // FIXME: Needs the FlagAppleBlock bit.
4591 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
4592 &Idents.get("__block_descriptor_withcopydispose"));
4593 T->startDefinition();
4594
4595 QualType FieldTypes[] = {
4596 UnsignedLongTy,
4597 UnsignedLongTy,
4598 getPointerType(VoidPtrTy),
4599 getPointerType(VoidPtrTy)
4600 };
4601
4602 static const char *const FieldNames[] = {
4603 "reserved",
4604 "Size",
4605 "CopyFuncPtr",
4606 "DestroyFuncPtr"
4607 };
4608
4609 for (size_t i = 0; i < 4; ++i) {
4610 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
4611 SourceLocation(),
4612 &Idents.get(FieldNames[i]),
4613 FieldTypes[i], /*TInfo=*/0,
4614 /*BitWidth=*/0,
4615 /*Mutable=*/false,
4616 ICIS_NoInit);
4617 Field->setAccess(AS_public);
4618 T->addDecl(Field);
4619 }
4620
4621 T->completeDefinition();
4622
4623 BlockDescriptorExtendedType = T;
4624
4625 return getTagDeclType(BlockDescriptorExtendedType);
4626 }
4627
4628 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4629 /// requires copy/dispose. Note that this must match the logic
4630 /// in buildByrefHelpers.
BlockRequiresCopying(QualType Ty,const VarDecl * D)4631 bool ASTContext::BlockRequiresCopying(QualType Ty,
4632 const VarDecl *D) {
4633 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4634 const Expr *copyExpr = getBlockVarCopyInits(D);
4635 if (!copyExpr && record->hasTrivialDestructor()) return false;
4636
4637 return true;
4638 }
4639
4640 if (!Ty->isObjCRetainableType()) return false;
4641
4642 Qualifiers qs = Ty.getQualifiers();
4643
4644 // If we have lifetime, that dominates.
4645 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4646 assert(getLangOpts().ObjCAutoRefCount);
4647
4648 switch (lifetime) {
4649 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4650
4651 // These are just bits as far as the runtime is concerned.
4652 case Qualifiers::OCL_ExplicitNone:
4653 case Qualifiers::OCL_Autoreleasing:
4654 return false;
4655
4656 // Tell the runtime that this is ARC __weak, called by the
4657 // byref routines.
4658 case Qualifiers::OCL_Weak:
4659 // ARC __strong __block variables need to be retained.
4660 case Qualifiers::OCL_Strong:
4661 return true;
4662 }
4663 llvm_unreachable("fell out of lifetime switch!");
4664 }
4665 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4666 Ty->isObjCObjectPointerType());
4667 }
4668
getByrefLifetime(QualType Ty,Qualifiers::ObjCLifetime & LifeTime,bool & HasByrefExtendedLayout) const4669 bool ASTContext::getByrefLifetime(QualType Ty,
4670 Qualifiers::ObjCLifetime &LifeTime,
4671 bool &HasByrefExtendedLayout) const {
4672
4673 if (!getLangOpts().ObjC1 ||
4674 getLangOpts().getGC() != LangOptions::NonGC)
4675 return false;
4676
4677 HasByrefExtendedLayout = false;
4678 if (Ty->isRecordType()) {
4679 HasByrefExtendedLayout = true;
4680 LifeTime = Qualifiers::OCL_None;
4681 }
4682 else if (getLangOpts().ObjCAutoRefCount)
4683 LifeTime = Ty.getObjCLifetime();
4684 // MRR.
4685 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4686 LifeTime = Qualifiers::OCL_ExplicitNone;
4687 else
4688 LifeTime = Qualifiers::OCL_None;
4689 return true;
4690 }
4691
getObjCInstanceTypeDecl()4692 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4693 if (!ObjCInstanceTypeDecl)
4694 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4695 getTranslationUnitDecl(),
4696 SourceLocation(),
4697 SourceLocation(),
4698 &Idents.get("instancetype"),
4699 getTrivialTypeSourceInfo(getObjCIdType()));
4700 return ObjCInstanceTypeDecl;
4701 }
4702
4703 // This returns true if a type has been typedefed to BOOL:
4704 // typedef <type> BOOL;
isTypeTypedefedAsBOOL(QualType T)4705 static bool isTypeTypedefedAsBOOL(QualType T) {
4706 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
4707 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4708 return II->isStr("BOOL");
4709
4710 return false;
4711 }
4712
4713 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
4714 /// purpose.
getObjCEncodingTypeSize(QualType type) const4715 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
4716 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4717 return CharUnits::Zero();
4718
4719 CharUnits sz = getTypeSizeInChars(type);
4720
4721 // Make all integer and enum types at least as large as an int
4722 if (sz.isPositive() && type->isIntegralOrEnumerationType())
4723 sz = std::max(sz, getTypeSizeInChars(IntTy));
4724 // Treat arrays as pointers, since that's how they're passed in.
4725 else if (type->isArrayType())
4726 sz = getTypeSizeInChars(VoidPtrTy);
4727 return sz;
4728 }
4729
4730 static inline
charUnitsToString(const CharUnits & CU)4731 std::string charUnitsToString(const CharUnits &CU) {
4732 return llvm::itostr(CU.getQuantity());
4733 }
4734
4735 /// getObjCEncodingForBlock - Return the encoded type for this block
4736 /// declaration.
getObjCEncodingForBlock(const BlockExpr * Expr) const4737 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4738 std::string S;
4739
4740 const BlockDecl *Decl = Expr->getBlockDecl();
4741 QualType BlockTy =
4742 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4743 // Encode result type.
4744 if (getLangOpts().EncodeExtendedBlockSig)
4745 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4746 BlockTy->getAs<FunctionType>()->getResultType(),
4747 S, true /*Extended*/);
4748 else
4749 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4750 S);
4751 // Compute size of all parameters.
4752 // Start with computing size of a pointer in number of bytes.
4753 // FIXME: There might(should) be a better way of doing this computation!
4754 SourceLocation Loc;
4755 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4756 CharUnits ParmOffset = PtrSize;
4757 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
4758 E = Decl->param_end(); PI != E; ++PI) {
4759 QualType PType = (*PI)->getType();
4760 CharUnits sz = getObjCEncodingTypeSize(PType);
4761 if (sz.isZero())
4762 continue;
4763 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
4764 ParmOffset += sz;
4765 }
4766 // Size of the argument frame
4767 S += charUnitsToString(ParmOffset);
4768 // Block pointer and offset.
4769 S += "@?0";
4770
4771 // Argument types.
4772 ParmOffset = PtrSize;
4773 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4774 Decl->param_end(); PI != E; ++PI) {
4775 ParmVarDecl *PVDecl = *PI;
4776 QualType PType = PVDecl->getOriginalType();
4777 if (const ArrayType *AT =
4778 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4779 // Use array's original type only if it has known number of
4780 // elements.
4781 if (!isa<ConstantArrayType>(AT))
4782 PType = PVDecl->getType();
4783 } else if (PType->isFunctionType())
4784 PType = PVDecl->getType();
4785 if (getLangOpts().EncodeExtendedBlockSig)
4786 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4787 S, true /*Extended*/);
4788 else
4789 getObjCEncodingForType(PType, S);
4790 S += charUnitsToString(ParmOffset);
4791 ParmOffset += getObjCEncodingTypeSize(PType);
4792 }
4793
4794 return S;
4795 }
4796
getObjCEncodingForFunctionDecl(const FunctionDecl * Decl,std::string & S)4797 bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
4798 std::string& S) {
4799 // Encode result type.
4800 getObjCEncodingForType(Decl->getResultType(), S);
4801 CharUnits ParmOffset;
4802 // Compute size of all parameters.
4803 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4804 E = Decl->param_end(); PI != E; ++PI) {
4805 QualType PType = (*PI)->getType();
4806 CharUnits sz = getObjCEncodingTypeSize(PType);
4807 if (sz.isZero())
4808 continue;
4809
4810 assert (sz.isPositive() &&
4811 "getObjCEncodingForFunctionDecl - Incomplete param type");
4812 ParmOffset += sz;
4813 }
4814 S += charUnitsToString(ParmOffset);
4815 ParmOffset = CharUnits::Zero();
4816
4817 // Argument types.
4818 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4819 E = Decl->param_end(); PI != E; ++PI) {
4820 ParmVarDecl *PVDecl = *PI;
4821 QualType PType = PVDecl->getOriginalType();
4822 if (const ArrayType *AT =
4823 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4824 // Use array's original type only if it has known number of
4825 // elements.
4826 if (!isa<ConstantArrayType>(AT))
4827 PType = PVDecl->getType();
4828 } else if (PType->isFunctionType())
4829 PType = PVDecl->getType();
4830 getObjCEncodingForType(PType, S);
4831 S += charUnitsToString(ParmOffset);
4832 ParmOffset += getObjCEncodingTypeSize(PType);
4833 }
4834
4835 return false;
4836 }
4837
4838 /// getObjCEncodingForMethodParameter - Return the encoded type for a single
4839 /// method parameter or return type. If Extended, include class names and
4840 /// block object types.
getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,QualType T,std::string & S,bool Extended) const4841 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4842 QualType T, std::string& S,
4843 bool Extended) const {
4844 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4845 getObjCEncodingForTypeQualifier(QT, S);
4846 // Encode parameter type.
4847 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4848 true /*OutermostType*/,
4849 false /*EncodingProperty*/,
4850 false /*StructField*/,
4851 Extended /*EncodeBlockParameters*/,
4852 Extended /*EncodeClassNames*/);
4853 }
4854
4855 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
4856 /// declaration.
getObjCEncodingForMethodDecl(const ObjCMethodDecl * Decl,std::string & S,bool Extended) const4857 bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
4858 std::string& S,
4859 bool Extended) const {
4860 // FIXME: This is not very efficient.
4861 // Encode return type.
4862 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4863 Decl->getResultType(), S, Extended);
4864 // Compute size of all parameters.
4865 // Start with computing size of a pointer in number of bytes.
4866 // FIXME: There might(should) be a better way of doing this computation!
4867 SourceLocation Loc;
4868 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4869 // The first two arguments (self and _cmd) are pointers; account for
4870 // their size.
4871 CharUnits ParmOffset = 2 * PtrSize;
4872 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
4873 E = Decl->sel_param_end(); PI != E; ++PI) {
4874 QualType PType = (*PI)->getType();
4875 CharUnits sz = getObjCEncodingTypeSize(PType);
4876 if (sz.isZero())
4877 continue;
4878
4879 assert (sz.isPositive() &&
4880 "getObjCEncodingForMethodDecl - Incomplete param type");
4881 ParmOffset += sz;
4882 }
4883 S += charUnitsToString(ParmOffset);
4884 S += "@0:";
4885 S += charUnitsToString(PtrSize);
4886
4887 // Argument types.
4888 ParmOffset = 2 * PtrSize;
4889 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
4890 E = Decl->sel_param_end(); PI != E; ++PI) {
4891 const ParmVarDecl *PVDecl = *PI;
4892 QualType PType = PVDecl->getOriginalType();
4893 if (const ArrayType *AT =
4894 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4895 // Use array's original type only if it has known number of
4896 // elements.
4897 if (!isa<ConstantArrayType>(AT))
4898 PType = PVDecl->getType();
4899 } else if (PType->isFunctionType())
4900 PType = PVDecl->getType();
4901 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4902 PType, S, Extended);
4903 S += charUnitsToString(ParmOffset);
4904 ParmOffset += getObjCEncodingTypeSize(PType);
4905 }
4906
4907 return false;
4908 }
4909
4910 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
4911 /// property declaration. If non-NULL, Container must be either an
4912 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4913 /// NULL when getting encodings for protocol properties.
4914 /// Property attributes are stored as a comma-delimited C string. The simple
4915 /// attributes readonly and bycopy are encoded as single characters. The
4916 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
4917 /// encoded as single characters, followed by an identifier. Property types
4918 /// are also encoded as a parametrized attribute. The characters used to encode
4919 /// these attributes are defined by the following enumeration:
4920 /// @code
4921 /// enum PropertyAttributes {
4922 /// kPropertyReadOnly = 'R', // property is read-only.
4923 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4924 /// kPropertyByref = '&', // property is a reference to the value last assigned
4925 /// kPropertyDynamic = 'D', // property is dynamic
4926 /// kPropertyGetter = 'G', // followed by getter selector name
4927 /// kPropertySetter = 'S', // followed by setter selector name
4928 /// kPropertyInstanceVariable = 'V' // followed by instance variable name
4929 /// kPropertyType = 'T' // followed by old-style type encoding.
4930 /// kPropertyWeak = 'W' // 'weak' property
4931 /// kPropertyStrong = 'P' // property GC'able
4932 /// kPropertyNonAtomic = 'N' // property non-atomic
4933 /// };
4934 /// @endcode
getObjCEncodingForPropertyDecl(const ObjCPropertyDecl * PD,const Decl * Container,std::string & S) const4935 void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
4936 const Decl *Container,
4937 std::string& S) const {
4938 // Collect information from the property implementation decl(s).
4939 bool Dynamic = false;
4940 ObjCPropertyImplDecl *SynthesizePID = 0;
4941
4942 // FIXME: Duplicated code due to poor abstraction.
4943 if (Container) {
4944 if (const ObjCCategoryImplDecl *CID =
4945 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4946 for (ObjCCategoryImplDecl::propimpl_iterator
4947 i = CID->propimpl_begin(), e = CID->propimpl_end();
4948 i != e; ++i) {
4949 ObjCPropertyImplDecl *PID = *i;
4950 if (PID->getPropertyDecl() == PD) {
4951 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4952 Dynamic = true;
4953 } else {
4954 SynthesizePID = PID;
4955 }
4956 }
4957 }
4958 } else {
4959 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
4960 for (ObjCCategoryImplDecl::propimpl_iterator
4961 i = OID->propimpl_begin(), e = OID->propimpl_end();
4962 i != e; ++i) {
4963 ObjCPropertyImplDecl *PID = *i;
4964 if (PID->getPropertyDecl() == PD) {
4965 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4966 Dynamic = true;
4967 } else {
4968 SynthesizePID = PID;
4969 }
4970 }
4971 }
4972 }
4973 }
4974
4975 // FIXME: This is not very efficient.
4976 S = "T";
4977
4978 // Encode result type.
4979 // GCC has some special rules regarding encoding of properties which
4980 // closely resembles encoding of ivars.
4981 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
4982 true /* outermost type */,
4983 true /* encoding for property */);
4984
4985 if (PD->isReadOnly()) {
4986 S += ",R";
4987 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
4988 S += ",C";
4989 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
4990 S += ",&";
4991 } else {
4992 switch (PD->getSetterKind()) {
4993 case ObjCPropertyDecl::Assign: break;
4994 case ObjCPropertyDecl::Copy: S += ",C"; break;
4995 case ObjCPropertyDecl::Retain: S += ",&"; break;
4996 case ObjCPropertyDecl::Weak: S += ",W"; break;
4997 }
4998 }
4999
5000 // It really isn't clear at all what this means, since properties
5001 // are "dynamic by default".
5002 if (Dynamic)
5003 S += ",D";
5004
5005 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5006 S += ",N";
5007
5008 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5009 S += ",G";
5010 S += PD->getGetterName().getAsString();
5011 }
5012
5013 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5014 S += ",S";
5015 S += PD->getSetterName().getAsString();
5016 }
5017
5018 if (SynthesizePID) {
5019 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5020 S += ",V";
5021 S += OID->getNameAsString();
5022 }
5023
5024 // FIXME: OBJCGC: weak & strong
5025 }
5026
5027 /// getLegacyIntegralTypeEncoding -
5028 /// Another legacy compatibility encoding: 32-bit longs are encoded as
5029 /// 'l' or 'L' , but not always. For typedefs, we need to use
5030 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
5031 ///
getLegacyIntegralTypeEncoding(QualType & PointeeTy) const5032 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
5033 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
5034 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
5035 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
5036 PointeeTy = UnsignedIntTy;
5037 else
5038 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
5039 PointeeTy = IntTy;
5040 }
5041 }
5042 }
5043
getObjCEncodingForType(QualType T,std::string & S,const FieldDecl * Field) const5044 void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
5045 const FieldDecl *Field) const {
5046 // We follow the behavior of gcc, expanding structures which are
5047 // directly pointed to, and expanding embedded structures. Note that
5048 // these rules are sufficient to prevent recursive encoding of the
5049 // same type.
5050 getObjCEncodingForTypeImpl(T, S, true, true, Field,
5051 true /* outermost type */);
5052 }
5053
getObjCEncodingForPrimitiveKind(const ASTContext * C,BuiltinType::Kind kind)5054 static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5055 BuiltinType::Kind kind) {
5056 switch (kind) {
5057 case BuiltinType::Void: return 'v';
5058 case BuiltinType::Bool: return 'B';
5059 case BuiltinType::Char_U:
5060 case BuiltinType::UChar: return 'C';
5061 case BuiltinType::Char16:
5062 case BuiltinType::UShort: return 'S';
5063 case BuiltinType::Char32:
5064 case BuiltinType::UInt: return 'I';
5065 case BuiltinType::ULong:
5066 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
5067 case BuiltinType::UInt128: return 'T';
5068 case BuiltinType::ULongLong: return 'Q';
5069 case BuiltinType::Char_S:
5070 case BuiltinType::SChar: return 'c';
5071 case BuiltinType::Short: return 's';
5072 case BuiltinType::WChar_S:
5073 case BuiltinType::WChar_U:
5074 case BuiltinType::Int: return 'i';
5075 case BuiltinType::Long:
5076 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
5077 case BuiltinType::LongLong: return 'q';
5078 case BuiltinType::Int128: return 't';
5079 case BuiltinType::Float: return 'f';
5080 case BuiltinType::Double: return 'd';
5081 case BuiltinType::LongDouble: return 'D';
5082 case BuiltinType::NullPtr: return '*'; // like char*
5083
5084 case BuiltinType::Half:
5085 // FIXME: potentially need @encodes for these!
5086 return ' ';
5087
5088 case BuiltinType::ObjCId:
5089 case BuiltinType::ObjCClass:
5090 case BuiltinType::ObjCSel:
5091 llvm_unreachable("@encoding ObjC primitive type");
5092
5093 // OpenCL and placeholder types don't need @encodings.
5094 case BuiltinType::OCLImage1d:
5095 case BuiltinType::OCLImage1dArray:
5096 case BuiltinType::OCLImage1dBuffer:
5097 case BuiltinType::OCLImage2d:
5098 case BuiltinType::OCLImage2dArray:
5099 case BuiltinType::OCLImage3d:
5100 case BuiltinType::OCLEvent:
5101 case BuiltinType::OCLSampler:
5102 case BuiltinType::Dependent:
5103 #define BUILTIN_TYPE(KIND, ID)
5104 #define PLACEHOLDER_TYPE(KIND, ID) \
5105 case BuiltinType::KIND:
5106 #include "clang/AST/BuiltinTypes.def"
5107 llvm_unreachable("invalid builtin type for @encode");
5108 }
5109 llvm_unreachable("invalid BuiltinType::Kind value");
5110 }
5111
ObjCEncodingForEnumType(const ASTContext * C,const EnumType * ET)5112 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5113 EnumDecl *Enum = ET->getDecl();
5114
5115 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5116 if (!Enum->isFixed())
5117 return 'i';
5118
5119 // The encoding of a fixed enum type matches its fixed underlying type.
5120 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5121 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
5122 }
5123
EncodeBitField(const ASTContext * Ctx,std::string & S,QualType T,const FieldDecl * FD)5124 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
5125 QualType T, const FieldDecl *FD) {
5126 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
5127 S += 'b';
5128 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5129 // The GNU runtime requires more information; bitfields are encoded as b,
5130 // then the offset (in bits) of the first element, then the type of the
5131 // bitfield, then the size in bits. For example, in this structure:
5132 //
5133 // struct
5134 // {
5135 // int integer;
5136 // int flags:2;
5137 // };
5138 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5139 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5140 // information is not especially sensible, but we're stuck with it for
5141 // compatibility with GCC, although providing it breaks anything that
5142 // actually uses runtime introspection and wants to work on both runtimes...
5143 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
5144 const RecordDecl *RD = FD->getParent();
5145 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
5146 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
5147 if (const EnumType *ET = T->getAs<EnumType>())
5148 S += ObjCEncodingForEnumType(Ctx, ET);
5149 else {
5150 const BuiltinType *BT = T->castAs<BuiltinType>();
5151 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5152 }
5153 }
5154 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
5155 }
5156
5157 // FIXME: Use SmallString for accumulating string.
getObjCEncodingForTypeImpl(QualType T,std::string & S,bool ExpandPointedToStructures,bool ExpandStructures,const FieldDecl * FD,bool OutermostType,bool EncodingProperty,bool StructField,bool EncodeBlockParameters,bool EncodeClassNames,bool EncodePointerToObjCTypedef) const5158 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5159 bool ExpandPointedToStructures,
5160 bool ExpandStructures,
5161 const FieldDecl *FD,
5162 bool OutermostType,
5163 bool EncodingProperty,
5164 bool StructField,
5165 bool EncodeBlockParameters,
5166 bool EncodeClassNames,
5167 bool EncodePointerToObjCTypedef) const {
5168 CanQualType CT = getCanonicalType(T);
5169 switch (CT->getTypeClass()) {
5170 case Type::Builtin:
5171 case Type::Enum:
5172 if (FD && FD->isBitField())
5173 return EncodeBitField(this, S, T, FD);
5174 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5175 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5176 else
5177 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
5178 return;
5179
5180 case Type::Complex: {
5181 const ComplexType *CT = T->castAs<ComplexType>();
5182 S += 'j';
5183 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
5184 false);
5185 return;
5186 }
5187
5188 case Type::Atomic: {
5189 const AtomicType *AT = T->castAs<AtomicType>();
5190 S += 'A';
5191 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5192 false, false);
5193 return;
5194 }
5195
5196 // encoding for pointer or reference types.
5197 case Type::Pointer:
5198 case Type::LValueReference:
5199 case Type::RValueReference: {
5200 QualType PointeeTy;
5201 if (isa<PointerType>(CT)) {
5202 const PointerType *PT = T->castAs<PointerType>();
5203 if (PT->isObjCSelType()) {
5204 S += ':';
5205 return;
5206 }
5207 PointeeTy = PT->getPointeeType();
5208 } else {
5209 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5210 }
5211
5212 bool isReadOnly = false;
5213 // For historical/compatibility reasons, the read-only qualifier of the
5214 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5215 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
5216 // Also, do not emit the 'r' for anything but the outermost type!
5217 if (isa<TypedefType>(T.getTypePtr())) {
5218 if (OutermostType && T.isConstQualified()) {
5219 isReadOnly = true;
5220 S += 'r';
5221 }
5222 } else if (OutermostType) {
5223 QualType P = PointeeTy;
5224 while (P->getAs<PointerType>())
5225 P = P->getAs<PointerType>()->getPointeeType();
5226 if (P.isConstQualified()) {
5227 isReadOnly = true;
5228 S += 'r';
5229 }
5230 }
5231 if (isReadOnly) {
5232 // Another legacy compatibility encoding. Some ObjC qualifier and type
5233 // combinations need to be rearranged.
5234 // Rewrite "in const" from "nr" to "rn"
5235 if (StringRef(S).endswith("nr"))
5236 S.replace(S.end()-2, S.end(), "rn");
5237 }
5238
5239 if (PointeeTy->isCharType()) {
5240 // char pointer types should be encoded as '*' unless it is a
5241 // type that has been typedef'd to 'BOOL'.
5242 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
5243 S += '*';
5244 return;
5245 }
5246 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
5247 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5248 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5249 S += '#';
5250 return;
5251 }
5252 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5253 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5254 S += '@';
5255 return;
5256 }
5257 // fall through...
5258 }
5259 S += '^';
5260 getLegacyIntegralTypeEncoding(PointeeTy);
5261
5262 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
5263 NULL);
5264 return;
5265 }
5266
5267 case Type::ConstantArray:
5268 case Type::IncompleteArray:
5269 case Type::VariableArray: {
5270 const ArrayType *AT = cast<ArrayType>(CT);
5271
5272 if (isa<IncompleteArrayType>(AT) && !StructField) {
5273 // Incomplete arrays are encoded as a pointer to the array element.
5274 S += '^';
5275
5276 getObjCEncodingForTypeImpl(AT->getElementType(), S,
5277 false, ExpandStructures, FD);
5278 } else {
5279 S += '[';
5280
5281 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5282 S += llvm::utostr(CAT->getSize().getZExtValue());
5283 else {
5284 //Variable length arrays are encoded as a regular array with 0 elements.
5285 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5286 "Unknown array type!");
5287 S += '0';
5288 }
5289
5290 getObjCEncodingForTypeImpl(AT->getElementType(), S,
5291 false, ExpandStructures, FD);
5292 S += ']';
5293 }
5294 return;
5295 }
5296
5297 case Type::FunctionNoProto:
5298 case Type::FunctionProto:
5299 S += '?';
5300 return;
5301
5302 case Type::Record: {
5303 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
5304 S += RDecl->isUnion() ? '(' : '{';
5305 // Anonymous structures print as '?'
5306 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5307 S += II->getName();
5308 if (ClassTemplateSpecializationDecl *Spec
5309 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5310 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
5311 llvm::raw_string_ostream OS(S);
5312 TemplateSpecializationType::PrintTemplateArgumentList(OS,
5313 TemplateArgs.data(),
5314 TemplateArgs.size(),
5315 (*this).getPrintingPolicy());
5316 }
5317 } else {
5318 S += '?';
5319 }
5320 if (ExpandStructures) {
5321 S += '=';
5322 if (!RDecl->isUnion()) {
5323 getObjCEncodingForStructureImpl(RDecl, S, FD);
5324 } else {
5325 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5326 FieldEnd = RDecl->field_end();
5327 Field != FieldEnd; ++Field) {
5328 if (FD) {
5329 S += '"';
5330 S += Field->getNameAsString();
5331 S += '"';
5332 }
5333
5334 // Special case bit-fields.
5335 if (Field->isBitField()) {
5336 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
5337 *Field);
5338 } else {
5339 QualType qt = Field->getType();
5340 getLegacyIntegralTypeEncoding(qt);
5341 getObjCEncodingForTypeImpl(qt, S, false, true,
5342 FD, /*OutermostType*/false,
5343 /*EncodingProperty*/false,
5344 /*StructField*/true);
5345 }
5346 }
5347 }
5348 }
5349 S += RDecl->isUnion() ? ')' : '}';
5350 return;
5351 }
5352
5353 case Type::BlockPointer: {
5354 const BlockPointerType *BT = T->castAs<BlockPointerType>();
5355 S += "@?"; // Unlike a pointer-to-function, which is "^?".
5356 if (EncodeBlockParameters) {
5357 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
5358
5359 S += '<';
5360 // Block return type
5361 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5362 ExpandPointedToStructures, ExpandStructures,
5363 FD,
5364 false /* OutermostType */,
5365 EncodingProperty,
5366 false /* StructField */,
5367 EncodeBlockParameters,
5368 EncodeClassNames);
5369 // Block self
5370 S += "@?";
5371 // Block parameters
5372 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5373 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5374 E = FPT->arg_type_end(); I && (I != E); ++I) {
5375 getObjCEncodingForTypeImpl(*I, S,
5376 ExpandPointedToStructures,
5377 ExpandStructures,
5378 FD,
5379 false /* OutermostType */,
5380 EncodingProperty,
5381 false /* StructField */,
5382 EncodeBlockParameters,
5383 EncodeClassNames);
5384 }
5385 }
5386 S += '>';
5387 }
5388 return;
5389 }
5390
5391 case Type::ObjCObject:
5392 case Type::ObjCInterface: {
5393 // Ignore protocol qualifiers when mangling at this level.
5394 T = T->castAs<ObjCObjectType>()->getBaseType();
5395
5396 // The assumption seems to be that this assert will succeed
5397 // because nested levels will have filtered out 'id' and 'Class'.
5398 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
5399 // @encode(class_name)
5400 ObjCInterfaceDecl *OI = OIT->getDecl();
5401 S += '{';
5402 const IdentifierInfo *II = OI->getIdentifier();
5403 S += II->getName();
5404 S += '=';
5405 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5406 DeepCollectObjCIvars(OI, true, Ivars);
5407 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5408 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
5409 if (Field->isBitField())
5410 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
5411 else
5412 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5413 false, false, false, false, false,
5414 EncodePointerToObjCTypedef);
5415 }
5416 S += '}';
5417 return;
5418 }
5419
5420 case Type::ObjCObjectPointer: {
5421 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
5422 if (OPT->isObjCIdType()) {
5423 S += '@';
5424 return;
5425 }
5426
5427 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5428 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5429 // Since this is a binary compatibility issue, need to consult with runtime
5430 // folks. Fortunately, this is a *very* obsure construct.
5431 S += '#';
5432 return;
5433 }
5434
5435 if (OPT->isObjCQualifiedIdType()) {
5436 getObjCEncodingForTypeImpl(getObjCIdType(), S,
5437 ExpandPointedToStructures,
5438 ExpandStructures, FD);
5439 if (FD || EncodingProperty || EncodeClassNames) {
5440 // Note that we do extended encoding of protocol qualifer list
5441 // Only when doing ivar or property encoding.
5442 S += '"';
5443 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5444 E = OPT->qual_end(); I != E; ++I) {
5445 S += '<';
5446 S += (*I)->getNameAsString();
5447 S += '>';
5448 }
5449 S += '"';
5450 }
5451 return;
5452 }
5453
5454 QualType PointeeTy = OPT->getPointeeType();
5455 if (!EncodingProperty &&
5456 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5457 !EncodePointerToObjCTypedef) {
5458 // Another historical/compatibility reason.
5459 // We encode the underlying type which comes out as
5460 // {...};
5461 S += '^';
5462 if (FD && OPT->getInterfaceDecl()) {
5463 // Prevent recursive encoding of fields in some rare cases.
5464 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5465 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5466 DeepCollectObjCIvars(OI, true, Ivars);
5467 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5468 if (cast<FieldDecl>(Ivars[i]) == FD) {
5469 S += '{';
5470 S += OI->getIdentifier()->getName();
5471 S += '}';
5472 return;
5473 }
5474 }
5475 }
5476 getObjCEncodingForTypeImpl(PointeeTy, S,
5477 false, ExpandPointedToStructures,
5478 NULL,
5479 false, false, false, false, false,
5480 /*EncodePointerToObjCTypedef*/true);
5481 return;
5482 }
5483
5484 S += '@';
5485 if (OPT->getInterfaceDecl() &&
5486 (FD || EncodingProperty || EncodeClassNames)) {
5487 S += '"';
5488 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
5489 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5490 E = OPT->qual_end(); I != E; ++I) {
5491 S += '<';
5492 S += (*I)->getNameAsString();
5493 S += '>';
5494 }
5495 S += '"';
5496 }
5497 return;
5498 }
5499
5500 // gcc just blithely ignores member pointers.
5501 // FIXME: we shoul do better than that. 'M' is available.
5502 case Type::MemberPointer:
5503 return;
5504
5505 case Type::Vector:
5506 case Type::ExtVector:
5507 // This matches gcc's encoding, even though technically it is
5508 // insufficient.
5509 // FIXME. We should do a better job than gcc.
5510 return;
5511
5512 case Type::Auto:
5513 // We could see an undeduced auto type here during error recovery.
5514 // Just ignore it.
5515 return;
5516
5517 #define ABSTRACT_TYPE(KIND, BASE)
5518 #define TYPE(KIND, BASE)
5519 #define DEPENDENT_TYPE(KIND, BASE) \
5520 case Type::KIND:
5521 #define NON_CANONICAL_TYPE(KIND, BASE) \
5522 case Type::KIND:
5523 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5524 case Type::KIND:
5525 #include "clang/AST/TypeNodes.def"
5526 llvm_unreachable("@encode for dependent type!");
5527 }
5528 llvm_unreachable("bad type kind!");
5529 }
5530
getObjCEncodingForStructureImpl(RecordDecl * RDecl,std::string & S,const FieldDecl * FD,bool includeVBases) const5531 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5532 std::string &S,
5533 const FieldDecl *FD,
5534 bool includeVBases) const {
5535 assert(RDecl && "Expected non-null RecordDecl");
5536 assert(!RDecl->isUnion() && "Should not be called for unions");
5537 if (!RDecl->getDefinition())
5538 return;
5539
5540 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5541 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5542 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5543
5544 if (CXXRec) {
5545 for (CXXRecordDecl::base_class_iterator
5546 BI = CXXRec->bases_begin(),
5547 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5548 if (!BI->isVirtual()) {
5549 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
5550 if (base->isEmpty())
5551 continue;
5552 uint64_t offs = toBits(layout.getBaseClassOffset(base));
5553 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5554 std::make_pair(offs, base));
5555 }
5556 }
5557 }
5558
5559 unsigned i = 0;
5560 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5561 FieldEnd = RDecl->field_end();
5562 Field != FieldEnd; ++Field, ++i) {
5563 uint64_t offs = layout.getFieldOffset(i);
5564 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5565 std::make_pair(offs, *Field));
5566 }
5567
5568 if (CXXRec && includeVBases) {
5569 for (CXXRecordDecl::base_class_iterator
5570 BI = CXXRec->vbases_begin(),
5571 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5572 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
5573 if (base->isEmpty())
5574 continue;
5575 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
5576 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5577 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5578 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5579 std::make_pair(offs, base));
5580 }
5581 }
5582
5583 CharUnits size;
5584 if (CXXRec) {
5585 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5586 } else {
5587 size = layout.getSize();
5588 }
5589
5590 uint64_t CurOffs = 0;
5591 std::multimap<uint64_t, NamedDecl *>::iterator
5592 CurLayObj = FieldOrBaseOffsets.begin();
5593
5594 if (CXXRec && CXXRec->isDynamicClass() &&
5595 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
5596 if (FD) {
5597 S += "\"_vptr$";
5598 std::string recname = CXXRec->getNameAsString();
5599 if (recname.empty()) recname = "?";
5600 S += recname;
5601 S += '"';
5602 }
5603 S += "^^?";
5604 CurOffs += getTypeSize(VoidPtrTy);
5605 }
5606
5607 if (!RDecl->hasFlexibleArrayMember()) {
5608 // Mark the end of the structure.
5609 uint64_t offs = toBits(size);
5610 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5611 std::make_pair(offs, (NamedDecl*)0));
5612 }
5613
5614 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5615 assert(CurOffs <= CurLayObj->first);
5616
5617 if (CurOffs < CurLayObj->first) {
5618 uint64_t padding = CurLayObj->first - CurOffs;
5619 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5620 // packing/alignment of members is different that normal, in which case
5621 // the encoding will be out-of-sync with the real layout.
5622 // If the runtime switches to just consider the size of types without
5623 // taking into account alignment, we could make padding explicit in the
5624 // encoding (e.g. using arrays of chars). The encoding strings would be
5625 // longer then though.
5626 CurOffs += padding;
5627 }
5628
5629 NamedDecl *dcl = CurLayObj->second;
5630 if (dcl == 0)
5631 break; // reached end of structure.
5632
5633 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5634 // We expand the bases without their virtual bases since those are going
5635 // in the initial structure. Note that this differs from gcc which
5636 // expands virtual bases each time one is encountered in the hierarchy,
5637 // making the encoding type bigger than it really is.
5638 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
5639 assert(!base->isEmpty());
5640 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
5641 } else {
5642 FieldDecl *field = cast<FieldDecl>(dcl);
5643 if (FD) {
5644 S += '"';
5645 S += field->getNameAsString();
5646 S += '"';
5647 }
5648
5649 if (field->isBitField()) {
5650 EncodeBitField(this, S, field->getType(), field);
5651 CurOffs += field->getBitWidthValue(*this);
5652 } else {
5653 QualType qt = field->getType();
5654 getLegacyIntegralTypeEncoding(qt);
5655 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5656 /*OutermostType*/false,
5657 /*EncodingProperty*/false,
5658 /*StructField*/true);
5659 CurOffs += getTypeSize(field->getType());
5660 }
5661 }
5662 }
5663 }
5664
getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,std::string & S) const5665 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
5666 std::string& S) const {
5667 if (QT & Decl::OBJC_TQ_In)
5668 S += 'n';
5669 if (QT & Decl::OBJC_TQ_Inout)
5670 S += 'N';
5671 if (QT & Decl::OBJC_TQ_Out)
5672 S += 'o';
5673 if (QT & Decl::OBJC_TQ_Bycopy)
5674 S += 'O';
5675 if (QT & Decl::OBJC_TQ_Byref)
5676 S += 'R';
5677 if (QT & Decl::OBJC_TQ_Oneway)
5678 S += 'V';
5679 }
5680
getObjCIdDecl() const5681 TypedefDecl *ASTContext::getObjCIdDecl() const {
5682 if (!ObjCIdDecl) {
5683 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5684 T = getObjCObjectPointerType(T);
5685 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5686 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5687 getTranslationUnitDecl(),
5688 SourceLocation(), SourceLocation(),
5689 &Idents.get("id"), IdInfo);
5690 }
5691
5692 return ObjCIdDecl;
5693 }
5694
getObjCSelDecl() const5695 TypedefDecl *ASTContext::getObjCSelDecl() const {
5696 if (!ObjCSelDecl) {
5697 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5698 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5699 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5700 getTranslationUnitDecl(),
5701 SourceLocation(), SourceLocation(),
5702 &Idents.get("SEL"), SelInfo);
5703 }
5704 return ObjCSelDecl;
5705 }
5706
getObjCClassDecl() const5707 TypedefDecl *ASTContext::getObjCClassDecl() const {
5708 if (!ObjCClassDecl) {
5709 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5710 T = getObjCObjectPointerType(T);
5711 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5712 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5713 getTranslationUnitDecl(),
5714 SourceLocation(), SourceLocation(),
5715 &Idents.get("Class"), ClassInfo);
5716 }
5717
5718 return ObjCClassDecl;
5719 }
5720
getObjCProtocolDecl() const5721 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5722 if (!ObjCProtocolClassDecl) {
5723 ObjCProtocolClassDecl
5724 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5725 SourceLocation(),
5726 &Idents.get("Protocol"),
5727 /*PrevDecl=*/0,
5728 SourceLocation(), true);
5729 }
5730
5731 return ObjCProtocolClassDecl;
5732 }
5733
5734 //===----------------------------------------------------------------------===//
5735 // __builtin_va_list Construction Functions
5736 //===----------------------------------------------------------------------===//
5737
CreateCharPtrBuiltinVaListDecl(const ASTContext * Context)5738 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5739 // typedef char* __builtin_va_list;
5740 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5741 TypeSourceInfo *TInfo
5742 = Context->getTrivialTypeSourceInfo(CharPtrType);
5743
5744 TypedefDecl *VaListTypeDecl
5745 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5746 Context->getTranslationUnitDecl(),
5747 SourceLocation(), SourceLocation(),
5748 &Context->Idents.get("__builtin_va_list"),
5749 TInfo);
5750 return VaListTypeDecl;
5751 }
5752
CreateVoidPtrBuiltinVaListDecl(const ASTContext * Context)5753 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5754 // typedef void* __builtin_va_list;
5755 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5756 TypeSourceInfo *TInfo
5757 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5758
5759 TypedefDecl *VaListTypeDecl
5760 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5761 Context->getTranslationUnitDecl(),
5762 SourceLocation(), SourceLocation(),
5763 &Context->Idents.get("__builtin_va_list"),
5764 TInfo);
5765 return VaListTypeDecl;
5766 }
5767
5768 static TypedefDecl *
CreateAArch64ABIBuiltinVaListDecl(const ASTContext * Context)5769 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
5770 RecordDecl *VaListTagDecl;
5771 if (Context->getLangOpts().CPlusPlus) {
5772 // namespace std { struct __va_list {
5773 NamespaceDecl *NS;
5774 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5775 Context->getTranslationUnitDecl(),
5776 /*Inline*/false, SourceLocation(),
5777 SourceLocation(), &Context->Idents.get("std"),
5778 /*PrevDecl*/0);
5779
5780 VaListTagDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5781 Context->getTranslationUnitDecl(),
5782 SourceLocation(), SourceLocation(),
5783 &Context->Idents.get("__va_list"));
5784 VaListTagDecl->setDeclContext(NS);
5785 } else {
5786 // struct __va_list
5787 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5788 Context->getTranslationUnitDecl(),
5789 &Context->Idents.get("__va_list"));
5790 }
5791
5792 VaListTagDecl->startDefinition();
5793
5794 const size_t NumFields = 5;
5795 QualType FieldTypes[NumFields];
5796 const char *FieldNames[NumFields];
5797
5798 // void *__stack;
5799 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5800 FieldNames[0] = "__stack";
5801
5802 // void *__gr_top;
5803 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5804 FieldNames[1] = "__gr_top";
5805
5806 // void *__vr_top;
5807 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5808 FieldNames[2] = "__vr_top";
5809
5810 // int __gr_offs;
5811 FieldTypes[3] = Context->IntTy;
5812 FieldNames[3] = "__gr_offs";
5813
5814 // int __vr_offs;
5815 FieldTypes[4] = Context->IntTy;
5816 FieldNames[4] = "__vr_offs";
5817
5818 // Create fields
5819 for (unsigned i = 0; i < NumFields; ++i) {
5820 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5821 VaListTagDecl,
5822 SourceLocation(),
5823 SourceLocation(),
5824 &Context->Idents.get(FieldNames[i]),
5825 FieldTypes[i], /*TInfo=*/0,
5826 /*BitWidth=*/0,
5827 /*Mutable=*/false,
5828 ICIS_NoInit);
5829 Field->setAccess(AS_public);
5830 VaListTagDecl->addDecl(Field);
5831 }
5832 VaListTagDecl->completeDefinition();
5833 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5834 Context->VaListTagTy = VaListTagType;
5835
5836 // } __builtin_va_list;
5837 TypedefDecl *VaListTypedefDecl
5838 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5839 Context->getTranslationUnitDecl(),
5840 SourceLocation(), SourceLocation(),
5841 &Context->Idents.get("__builtin_va_list"),
5842 Context->getTrivialTypeSourceInfo(VaListTagType));
5843
5844 return VaListTypedefDecl;
5845 }
5846
CreatePowerABIBuiltinVaListDecl(const ASTContext * Context)5847 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5848 // typedef struct __va_list_tag {
5849 RecordDecl *VaListTagDecl;
5850
5851 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5852 Context->getTranslationUnitDecl(),
5853 &Context->Idents.get("__va_list_tag"));
5854 VaListTagDecl->startDefinition();
5855
5856 const size_t NumFields = 5;
5857 QualType FieldTypes[NumFields];
5858 const char *FieldNames[NumFields];
5859
5860 // unsigned char gpr;
5861 FieldTypes[0] = Context->UnsignedCharTy;
5862 FieldNames[0] = "gpr";
5863
5864 // unsigned char fpr;
5865 FieldTypes[1] = Context->UnsignedCharTy;
5866 FieldNames[1] = "fpr";
5867
5868 // unsigned short reserved;
5869 FieldTypes[2] = Context->UnsignedShortTy;
5870 FieldNames[2] = "reserved";
5871
5872 // void* overflow_arg_area;
5873 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5874 FieldNames[3] = "overflow_arg_area";
5875
5876 // void* reg_save_area;
5877 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5878 FieldNames[4] = "reg_save_area";
5879
5880 // Create fields
5881 for (unsigned i = 0; i < NumFields; ++i) {
5882 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5883 SourceLocation(),
5884 SourceLocation(),
5885 &Context->Idents.get(FieldNames[i]),
5886 FieldTypes[i], /*TInfo=*/0,
5887 /*BitWidth=*/0,
5888 /*Mutable=*/false,
5889 ICIS_NoInit);
5890 Field->setAccess(AS_public);
5891 VaListTagDecl->addDecl(Field);
5892 }
5893 VaListTagDecl->completeDefinition();
5894 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5895 Context->VaListTagTy = VaListTagType;
5896
5897 // } __va_list_tag;
5898 TypedefDecl *VaListTagTypedefDecl
5899 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5900 Context->getTranslationUnitDecl(),
5901 SourceLocation(), SourceLocation(),
5902 &Context->Idents.get("__va_list_tag"),
5903 Context->getTrivialTypeSourceInfo(VaListTagType));
5904 QualType VaListTagTypedefType =
5905 Context->getTypedefType(VaListTagTypedefDecl);
5906
5907 // typedef __va_list_tag __builtin_va_list[1];
5908 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5909 QualType VaListTagArrayType
5910 = Context->getConstantArrayType(VaListTagTypedefType,
5911 Size, ArrayType::Normal, 0);
5912 TypeSourceInfo *TInfo
5913 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5914 TypedefDecl *VaListTypedefDecl
5915 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5916 Context->getTranslationUnitDecl(),
5917 SourceLocation(), SourceLocation(),
5918 &Context->Idents.get("__builtin_va_list"),
5919 TInfo);
5920
5921 return VaListTypedefDecl;
5922 }
5923
5924 static TypedefDecl *
CreateX86_64ABIBuiltinVaListDecl(const ASTContext * Context)5925 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5926 // typedef struct __va_list_tag {
5927 RecordDecl *VaListTagDecl;
5928 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5929 Context->getTranslationUnitDecl(),
5930 &Context->Idents.get("__va_list_tag"));
5931 VaListTagDecl->startDefinition();
5932
5933 const size_t NumFields = 4;
5934 QualType FieldTypes[NumFields];
5935 const char *FieldNames[NumFields];
5936
5937 // unsigned gp_offset;
5938 FieldTypes[0] = Context->UnsignedIntTy;
5939 FieldNames[0] = "gp_offset";
5940
5941 // unsigned fp_offset;
5942 FieldTypes[1] = Context->UnsignedIntTy;
5943 FieldNames[1] = "fp_offset";
5944
5945 // void* overflow_arg_area;
5946 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5947 FieldNames[2] = "overflow_arg_area";
5948
5949 // void* reg_save_area;
5950 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5951 FieldNames[3] = "reg_save_area";
5952
5953 // Create fields
5954 for (unsigned i = 0; i < NumFields; ++i) {
5955 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5956 VaListTagDecl,
5957 SourceLocation(),
5958 SourceLocation(),
5959 &Context->Idents.get(FieldNames[i]),
5960 FieldTypes[i], /*TInfo=*/0,
5961 /*BitWidth=*/0,
5962 /*Mutable=*/false,
5963 ICIS_NoInit);
5964 Field->setAccess(AS_public);
5965 VaListTagDecl->addDecl(Field);
5966 }
5967 VaListTagDecl->completeDefinition();
5968 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5969 Context->VaListTagTy = VaListTagType;
5970
5971 // } __va_list_tag;
5972 TypedefDecl *VaListTagTypedefDecl
5973 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5974 Context->getTranslationUnitDecl(),
5975 SourceLocation(), SourceLocation(),
5976 &Context->Idents.get("__va_list_tag"),
5977 Context->getTrivialTypeSourceInfo(VaListTagType));
5978 QualType VaListTagTypedefType =
5979 Context->getTypedefType(VaListTagTypedefDecl);
5980
5981 // typedef __va_list_tag __builtin_va_list[1];
5982 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5983 QualType VaListTagArrayType
5984 = Context->getConstantArrayType(VaListTagTypedefType,
5985 Size, ArrayType::Normal,0);
5986 TypeSourceInfo *TInfo
5987 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5988 TypedefDecl *VaListTypedefDecl
5989 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5990 Context->getTranslationUnitDecl(),
5991 SourceLocation(), SourceLocation(),
5992 &Context->Idents.get("__builtin_va_list"),
5993 TInfo);
5994
5995 return VaListTypedefDecl;
5996 }
5997
CreatePNaClABIBuiltinVaListDecl(const ASTContext * Context)5998 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5999 // typedef int __builtin_va_list[4];
6000 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6001 QualType IntArrayType
6002 = Context->getConstantArrayType(Context->IntTy,
6003 Size, ArrayType::Normal, 0);
6004 TypedefDecl *VaListTypedefDecl
6005 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6006 Context->getTranslationUnitDecl(),
6007 SourceLocation(), SourceLocation(),
6008 &Context->Idents.get("__builtin_va_list"),
6009 Context->getTrivialTypeSourceInfo(IntArrayType));
6010
6011 return VaListTypedefDecl;
6012 }
6013
6014 static TypedefDecl *
CreateAAPCSABIBuiltinVaListDecl(const ASTContext * Context)6015 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
6016 RecordDecl *VaListDecl;
6017 if (Context->getLangOpts().CPlusPlus) {
6018 // namespace std { struct __va_list {
6019 NamespaceDecl *NS;
6020 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6021 Context->getTranslationUnitDecl(),
6022 /*Inline*/false, SourceLocation(),
6023 SourceLocation(), &Context->Idents.get("std"),
6024 /*PrevDecl*/0);
6025
6026 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
6027 Context->getTranslationUnitDecl(),
6028 SourceLocation(), SourceLocation(),
6029 &Context->Idents.get("__va_list"));
6030
6031 VaListDecl->setDeclContext(NS);
6032
6033 } else {
6034 // struct __va_list {
6035 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
6036 Context->getTranslationUnitDecl(),
6037 &Context->Idents.get("__va_list"));
6038 }
6039
6040 VaListDecl->startDefinition();
6041
6042 // void * __ap;
6043 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6044 VaListDecl,
6045 SourceLocation(),
6046 SourceLocation(),
6047 &Context->Idents.get("__ap"),
6048 Context->getPointerType(Context->VoidTy),
6049 /*TInfo=*/0,
6050 /*BitWidth=*/0,
6051 /*Mutable=*/false,
6052 ICIS_NoInit);
6053 Field->setAccess(AS_public);
6054 VaListDecl->addDecl(Field);
6055
6056 // };
6057 VaListDecl->completeDefinition();
6058
6059 // typedef struct __va_list __builtin_va_list;
6060 TypeSourceInfo *TInfo
6061 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
6062
6063 TypedefDecl *VaListTypeDecl
6064 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6065 Context->getTranslationUnitDecl(),
6066 SourceLocation(), SourceLocation(),
6067 &Context->Idents.get("__builtin_va_list"),
6068 TInfo);
6069
6070 return VaListTypeDecl;
6071 }
6072
6073 static TypedefDecl *
CreateSystemZBuiltinVaListDecl(const ASTContext * Context)6074 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6075 // typedef struct __va_list_tag {
6076 RecordDecl *VaListTagDecl;
6077 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
6078 Context->getTranslationUnitDecl(),
6079 &Context->Idents.get("__va_list_tag"));
6080 VaListTagDecl->startDefinition();
6081
6082 const size_t NumFields = 4;
6083 QualType FieldTypes[NumFields];
6084 const char *FieldNames[NumFields];
6085
6086 // long __gpr;
6087 FieldTypes[0] = Context->LongTy;
6088 FieldNames[0] = "__gpr";
6089
6090 // long __fpr;
6091 FieldTypes[1] = Context->LongTy;
6092 FieldNames[1] = "__fpr";
6093
6094 // void *__overflow_arg_area;
6095 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6096 FieldNames[2] = "__overflow_arg_area";
6097
6098 // void *__reg_save_area;
6099 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6100 FieldNames[3] = "__reg_save_area";
6101
6102 // Create fields
6103 for (unsigned i = 0; i < NumFields; ++i) {
6104 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6105 VaListTagDecl,
6106 SourceLocation(),
6107 SourceLocation(),
6108 &Context->Idents.get(FieldNames[i]),
6109 FieldTypes[i], /*TInfo=*/0,
6110 /*BitWidth=*/0,
6111 /*Mutable=*/false,
6112 ICIS_NoInit);
6113 Field->setAccess(AS_public);
6114 VaListTagDecl->addDecl(Field);
6115 }
6116 VaListTagDecl->completeDefinition();
6117 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6118 Context->VaListTagTy = VaListTagType;
6119
6120 // } __va_list_tag;
6121 TypedefDecl *VaListTagTypedefDecl
6122 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6123 Context->getTranslationUnitDecl(),
6124 SourceLocation(), SourceLocation(),
6125 &Context->Idents.get("__va_list_tag"),
6126 Context->getTrivialTypeSourceInfo(VaListTagType));
6127 QualType VaListTagTypedefType =
6128 Context->getTypedefType(VaListTagTypedefDecl);
6129
6130 // typedef __va_list_tag __builtin_va_list[1];
6131 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6132 QualType VaListTagArrayType
6133 = Context->getConstantArrayType(VaListTagTypedefType,
6134 Size, ArrayType::Normal,0);
6135 TypeSourceInfo *TInfo
6136 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
6137 TypedefDecl *VaListTypedefDecl
6138 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6139 Context->getTranslationUnitDecl(),
6140 SourceLocation(), SourceLocation(),
6141 &Context->Idents.get("__builtin_va_list"),
6142 TInfo);
6143
6144 return VaListTypedefDecl;
6145 }
6146
CreateVaListDecl(const ASTContext * Context,TargetInfo::BuiltinVaListKind Kind)6147 static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6148 TargetInfo::BuiltinVaListKind Kind) {
6149 switch (Kind) {
6150 case TargetInfo::CharPtrBuiltinVaList:
6151 return CreateCharPtrBuiltinVaListDecl(Context);
6152 case TargetInfo::VoidPtrBuiltinVaList:
6153 return CreateVoidPtrBuiltinVaListDecl(Context);
6154 case TargetInfo::AArch64ABIBuiltinVaList:
6155 return CreateAArch64ABIBuiltinVaListDecl(Context);
6156 case TargetInfo::PowerABIBuiltinVaList:
6157 return CreatePowerABIBuiltinVaListDecl(Context);
6158 case TargetInfo::X86_64ABIBuiltinVaList:
6159 return CreateX86_64ABIBuiltinVaListDecl(Context);
6160 case TargetInfo::PNaClABIBuiltinVaList:
6161 return CreatePNaClABIBuiltinVaListDecl(Context);
6162 case TargetInfo::AAPCSABIBuiltinVaList:
6163 return CreateAAPCSABIBuiltinVaListDecl(Context);
6164 case TargetInfo::SystemZBuiltinVaList:
6165 return CreateSystemZBuiltinVaListDecl(Context);
6166 }
6167
6168 llvm_unreachable("Unhandled __builtin_va_list type kind");
6169 }
6170
getBuiltinVaListDecl() const6171 TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
6172 if (!BuiltinVaListDecl)
6173 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
6174
6175 return BuiltinVaListDecl;
6176 }
6177
getVaListTagType() const6178 QualType ASTContext::getVaListTagType() const {
6179 // Force the creation of VaListTagTy by building the __builtin_va_list
6180 // declaration.
6181 if (VaListTagTy.isNull())
6182 (void) getBuiltinVaListDecl();
6183
6184 return VaListTagTy;
6185 }
6186
setObjCConstantStringInterface(ObjCInterfaceDecl * Decl)6187 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
6188 assert(ObjCConstantStringType.isNull() &&
6189 "'NSConstantString' type already set!");
6190
6191 ObjCConstantStringType = getObjCInterfaceType(Decl);
6192 }
6193
6194 /// \brief Retrieve the template name that corresponds to a non-empty
6195 /// lookup.
6196 TemplateName
getOverloadedTemplateName(UnresolvedSetIterator Begin,UnresolvedSetIterator End) const6197 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6198 UnresolvedSetIterator End) const {
6199 unsigned size = End - Begin;
6200 assert(size > 1 && "set is not overloaded!");
6201
6202 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6203 size * sizeof(FunctionTemplateDecl*));
6204 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6205
6206 NamedDecl **Storage = OT->getStorage();
6207 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
6208 NamedDecl *D = *I;
6209 assert(isa<FunctionTemplateDecl>(D) ||
6210 (isa<UsingShadowDecl>(D) &&
6211 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6212 *Storage++ = D;
6213 }
6214
6215 return TemplateName(OT);
6216 }
6217
6218 /// \brief Retrieve the template name that represents a qualified
6219 /// template name such as \c std::vector.
6220 TemplateName
getQualifiedTemplateName(NestedNameSpecifier * NNS,bool TemplateKeyword,TemplateDecl * Template) const6221 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6222 bool TemplateKeyword,
6223 TemplateDecl *Template) const {
6224 assert(NNS && "Missing nested-name-specifier in qualified template name");
6225
6226 // FIXME: Canonicalization?
6227 llvm::FoldingSetNodeID ID;
6228 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6229
6230 void *InsertPos = 0;
6231 QualifiedTemplateName *QTN =
6232 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6233 if (!QTN) {
6234 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6235 QualifiedTemplateName(NNS, TemplateKeyword, Template);
6236 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6237 }
6238
6239 return TemplateName(QTN);
6240 }
6241
6242 /// \brief Retrieve the template name that represents a dependent
6243 /// template name such as \c MetaFun::template apply.
6244 TemplateName
getDependentTemplateName(NestedNameSpecifier * NNS,const IdentifierInfo * Name) const6245 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6246 const IdentifierInfo *Name) const {
6247 assert((!NNS || NNS->isDependent()) &&
6248 "Nested name specifier must be dependent");
6249
6250 llvm::FoldingSetNodeID ID;
6251 DependentTemplateName::Profile(ID, NNS, Name);
6252
6253 void *InsertPos = 0;
6254 DependentTemplateName *QTN =
6255 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6256
6257 if (QTN)
6258 return TemplateName(QTN);
6259
6260 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6261 if (CanonNNS == NNS) {
6262 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6263 DependentTemplateName(NNS, Name);
6264 } else {
6265 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
6266 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6267 DependentTemplateName(NNS, Name, Canon);
6268 DependentTemplateName *CheckQTN =
6269 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6270 assert(!CheckQTN && "Dependent type name canonicalization broken");
6271 (void)CheckQTN;
6272 }
6273
6274 DependentTemplateNames.InsertNode(QTN, InsertPos);
6275 return TemplateName(QTN);
6276 }
6277
6278 /// \brief Retrieve the template name that represents a dependent
6279 /// template name such as \c MetaFun::template operator+.
6280 TemplateName
getDependentTemplateName(NestedNameSpecifier * NNS,OverloadedOperatorKind Operator) const6281 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6282 OverloadedOperatorKind Operator) const {
6283 assert((!NNS || NNS->isDependent()) &&
6284 "Nested name specifier must be dependent");
6285
6286 llvm::FoldingSetNodeID ID;
6287 DependentTemplateName::Profile(ID, NNS, Operator);
6288
6289 void *InsertPos = 0;
6290 DependentTemplateName *QTN
6291 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6292
6293 if (QTN)
6294 return TemplateName(QTN);
6295
6296 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6297 if (CanonNNS == NNS) {
6298 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6299 DependentTemplateName(NNS, Operator);
6300 } else {
6301 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
6302 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6303 DependentTemplateName(NNS, Operator, Canon);
6304
6305 DependentTemplateName *CheckQTN
6306 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6307 assert(!CheckQTN && "Dependent template name canonicalization broken");
6308 (void)CheckQTN;
6309 }
6310
6311 DependentTemplateNames.InsertNode(QTN, InsertPos);
6312 return TemplateName(QTN);
6313 }
6314
6315 TemplateName
getSubstTemplateTemplateParm(TemplateTemplateParmDecl * param,TemplateName replacement) const6316 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6317 TemplateName replacement) const {
6318 llvm::FoldingSetNodeID ID;
6319 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6320
6321 void *insertPos = 0;
6322 SubstTemplateTemplateParmStorage *subst
6323 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6324
6325 if (!subst) {
6326 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6327 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6328 }
6329
6330 return TemplateName(subst);
6331 }
6332
6333 TemplateName
getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl * Param,const TemplateArgument & ArgPack) const6334 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6335 const TemplateArgument &ArgPack) const {
6336 ASTContext &Self = const_cast<ASTContext &>(*this);
6337 llvm::FoldingSetNodeID ID;
6338 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6339
6340 void *InsertPos = 0;
6341 SubstTemplateTemplateParmPackStorage *Subst
6342 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6343
6344 if (!Subst) {
6345 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
6346 ArgPack.pack_size(),
6347 ArgPack.pack_begin());
6348 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6349 }
6350
6351 return TemplateName(Subst);
6352 }
6353
6354 /// getFromTargetType - Given one of the integer types provided by
6355 /// TargetInfo, produce the corresponding type. The unsigned @p Type
6356 /// is actually a value of type @c TargetInfo::IntType.
getFromTargetType(unsigned Type) const6357 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
6358 switch (Type) {
6359 case TargetInfo::NoInt: return CanQualType();
6360 case TargetInfo::SignedChar: return SignedCharTy;
6361 case TargetInfo::UnsignedChar: return UnsignedCharTy;
6362 case TargetInfo::SignedShort: return ShortTy;
6363 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6364 case TargetInfo::SignedInt: return IntTy;
6365 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6366 case TargetInfo::SignedLong: return LongTy;
6367 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6368 case TargetInfo::SignedLongLong: return LongLongTy;
6369 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6370 }
6371
6372 llvm_unreachable("Unhandled TargetInfo::IntType value");
6373 }
6374
6375 //===----------------------------------------------------------------------===//
6376 // Type Predicates.
6377 //===----------------------------------------------------------------------===//
6378
6379 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6380 /// garbage collection attribute.
6381 ///
getObjCGCAttrKind(QualType Ty) const6382 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
6383 if (getLangOpts().getGC() == LangOptions::NonGC)
6384 return Qualifiers::GCNone;
6385
6386 assert(getLangOpts().ObjC1);
6387 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6388
6389 // Default behaviour under objective-C's gc is for ObjC pointers
6390 // (or pointers to them) be treated as though they were declared
6391 // as __strong.
6392 if (GCAttrs == Qualifiers::GCNone) {
6393 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6394 return Qualifiers::Strong;
6395 else if (Ty->isPointerType())
6396 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6397 } else {
6398 // It's not valid to set GC attributes on anything that isn't a
6399 // pointer.
6400 #ifndef NDEBUG
6401 QualType CT = Ty->getCanonicalTypeInternal();
6402 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6403 CT = AT->getElementType();
6404 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6405 #endif
6406 }
6407 return GCAttrs;
6408 }
6409
6410 //===----------------------------------------------------------------------===//
6411 // Type Compatibility Testing
6412 //===----------------------------------------------------------------------===//
6413
6414 /// areCompatVectorTypes - Return true if the two specified vector types are
6415 /// compatible.
areCompatVectorTypes(const VectorType * LHS,const VectorType * RHS)6416 static bool areCompatVectorTypes(const VectorType *LHS,
6417 const VectorType *RHS) {
6418 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
6419 return LHS->getElementType() == RHS->getElementType() &&
6420 LHS->getNumElements() == RHS->getNumElements();
6421 }
6422
areCompatibleVectorTypes(QualType FirstVec,QualType SecondVec)6423 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6424 QualType SecondVec) {
6425 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6426 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6427
6428 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6429 return true;
6430
6431 // Treat Neon vector types and most AltiVec vector types as if they are the
6432 // equivalent GCC vector types.
6433 const VectorType *First = FirstVec->getAs<VectorType>();
6434 const VectorType *Second = SecondVec->getAs<VectorType>();
6435 if (First->getNumElements() == Second->getNumElements() &&
6436 hasSameType(First->getElementType(), Second->getElementType()) &&
6437 First->getVectorKind() != VectorType::AltiVecPixel &&
6438 First->getVectorKind() != VectorType::AltiVecBool &&
6439 Second->getVectorKind() != VectorType::AltiVecPixel &&
6440 Second->getVectorKind() != VectorType::AltiVecBool)
6441 return true;
6442
6443 return false;
6444 }
6445
6446 //===----------------------------------------------------------------------===//
6447 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6448 //===----------------------------------------------------------------------===//
6449
6450 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6451 /// inheritance hierarchy of 'rProto'.
6452 bool
ProtocolCompatibleWithProtocol(ObjCProtocolDecl * lProto,ObjCProtocolDecl * rProto) const6453 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6454 ObjCProtocolDecl *rProto) const {
6455 if (declaresSameEntity(lProto, rProto))
6456 return true;
6457 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6458 E = rProto->protocol_end(); PI != E; ++PI)
6459 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6460 return true;
6461 return false;
6462 }
6463
6464 /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6465 /// Class<pr1, ...>.
ObjCQualifiedClassTypesAreCompatible(QualType lhs,QualType rhs)6466 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6467 QualType rhs) {
6468 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6469 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6470 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6471
6472 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6473 E = lhsQID->qual_end(); I != E; ++I) {
6474 bool match = false;
6475 ObjCProtocolDecl *lhsProto = *I;
6476 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6477 E = rhsOPT->qual_end(); J != E; ++J) {
6478 ObjCProtocolDecl *rhsProto = *J;
6479 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6480 match = true;
6481 break;
6482 }
6483 }
6484 if (!match)
6485 return false;
6486 }
6487 return true;
6488 }
6489
6490 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6491 /// ObjCQualifiedIDType.
ObjCQualifiedIdTypesAreCompatible(QualType lhs,QualType rhs,bool compare)6492 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6493 bool compare) {
6494 // Allow id<P..> and an 'id' or void* type in all cases.
6495 if (lhs->isVoidPointerType() ||
6496 lhs->isObjCIdType() || lhs->isObjCClassType())
6497 return true;
6498 else if (rhs->isVoidPointerType() ||
6499 rhs->isObjCIdType() || rhs->isObjCClassType())
6500 return true;
6501
6502 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
6503 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6504
6505 if (!rhsOPT) return false;
6506
6507 if (rhsOPT->qual_empty()) {
6508 // If the RHS is a unqualified interface pointer "NSString*",
6509 // make sure we check the class hierarchy.
6510 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6511 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6512 E = lhsQID->qual_end(); I != E; ++I) {
6513 // when comparing an id<P> on lhs with a static type on rhs,
6514 // see if static class implements all of id's protocols, directly or
6515 // through its super class and categories.
6516 if (!rhsID->ClassImplementsProtocol(*I, true))
6517 return false;
6518 }
6519 }
6520 // If there are no qualifiers and no interface, we have an 'id'.
6521 return true;
6522 }
6523 // Both the right and left sides have qualifiers.
6524 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6525 E = lhsQID->qual_end(); I != E; ++I) {
6526 ObjCProtocolDecl *lhsProto = *I;
6527 bool match = false;
6528
6529 // when comparing an id<P> on lhs with a static type on rhs,
6530 // see if static class implements all of id's protocols, directly or
6531 // through its super class and categories.
6532 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6533 E = rhsOPT->qual_end(); J != E; ++J) {
6534 ObjCProtocolDecl *rhsProto = *J;
6535 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6536 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6537 match = true;
6538 break;
6539 }
6540 }
6541 // If the RHS is a qualified interface pointer "NSString<P>*",
6542 // make sure we check the class hierarchy.
6543 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6544 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6545 E = lhsQID->qual_end(); I != E; ++I) {
6546 // when comparing an id<P> on lhs with a static type on rhs,
6547 // see if static class implements all of id's protocols, directly or
6548 // through its super class and categories.
6549 if (rhsID->ClassImplementsProtocol(*I, true)) {
6550 match = true;
6551 break;
6552 }
6553 }
6554 }
6555 if (!match)
6556 return false;
6557 }
6558
6559 return true;
6560 }
6561
6562 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6563 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6564
6565 if (const ObjCObjectPointerType *lhsOPT =
6566 lhs->getAsObjCInterfacePointerType()) {
6567 // If both the right and left sides have qualifiers.
6568 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6569 E = lhsOPT->qual_end(); I != E; ++I) {
6570 ObjCProtocolDecl *lhsProto = *I;
6571 bool match = false;
6572
6573 // when comparing an id<P> on rhs with a static type on lhs,
6574 // see if static class implements all of id's protocols, directly or
6575 // through its super class and categories.
6576 // First, lhs protocols in the qualifier list must be found, direct
6577 // or indirect in rhs's qualifier list or it is a mismatch.
6578 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6579 E = rhsQID->qual_end(); J != E; ++J) {
6580 ObjCProtocolDecl *rhsProto = *J;
6581 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6582 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6583 match = true;
6584 break;
6585 }
6586 }
6587 if (!match)
6588 return false;
6589 }
6590
6591 // Static class's protocols, or its super class or category protocols
6592 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6593 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6594 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6595 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6596 // This is rather dubious but matches gcc's behavior. If lhs has
6597 // no type qualifier and its class has no static protocol(s)
6598 // assume that it is mismatch.
6599 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6600 return false;
6601 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6602 LHSInheritedProtocols.begin(),
6603 E = LHSInheritedProtocols.end(); I != E; ++I) {
6604 bool match = false;
6605 ObjCProtocolDecl *lhsProto = (*I);
6606 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6607 E = rhsQID->qual_end(); J != E; ++J) {
6608 ObjCProtocolDecl *rhsProto = *J;
6609 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6610 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6611 match = true;
6612 break;
6613 }
6614 }
6615 if (!match)
6616 return false;
6617 }
6618 }
6619 return true;
6620 }
6621 return false;
6622 }
6623
6624 /// canAssignObjCInterfaces - Return true if the two interface types are
6625 /// compatible for assignment from RHS to LHS. This handles validation of any
6626 /// protocol qualifiers on the LHS or RHS.
6627 ///
canAssignObjCInterfaces(const ObjCObjectPointerType * LHSOPT,const ObjCObjectPointerType * RHSOPT)6628 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6629 const ObjCObjectPointerType *RHSOPT) {
6630 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6631 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6632
6633 // If either type represents the built-in 'id' or 'Class' types, return true.
6634 if (LHS->isObjCUnqualifiedIdOrClass() ||
6635 RHS->isObjCUnqualifiedIdOrClass())
6636 return true;
6637
6638 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
6639 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6640 QualType(RHSOPT,0),
6641 false);
6642
6643 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6644 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6645 QualType(RHSOPT,0));
6646
6647 // If we have 2 user-defined types, fall into that path.
6648 if (LHS->getInterface() && RHS->getInterface())
6649 return canAssignObjCInterfaces(LHS, RHS);
6650
6651 return false;
6652 }
6653
6654 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
6655 /// for providing type-safety for objective-c pointers used to pass/return
6656 /// arguments in block literals. When passed as arguments, passing 'A*' where
6657 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6658 /// not OK. For the return type, the opposite is not OK.
canAssignObjCInterfacesInBlockPointer(const ObjCObjectPointerType * LHSOPT,const ObjCObjectPointerType * RHSOPT,bool BlockReturnType)6659 bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6660 const ObjCObjectPointerType *LHSOPT,
6661 const ObjCObjectPointerType *RHSOPT,
6662 bool BlockReturnType) {
6663 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
6664 return true;
6665
6666 if (LHSOPT->isObjCBuiltinType()) {
6667 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6668 }
6669
6670 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
6671 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6672 QualType(RHSOPT,0),
6673 false);
6674
6675 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6676 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6677 if (LHS && RHS) { // We have 2 user-defined types.
6678 if (LHS != RHS) {
6679 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
6680 return BlockReturnType;
6681 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
6682 return !BlockReturnType;
6683 }
6684 else
6685 return true;
6686 }
6687 return false;
6688 }
6689
6690 /// getIntersectionOfProtocols - This routine finds the intersection of set
6691 /// of protocols inherited from two distinct objective-c pointer objects.
6692 /// It is used to build composite qualifier list of the composite type of
6693 /// the conditional expression involving two objective-c pointer objects.
6694 static
getIntersectionOfProtocols(ASTContext & Context,const ObjCObjectPointerType * LHSOPT,const ObjCObjectPointerType * RHSOPT,SmallVectorImpl<ObjCProtocolDecl * > & IntersectionOfProtocols)6695 void getIntersectionOfProtocols(ASTContext &Context,
6696 const ObjCObjectPointerType *LHSOPT,
6697 const ObjCObjectPointerType *RHSOPT,
6698 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
6699
6700 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6701 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6702 assert(LHS->getInterface() && "LHS must have an interface base");
6703 assert(RHS->getInterface() && "RHS must have an interface base");
6704
6705 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6706 unsigned LHSNumProtocols = LHS->getNumProtocols();
6707 if (LHSNumProtocols > 0)
6708 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6709 else {
6710 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6711 Context.CollectInheritedProtocols(LHS->getInterface(),
6712 LHSInheritedProtocols);
6713 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6714 LHSInheritedProtocols.end());
6715 }
6716
6717 unsigned RHSNumProtocols = RHS->getNumProtocols();
6718 if (RHSNumProtocols > 0) {
6719 ObjCProtocolDecl **RHSProtocols =
6720 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
6721 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6722 if (InheritedProtocolSet.count(RHSProtocols[i]))
6723 IntersectionOfProtocols.push_back(RHSProtocols[i]);
6724 } else {
6725 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
6726 Context.CollectInheritedProtocols(RHS->getInterface(),
6727 RHSInheritedProtocols);
6728 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6729 RHSInheritedProtocols.begin(),
6730 E = RHSInheritedProtocols.end(); I != E; ++I)
6731 if (InheritedProtocolSet.count((*I)))
6732 IntersectionOfProtocols.push_back((*I));
6733 }
6734 }
6735
6736 /// areCommonBaseCompatible - Returns common base class of the two classes if
6737 /// one found. Note that this is O'2 algorithm. But it will be called as the
6738 /// last type comparison in a ?-exp of ObjC pointer types before a
6739 /// warning is issued. So, its invokation is extremely rare.
areCommonBaseCompatible(const ObjCObjectPointerType * Lptr,const ObjCObjectPointerType * Rptr)6740 QualType ASTContext::areCommonBaseCompatible(
6741 const ObjCObjectPointerType *Lptr,
6742 const ObjCObjectPointerType *Rptr) {
6743 const ObjCObjectType *LHS = Lptr->getObjectType();
6744 const ObjCObjectType *RHS = Rptr->getObjectType();
6745 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6746 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
6747 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
6748 return QualType();
6749
6750 do {
6751 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
6752 if (canAssignObjCInterfaces(LHS, RHS)) {
6753 SmallVector<ObjCProtocolDecl *, 8> Protocols;
6754 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6755
6756 QualType Result = QualType(LHS, 0);
6757 if (!Protocols.empty())
6758 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6759 Result = getObjCObjectPointerType(Result);
6760 return Result;
6761 }
6762 } while ((LDecl = LDecl->getSuperClass()));
6763
6764 return QualType();
6765 }
6766
canAssignObjCInterfaces(const ObjCObjectType * LHS,const ObjCObjectType * RHS)6767 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6768 const ObjCObjectType *RHS) {
6769 assert(LHS->getInterface() && "LHS is not an interface type");
6770 assert(RHS->getInterface() && "RHS is not an interface type");
6771
6772 // Verify that the base decls are compatible: the RHS must be a subclass of
6773 // the LHS.
6774 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
6775 return false;
6776
6777 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6778 // protocol qualified at all, then we are good.
6779 if (LHS->getNumProtocols() == 0)
6780 return true;
6781
6782 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6783 // more detailed analysis is required.
6784 if (RHS->getNumProtocols() == 0) {
6785 // OK, if LHS is a superclass of RHS *and*
6786 // this superclass is assignment compatible with LHS.
6787 // false otherwise.
6788 bool IsSuperClass =
6789 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6790 if (IsSuperClass) {
6791 // OK if conversion of LHS to SuperClass results in narrowing of types
6792 // ; i.e., SuperClass may implement at least one of the protocols
6793 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6794 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6795 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
6796 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
6797 // If super class has no protocols, it is not a match.
6798 if (SuperClassInheritedProtocols.empty())
6799 return false;
6800
6801 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6802 LHSPE = LHS->qual_end();
6803 LHSPI != LHSPE; LHSPI++) {
6804 bool SuperImplementsProtocol = false;
6805 ObjCProtocolDecl *LHSProto = (*LHSPI);
6806
6807 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6808 SuperClassInheritedProtocols.begin(),
6809 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6810 ObjCProtocolDecl *SuperClassProto = (*I);
6811 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6812 SuperImplementsProtocol = true;
6813 break;
6814 }
6815 }
6816 if (!SuperImplementsProtocol)
6817 return false;
6818 }
6819 return true;
6820 }
6821 return false;
6822 }
6823
6824 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6825 LHSPE = LHS->qual_end();
6826 LHSPI != LHSPE; LHSPI++) {
6827 bool RHSImplementsProtocol = false;
6828
6829 // If the RHS doesn't implement the protocol on the left, the types
6830 // are incompatible.
6831 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6832 RHSPE = RHS->qual_end();
6833 RHSPI != RHSPE; RHSPI++) {
6834 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
6835 RHSImplementsProtocol = true;
6836 break;
6837 }
6838 }
6839 // FIXME: For better diagnostics, consider passing back the protocol name.
6840 if (!RHSImplementsProtocol)
6841 return false;
6842 }
6843 // The RHS implements all protocols listed on the LHS.
6844 return true;
6845 }
6846
areComparableObjCPointerTypes(QualType LHS,QualType RHS)6847 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6848 // get the "pointed to" types
6849 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6850 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
6851
6852 if (!LHSOPT || !RHSOPT)
6853 return false;
6854
6855 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6856 canAssignObjCInterfaces(RHSOPT, LHSOPT);
6857 }
6858
canBindObjCObjectType(QualType To,QualType From)6859 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6860 return canAssignObjCInterfaces(
6861 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6862 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6863 }
6864
6865 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
6866 /// both shall have the identically qualified version of a compatible type.
6867 /// C99 6.2.7p1: Two types have compatible types if their types are the
6868 /// same. See 6.7.[2,3,5] for additional rules.
typesAreCompatible(QualType LHS,QualType RHS,bool CompareUnqualified)6869 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6870 bool CompareUnqualified) {
6871 if (getLangOpts().CPlusPlus)
6872 return hasSameType(LHS, RHS);
6873
6874 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
6875 }
6876
propertyTypesAreCompatible(QualType LHS,QualType RHS)6877 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
6878 return typesAreCompatible(LHS, RHS);
6879 }
6880
typesAreBlockPointerCompatible(QualType LHS,QualType RHS)6881 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6882 return !mergeTypes(LHS, RHS, true).isNull();
6883 }
6884
6885 /// mergeTransparentUnionType - if T is a transparent union type and a member
6886 /// of T is compatible with SubType, return the merged type, else return
6887 /// QualType()
mergeTransparentUnionType(QualType T,QualType SubType,bool OfBlockPointer,bool Unqualified)6888 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6889 bool OfBlockPointer,
6890 bool Unqualified) {
6891 if (const RecordType *UT = T->getAsUnionType()) {
6892 RecordDecl *UD = UT->getDecl();
6893 if (UD->hasAttr<TransparentUnionAttr>()) {
6894 for (RecordDecl::field_iterator it = UD->field_begin(),
6895 itend = UD->field_end(); it != itend; ++it) {
6896 QualType ET = it->getType().getUnqualifiedType();
6897 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6898 if (!MT.isNull())
6899 return MT;
6900 }
6901 }
6902 }
6903
6904 return QualType();
6905 }
6906
6907 /// mergeFunctionArgumentTypes - merge two types which appear as function
6908 /// argument types
mergeFunctionArgumentTypes(QualType lhs,QualType rhs,bool OfBlockPointer,bool Unqualified)6909 QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6910 bool OfBlockPointer,
6911 bool Unqualified) {
6912 // GNU extension: two types are compatible if they appear as a function
6913 // argument, one of the types is a transparent union type and the other
6914 // type is compatible with a union member
6915 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6916 Unqualified);
6917 if (!lmerge.isNull())
6918 return lmerge;
6919
6920 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6921 Unqualified);
6922 if (!rmerge.isNull())
6923 return rmerge;
6924
6925 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6926 }
6927
mergeFunctionTypes(QualType lhs,QualType rhs,bool OfBlockPointer,bool Unqualified)6928 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
6929 bool OfBlockPointer,
6930 bool Unqualified) {
6931 const FunctionType *lbase = lhs->getAs<FunctionType>();
6932 const FunctionType *rbase = rhs->getAs<FunctionType>();
6933 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6934 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
6935 bool allLTypes = true;
6936 bool allRTypes = true;
6937
6938 // Check return type
6939 QualType retType;
6940 if (OfBlockPointer) {
6941 QualType RHS = rbase->getResultType();
6942 QualType LHS = lbase->getResultType();
6943 bool UnqualifiedResult = Unqualified;
6944 if (!UnqualifiedResult)
6945 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
6946 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
6947 }
6948 else
6949 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6950 Unqualified);
6951 if (retType.isNull()) return QualType();
6952
6953 if (Unqualified)
6954 retType = retType.getUnqualifiedType();
6955
6956 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6957 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6958 if (Unqualified) {
6959 LRetType = LRetType.getUnqualifiedType();
6960 RRetType = RRetType.getUnqualifiedType();
6961 }
6962
6963 if (getCanonicalType(retType) != LRetType)
6964 allLTypes = false;
6965 if (getCanonicalType(retType) != RRetType)
6966 allRTypes = false;
6967
6968 // FIXME: double check this
6969 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6970 // rbase->getRegParmAttr() != 0 &&
6971 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
6972 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6973 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
6974
6975 // Compatible functions must have compatible calling conventions
6976 if (lbaseInfo.getCC() != rbaseInfo.getCC())
6977 return QualType();
6978
6979 // Regparm is part of the calling convention.
6980 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6981 return QualType();
6982 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6983 return QualType();
6984
6985 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6986 return QualType();
6987
6988 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6989 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
6990
6991 if (lbaseInfo.getNoReturn() != NoReturn)
6992 allLTypes = false;
6993 if (rbaseInfo.getNoReturn() != NoReturn)
6994 allRTypes = false;
6995
6996 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
6997
6998 if (lproto && rproto) { // two C99 style function prototypes
6999 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7000 "C++ shouldn't be here");
7001 unsigned lproto_nargs = lproto->getNumArgs();
7002 unsigned rproto_nargs = rproto->getNumArgs();
7003
7004 // Compatible functions must have the same number of arguments
7005 if (lproto_nargs != rproto_nargs)
7006 return QualType();
7007
7008 // Variadic and non-variadic functions aren't compatible
7009 if (lproto->isVariadic() != rproto->isVariadic())
7010 return QualType();
7011
7012 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7013 return QualType();
7014
7015 if (LangOpts.ObjCAutoRefCount &&
7016 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
7017 return QualType();
7018
7019 // Check argument compatibility
7020 SmallVector<QualType, 10> types;
7021 for (unsigned i = 0; i < lproto_nargs; i++) {
7022 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
7023 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
7024 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
7025 OfBlockPointer,
7026 Unqualified);
7027 if (argtype.isNull()) return QualType();
7028
7029 if (Unqualified)
7030 argtype = argtype.getUnqualifiedType();
7031
7032 types.push_back(argtype);
7033 if (Unqualified) {
7034 largtype = largtype.getUnqualifiedType();
7035 rargtype = rargtype.getUnqualifiedType();
7036 }
7037
7038 if (getCanonicalType(argtype) != getCanonicalType(largtype))
7039 allLTypes = false;
7040 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
7041 allRTypes = false;
7042 }
7043
7044 if (allLTypes) return lhs;
7045 if (allRTypes) return rhs;
7046
7047 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7048 EPI.ExtInfo = einfo;
7049 return getFunctionType(retType, types, EPI);
7050 }
7051
7052 if (lproto) allRTypes = false;
7053 if (rproto) allLTypes = false;
7054
7055 const FunctionProtoType *proto = lproto ? lproto : rproto;
7056 if (proto) {
7057 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
7058 if (proto->isVariadic()) return QualType();
7059 // Check that the types are compatible with the types that
7060 // would result from default argument promotions (C99 6.7.5.3p15).
7061 // The only types actually affected are promotable integer
7062 // types and floats, which would be passed as a different
7063 // type depending on whether the prototype is visible.
7064 unsigned proto_nargs = proto->getNumArgs();
7065 for (unsigned i = 0; i < proto_nargs; ++i) {
7066 QualType argTy = proto->getArgType(i);
7067
7068 // Look at the converted type of enum types, since that is the type used
7069 // to pass enum values.
7070 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
7071 argTy = Enum->getDecl()->getIntegerType();
7072 if (argTy.isNull())
7073 return QualType();
7074 }
7075
7076 if (argTy->isPromotableIntegerType() ||
7077 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
7078 return QualType();
7079 }
7080
7081 if (allLTypes) return lhs;
7082 if (allRTypes) return rhs;
7083
7084 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7085 EPI.ExtInfo = einfo;
7086 return getFunctionType(retType, proto->getArgTypes(), EPI);
7087 }
7088
7089 if (allLTypes) return lhs;
7090 if (allRTypes) return rhs;
7091 return getFunctionNoProtoType(retType, einfo);
7092 }
7093
7094 /// Given that we have an enum type and a non-enum type, try to merge them.
mergeEnumWithInteger(ASTContext & Context,const EnumType * ET,QualType other,bool isBlockReturnType)7095 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7096 QualType other, bool isBlockReturnType) {
7097 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7098 // a signed integer type, or an unsigned integer type.
7099 // Compatibility is based on the underlying type, not the promotion
7100 // type.
7101 QualType underlyingType = ET->getDecl()->getIntegerType();
7102 if (underlyingType.isNull()) return QualType();
7103 if (Context.hasSameType(underlyingType, other))
7104 return other;
7105
7106 // In block return types, we're more permissive and accept any
7107 // integral type of the same size.
7108 if (isBlockReturnType && other->isIntegerType() &&
7109 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7110 return other;
7111
7112 return QualType();
7113 }
7114
mergeTypes(QualType LHS,QualType RHS,bool OfBlockPointer,bool Unqualified,bool BlockReturnType)7115 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
7116 bool OfBlockPointer,
7117 bool Unqualified, bool BlockReturnType) {
7118 // C++ [expr]: If an expression initially has the type "reference to T", the
7119 // type is adjusted to "T" prior to any further analysis, the expression
7120 // designates the object or function denoted by the reference, and the
7121 // expression is an lvalue unless the reference is an rvalue reference and
7122 // the expression is a function call (possibly inside parentheses).
7123 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7124 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
7125
7126 if (Unqualified) {
7127 LHS = LHS.getUnqualifiedType();
7128 RHS = RHS.getUnqualifiedType();
7129 }
7130
7131 QualType LHSCan = getCanonicalType(LHS),
7132 RHSCan = getCanonicalType(RHS);
7133
7134 // If two types are identical, they are compatible.
7135 if (LHSCan == RHSCan)
7136 return LHS;
7137
7138 // If the qualifiers are different, the types aren't compatible... mostly.
7139 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7140 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7141 if (LQuals != RQuals) {
7142 // If any of these qualifiers are different, we have a type
7143 // mismatch.
7144 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7145 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7146 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
7147 return QualType();
7148
7149 // Exactly one GC qualifier difference is allowed: __strong is
7150 // okay if the other type has no GC qualifier but is an Objective
7151 // C object pointer (i.e. implicitly strong by default). We fix
7152 // this by pretending that the unqualified type was actually
7153 // qualified __strong.
7154 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7155 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7156 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7157
7158 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7159 return QualType();
7160
7161 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7162 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7163 }
7164 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7165 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7166 }
7167 return QualType();
7168 }
7169
7170 // Okay, qualifiers are equal.
7171
7172 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7173 Type::TypeClass RHSClass = RHSCan->getTypeClass();
7174
7175 // We want to consider the two function types to be the same for these
7176 // comparisons, just force one to the other.
7177 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7178 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
7179
7180 // Same as above for arrays
7181 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7182 LHSClass = Type::ConstantArray;
7183 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7184 RHSClass = Type::ConstantArray;
7185
7186 // ObjCInterfaces are just specialized ObjCObjects.
7187 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7188 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7189
7190 // Canonicalize ExtVector -> Vector.
7191 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7192 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
7193
7194 // If the canonical type classes don't match.
7195 if (LHSClass != RHSClass) {
7196 // Note that we only have special rules for turning block enum
7197 // returns into block int returns, not vice-versa.
7198 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
7199 return mergeEnumWithInteger(*this, ETy, RHS, false);
7200 }
7201 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
7202 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
7203 }
7204 // allow block pointer type to match an 'id' type.
7205 if (OfBlockPointer && !BlockReturnType) {
7206 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7207 return LHS;
7208 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7209 return RHS;
7210 }
7211
7212 return QualType();
7213 }
7214
7215 // The canonical type classes match.
7216 switch (LHSClass) {
7217 #define TYPE(Class, Base)
7218 #define ABSTRACT_TYPE(Class, Base)
7219 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
7220 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7221 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
7222 #include "clang/AST/TypeNodes.def"
7223 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
7224
7225 case Type::Auto:
7226 case Type::LValueReference:
7227 case Type::RValueReference:
7228 case Type::MemberPointer:
7229 llvm_unreachable("C++ should never be in mergeTypes");
7230
7231 case Type::ObjCInterface:
7232 case Type::IncompleteArray:
7233 case Type::VariableArray:
7234 case Type::FunctionProto:
7235 case Type::ExtVector:
7236 llvm_unreachable("Types are eliminated above");
7237
7238 case Type::Pointer:
7239 {
7240 // Merge two pointer types, while trying to preserve typedef info
7241 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7242 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
7243 if (Unqualified) {
7244 LHSPointee = LHSPointee.getUnqualifiedType();
7245 RHSPointee = RHSPointee.getUnqualifiedType();
7246 }
7247 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7248 Unqualified);
7249 if (ResultType.isNull()) return QualType();
7250 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7251 return LHS;
7252 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7253 return RHS;
7254 return getPointerType(ResultType);
7255 }
7256 case Type::BlockPointer:
7257 {
7258 // Merge two block pointer types, while trying to preserve typedef info
7259 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7260 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
7261 if (Unqualified) {
7262 LHSPointee = LHSPointee.getUnqualifiedType();
7263 RHSPointee = RHSPointee.getUnqualifiedType();
7264 }
7265 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7266 Unqualified);
7267 if (ResultType.isNull()) return QualType();
7268 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7269 return LHS;
7270 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7271 return RHS;
7272 return getBlockPointerType(ResultType);
7273 }
7274 case Type::Atomic:
7275 {
7276 // Merge two pointer types, while trying to preserve typedef info
7277 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7278 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7279 if (Unqualified) {
7280 LHSValue = LHSValue.getUnqualifiedType();
7281 RHSValue = RHSValue.getUnqualifiedType();
7282 }
7283 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7284 Unqualified);
7285 if (ResultType.isNull()) return QualType();
7286 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7287 return LHS;
7288 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7289 return RHS;
7290 return getAtomicType(ResultType);
7291 }
7292 case Type::ConstantArray:
7293 {
7294 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7295 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7296 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7297 return QualType();
7298
7299 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7300 QualType RHSElem = getAsArrayType(RHS)->getElementType();
7301 if (Unqualified) {
7302 LHSElem = LHSElem.getUnqualifiedType();
7303 RHSElem = RHSElem.getUnqualifiedType();
7304 }
7305
7306 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
7307 if (ResultType.isNull()) return QualType();
7308 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7309 return LHS;
7310 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7311 return RHS;
7312 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7313 ArrayType::ArraySizeModifier(), 0);
7314 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7315 ArrayType::ArraySizeModifier(), 0);
7316 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7317 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
7318 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7319 return LHS;
7320 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7321 return RHS;
7322 if (LVAT) {
7323 // FIXME: This isn't correct! But tricky to implement because
7324 // the array's size has to be the size of LHS, but the type
7325 // has to be different.
7326 return LHS;
7327 }
7328 if (RVAT) {
7329 // FIXME: This isn't correct! But tricky to implement because
7330 // the array's size has to be the size of RHS, but the type
7331 // has to be different.
7332 return RHS;
7333 }
7334 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7335 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
7336 return getIncompleteArrayType(ResultType,
7337 ArrayType::ArraySizeModifier(), 0);
7338 }
7339 case Type::FunctionNoProto:
7340 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
7341 case Type::Record:
7342 case Type::Enum:
7343 return QualType();
7344 case Type::Builtin:
7345 // Only exactly equal builtin types are compatible, which is tested above.
7346 return QualType();
7347 case Type::Complex:
7348 // Distinct complex types are incompatible.
7349 return QualType();
7350 case Type::Vector:
7351 // FIXME: The merged type should be an ExtVector!
7352 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7353 RHSCan->getAs<VectorType>()))
7354 return LHS;
7355 return QualType();
7356 case Type::ObjCObject: {
7357 // Check if the types are assignment compatible.
7358 // FIXME: This should be type compatibility, e.g. whether
7359 // "LHS x; RHS x;" at global scope is legal.
7360 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7361 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7362 if (canAssignObjCInterfaces(LHSIface, RHSIface))
7363 return LHS;
7364
7365 return QualType();
7366 }
7367 case Type::ObjCObjectPointer: {
7368 if (OfBlockPointer) {
7369 if (canAssignObjCInterfacesInBlockPointer(
7370 LHS->getAs<ObjCObjectPointerType>(),
7371 RHS->getAs<ObjCObjectPointerType>(),
7372 BlockReturnType))
7373 return LHS;
7374 return QualType();
7375 }
7376 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7377 RHS->getAs<ObjCObjectPointerType>()))
7378 return LHS;
7379
7380 return QualType();
7381 }
7382 }
7383
7384 llvm_unreachable("Invalid Type::Class!");
7385 }
7386
FunctionTypesMatchOnNSConsumedAttrs(const FunctionProtoType * FromFunctionType,const FunctionProtoType * ToFunctionType)7387 bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7388 const FunctionProtoType *FromFunctionType,
7389 const FunctionProtoType *ToFunctionType) {
7390 if (FromFunctionType->hasAnyConsumedArgs() !=
7391 ToFunctionType->hasAnyConsumedArgs())
7392 return false;
7393 FunctionProtoType::ExtProtoInfo FromEPI =
7394 FromFunctionType->getExtProtoInfo();
7395 FunctionProtoType::ExtProtoInfo ToEPI =
7396 ToFunctionType->getExtProtoInfo();
7397 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
7398 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
7399 ArgIdx != NumArgs; ++ArgIdx) {
7400 if (FromEPI.ConsumedArguments[ArgIdx] !=
7401 ToEPI.ConsumedArguments[ArgIdx])
7402 return false;
7403 }
7404 return true;
7405 }
7406
7407 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7408 /// 'RHS' attributes and returns the merged version; including for function
7409 /// return types.
mergeObjCGCQualifiers(QualType LHS,QualType RHS)7410 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7411 QualType LHSCan = getCanonicalType(LHS),
7412 RHSCan = getCanonicalType(RHS);
7413 // If two types are identical, they are compatible.
7414 if (LHSCan == RHSCan)
7415 return LHS;
7416 if (RHSCan->isFunctionType()) {
7417 if (!LHSCan->isFunctionType())
7418 return QualType();
7419 QualType OldReturnType =
7420 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
7421 QualType NewReturnType =
7422 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
7423 QualType ResReturnType =
7424 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7425 if (ResReturnType.isNull())
7426 return QualType();
7427 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7428 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7429 // In either case, use OldReturnType to build the new function type.
7430 const FunctionType *F = LHS->getAs<FunctionType>();
7431 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
7432 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7433 EPI.ExtInfo = getFunctionExtInfo(LHS);
7434 QualType ResultType =
7435 getFunctionType(OldReturnType, FPT->getArgTypes(), EPI);
7436 return ResultType;
7437 }
7438 }
7439 return QualType();
7440 }
7441
7442 // If the qualifiers are different, the types can still be merged.
7443 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7444 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7445 if (LQuals != RQuals) {
7446 // If any of these qualifiers are different, we have a type mismatch.
7447 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7448 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7449 return QualType();
7450
7451 // Exactly one GC qualifier difference is allowed: __strong is
7452 // okay if the other type has no GC qualifier but is an Objective
7453 // C object pointer (i.e. implicitly strong by default). We fix
7454 // this by pretending that the unqualified type was actually
7455 // qualified __strong.
7456 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7457 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7458 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7459
7460 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7461 return QualType();
7462
7463 if (GC_L == Qualifiers::Strong)
7464 return LHS;
7465 if (GC_R == Qualifiers::Strong)
7466 return RHS;
7467 return QualType();
7468 }
7469
7470 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7471 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7472 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7473 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7474 if (ResQT == LHSBaseQT)
7475 return LHS;
7476 if (ResQT == RHSBaseQT)
7477 return RHS;
7478 }
7479 return QualType();
7480 }
7481
7482 //===----------------------------------------------------------------------===//
7483 // Integer Predicates
7484 //===----------------------------------------------------------------------===//
7485
getIntWidth(QualType T) const7486 unsigned ASTContext::getIntWidth(QualType T) const {
7487 if (const EnumType *ET = T->getAs<EnumType>())
7488 T = ET->getDecl()->getIntegerType();
7489 if (T->isBooleanType())
7490 return 1;
7491 // For builtin types, just use the standard type sizing method
7492 return (unsigned)getTypeSize(T);
7493 }
7494
getCorrespondingUnsignedType(QualType T) const7495 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
7496 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
7497
7498 // Turn <4 x signed int> -> <4 x unsigned int>
7499 if (const VectorType *VTy = T->getAs<VectorType>())
7500 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
7501 VTy->getNumElements(), VTy->getVectorKind());
7502
7503 // For enums, we return the unsigned version of the base type.
7504 if (const EnumType *ETy = T->getAs<EnumType>())
7505 T = ETy->getDecl()->getIntegerType();
7506
7507 const BuiltinType *BTy = T->getAs<BuiltinType>();
7508 assert(BTy && "Unexpected signed integer type");
7509 switch (BTy->getKind()) {
7510 case BuiltinType::Char_S:
7511 case BuiltinType::SChar:
7512 return UnsignedCharTy;
7513 case BuiltinType::Short:
7514 return UnsignedShortTy;
7515 case BuiltinType::Int:
7516 return UnsignedIntTy;
7517 case BuiltinType::Long:
7518 return UnsignedLongTy;
7519 case BuiltinType::LongLong:
7520 return UnsignedLongLongTy;
7521 case BuiltinType::Int128:
7522 return UnsignedInt128Ty;
7523 default:
7524 llvm_unreachable("Unexpected signed integer type");
7525 }
7526 }
7527
~ASTMutationListener()7528 ASTMutationListener::~ASTMutationListener() { }
7529
DeducedReturnType(const FunctionDecl * FD,QualType ReturnType)7530 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7531 QualType ReturnType) {}
7532
7533 //===----------------------------------------------------------------------===//
7534 // Builtin Type Computation
7535 //===----------------------------------------------------------------------===//
7536
7537 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
7538 /// pointer over the consumed characters. This returns the resultant type. If
7539 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7540 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7541 /// a vector of "i*".
7542 ///
7543 /// RequiresICE is filled in on return to indicate whether the value is required
7544 /// to be an Integer Constant Expression.
DecodeTypeFromStr(const char * & Str,const ASTContext & Context,ASTContext::GetBuiltinTypeError & Error,bool & RequiresICE,bool AllowTypeModifiers)7545 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
7546 ASTContext::GetBuiltinTypeError &Error,
7547 bool &RequiresICE,
7548 bool AllowTypeModifiers) {
7549 // Modifiers.
7550 int HowLong = 0;
7551 bool Signed = false, Unsigned = false;
7552 RequiresICE = false;
7553
7554 // Read the prefixed modifiers first.
7555 bool Done = false;
7556 while (!Done) {
7557 switch (*Str++) {
7558 default: Done = true; --Str; break;
7559 case 'I':
7560 RequiresICE = true;
7561 break;
7562 case 'S':
7563 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7564 assert(!Signed && "Can't use 'S' modifier multiple times!");
7565 Signed = true;
7566 break;
7567 case 'U':
7568 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7569 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7570 Unsigned = true;
7571 break;
7572 case 'L':
7573 assert(HowLong <= 2 && "Can't have LLLL modifier");
7574 ++HowLong;
7575 break;
7576 }
7577 }
7578
7579 QualType Type;
7580
7581 // Read the base type.
7582 switch (*Str++) {
7583 default: llvm_unreachable("Unknown builtin type letter!");
7584 case 'v':
7585 assert(HowLong == 0 && !Signed && !Unsigned &&
7586 "Bad modifiers used with 'v'!");
7587 Type = Context.VoidTy;
7588 break;
7589 case 'h':
7590 assert(HowLong == 0 && !Signed && !Unsigned &&
7591 "Bad modifiers used with 'f'!");
7592 Type = Context.HalfTy;
7593 break;
7594 case 'f':
7595 assert(HowLong == 0 && !Signed && !Unsigned &&
7596 "Bad modifiers used with 'f'!");
7597 Type = Context.FloatTy;
7598 break;
7599 case 'd':
7600 assert(HowLong < 2 && !Signed && !Unsigned &&
7601 "Bad modifiers used with 'd'!");
7602 if (HowLong)
7603 Type = Context.LongDoubleTy;
7604 else
7605 Type = Context.DoubleTy;
7606 break;
7607 case 's':
7608 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7609 if (Unsigned)
7610 Type = Context.UnsignedShortTy;
7611 else
7612 Type = Context.ShortTy;
7613 break;
7614 case 'i':
7615 if (HowLong == 3)
7616 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7617 else if (HowLong == 2)
7618 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7619 else if (HowLong == 1)
7620 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7621 else
7622 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7623 break;
7624 case 'c':
7625 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7626 if (Signed)
7627 Type = Context.SignedCharTy;
7628 else if (Unsigned)
7629 Type = Context.UnsignedCharTy;
7630 else
7631 Type = Context.CharTy;
7632 break;
7633 case 'b': // boolean
7634 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7635 Type = Context.BoolTy;
7636 break;
7637 case 'z': // size_t.
7638 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7639 Type = Context.getSizeType();
7640 break;
7641 case 'F':
7642 Type = Context.getCFConstantStringType();
7643 break;
7644 case 'G':
7645 Type = Context.getObjCIdType();
7646 break;
7647 case 'H':
7648 Type = Context.getObjCSelType();
7649 break;
7650 case 'M':
7651 Type = Context.getObjCSuperType();
7652 break;
7653 case 'a':
7654 Type = Context.getBuiltinVaListType();
7655 assert(!Type.isNull() && "builtin va list type not initialized!");
7656 break;
7657 case 'A':
7658 // This is a "reference" to a va_list; however, what exactly
7659 // this means depends on how va_list is defined. There are two
7660 // different kinds of va_list: ones passed by value, and ones
7661 // passed by reference. An example of a by-value va_list is
7662 // x86, where va_list is a char*. An example of by-ref va_list
7663 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7664 // we want this argument to be a char*&; for x86-64, we want
7665 // it to be a __va_list_tag*.
7666 Type = Context.getBuiltinVaListType();
7667 assert(!Type.isNull() && "builtin va list type not initialized!");
7668 if (Type->isArrayType())
7669 Type = Context.getArrayDecayedType(Type);
7670 else
7671 Type = Context.getLValueReferenceType(Type);
7672 break;
7673 case 'V': {
7674 char *End;
7675 unsigned NumElements = strtoul(Str, &End, 10);
7676 assert(End != Str && "Missing vector size");
7677 Str = End;
7678
7679 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7680 RequiresICE, false);
7681 assert(!RequiresICE && "Can't require vector ICE");
7682
7683 // TODO: No way to make AltiVec vectors in builtins yet.
7684 Type = Context.getVectorType(ElementType, NumElements,
7685 VectorType::GenericVector);
7686 break;
7687 }
7688 case 'E': {
7689 char *End;
7690
7691 unsigned NumElements = strtoul(Str, &End, 10);
7692 assert(End != Str && "Missing vector size");
7693
7694 Str = End;
7695
7696 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7697 false);
7698 Type = Context.getExtVectorType(ElementType, NumElements);
7699 break;
7700 }
7701 case 'X': {
7702 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7703 false);
7704 assert(!RequiresICE && "Can't require complex ICE");
7705 Type = Context.getComplexType(ElementType);
7706 break;
7707 }
7708 case 'Y' : {
7709 Type = Context.getPointerDiffType();
7710 break;
7711 }
7712 case 'P':
7713 Type = Context.getFILEType();
7714 if (Type.isNull()) {
7715 Error = ASTContext::GE_Missing_stdio;
7716 return QualType();
7717 }
7718 break;
7719 case 'J':
7720 if (Signed)
7721 Type = Context.getsigjmp_bufType();
7722 else
7723 Type = Context.getjmp_bufType();
7724
7725 if (Type.isNull()) {
7726 Error = ASTContext::GE_Missing_setjmp;
7727 return QualType();
7728 }
7729 break;
7730 case 'K':
7731 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7732 Type = Context.getucontext_tType();
7733
7734 if (Type.isNull()) {
7735 Error = ASTContext::GE_Missing_ucontext;
7736 return QualType();
7737 }
7738 break;
7739 case 'p':
7740 Type = Context.getProcessIDType();
7741 break;
7742 }
7743
7744 // If there are modifiers and if we're allowed to parse them, go for it.
7745 Done = !AllowTypeModifiers;
7746 while (!Done) {
7747 switch (char c = *Str++) {
7748 default: Done = true; --Str; break;
7749 case '*':
7750 case '&': {
7751 // Both pointers and references can have their pointee types
7752 // qualified with an address space.
7753 char *End;
7754 unsigned AddrSpace = strtoul(Str, &End, 10);
7755 if (End != Str && AddrSpace != 0) {
7756 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7757 Str = End;
7758 }
7759 if (c == '*')
7760 Type = Context.getPointerType(Type);
7761 else
7762 Type = Context.getLValueReferenceType(Type);
7763 break;
7764 }
7765 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7766 case 'C':
7767 Type = Type.withConst();
7768 break;
7769 case 'D':
7770 Type = Context.getVolatileType(Type);
7771 break;
7772 case 'R':
7773 Type = Type.withRestrict();
7774 break;
7775 }
7776 }
7777
7778 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
7779 "Integer constant 'I' type must be an integer");
7780
7781 return Type;
7782 }
7783
7784 /// GetBuiltinType - Return the type for the specified builtin.
GetBuiltinType(unsigned Id,GetBuiltinTypeError & Error,unsigned * IntegerConstantArgs) const7785 QualType ASTContext::GetBuiltinType(unsigned Id,
7786 GetBuiltinTypeError &Error,
7787 unsigned *IntegerConstantArgs) const {
7788 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
7789
7790 SmallVector<QualType, 8> ArgTypes;
7791
7792 bool RequiresICE = false;
7793 Error = GE_None;
7794 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7795 RequiresICE, true);
7796 if (Error != GE_None)
7797 return QualType();
7798
7799 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7800
7801 while (TypeStr[0] && TypeStr[0] != '.') {
7802 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
7803 if (Error != GE_None)
7804 return QualType();
7805
7806 // If this argument is required to be an IntegerConstantExpression and the
7807 // caller cares, fill in the bitmask we return.
7808 if (RequiresICE && IntegerConstantArgs)
7809 *IntegerConstantArgs |= 1 << ArgTypes.size();
7810
7811 // Do array -> pointer decay. The builtin should use the decayed type.
7812 if (Ty->isArrayType())
7813 Ty = getArrayDecayedType(Ty);
7814
7815 ArgTypes.push_back(Ty);
7816 }
7817
7818 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7819 "'.' should only occur at end of builtin type list!");
7820
7821 FunctionType::ExtInfo EI(CC_C);
7822 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7823
7824 bool Variadic = (TypeStr[0] == '.');
7825
7826 // We really shouldn't be making a no-proto type here, especially in C++.
7827 if (ArgTypes.empty() && Variadic)
7828 return getFunctionNoProtoType(ResType, EI);
7829
7830 FunctionProtoType::ExtProtoInfo EPI;
7831 EPI.ExtInfo = EI;
7832 EPI.Variadic = Variadic;
7833
7834 return getFunctionType(ResType, ArgTypes, EPI);
7835 }
7836
GetGVALinkageForFunction(const FunctionDecl * FD)7837 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
7838 if (!FD->isExternallyVisible())
7839 return GVA_Internal;
7840
7841 GVALinkage External = GVA_StrongExternal;
7842 switch (FD->getTemplateSpecializationKind()) {
7843 case TSK_Undeclared:
7844 case TSK_ExplicitSpecialization:
7845 External = GVA_StrongExternal;
7846 break;
7847
7848 case TSK_ExplicitInstantiationDefinition:
7849 return GVA_ExplicitTemplateInstantiation;
7850
7851 case TSK_ExplicitInstantiationDeclaration:
7852 case TSK_ImplicitInstantiation:
7853 External = GVA_TemplateInstantiation;
7854 break;
7855 }
7856
7857 if (!FD->isInlined())
7858 return External;
7859
7860 if ((!getLangOpts().CPlusPlus && !getLangOpts().MicrosoftMode) ||
7861 FD->hasAttr<GNUInlineAttr>()) {
7862 // GNU or C99 inline semantics. Determine whether this symbol should be
7863 // externally visible.
7864 if (FD->isInlineDefinitionExternallyVisible())
7865 return External;
7866
7867 // C99 inline semantics, where the symbol is not externally visible.
7868 return GVA_C99Inline;
7869 }
7870
7871 // C++0x [temp.explicit]p9:
7872 // [ Note: The intent is that an inline function that is the subject of
7873 // an explicit instantiation declaration will still be implicitly
7874 // instantiated when used so that the body can be considered for
7875 // inlining, but that no out-of-line copy of the inline function would be
7876 // generated in the translation unit. -- end note ]
7877 if (FD->getTemplateSpecializationKind()
7878 == TSK_ExplicitInstantiationDeclaration)
7879 return GVA_C99Inline;
7880
7881 return GVA_CXXInline;
7882 }
7883
GetGVALinkageForVariable(const VarDecl * VD)7884 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7885 if (!VD->isExternallyVisible())
7886 return GVA_Internal;
7887
7888 switch (VD->getTemplateSpecializationKind()) {
7889 case TSK_Undeclared:
7890 case TSK_ExplicitSpecialization:
7891 return GVA_StrongExternal;
7892
7893 case TSK_ExplicitInstantiationDeclaration:
7894 llvm_unreachable("Variable should not be instantiated");
7895 // Fall through to treat this like any other instantiation.
7896
7897 case TSK_ExplicitInstantiationDefinition:
7898 return GVA_ExplicitTemplateInstantiation;
7899
7900 case TSK_ImplicitInstantiation:
7901 return GVA_TemplateInstantiation;
7902 }
7903
7904 llvm_unreachable("Invalid Linkage!");
7905 }
7906
DeclMustBeEmitted(const Decl * D)7907 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
7908 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7909 if (!VD->isFileVarDecl())
7910 return false;
7911 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7912 // We never need to emit an uninstantiated function template.
7913 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7914 return false;
7915 } else
7916 return false;
7917
7918 // If this is a member of a class template, we do not need to emit it.
7919 if (D->getDeclContext()->isDependentContext())
7920 return false;
7921
7922 // Weak references don't produce any output by themselves.
7923 if (D->hasAttr<WeakRefAttr>())
7924 return false;
7925
7926 // Aliases and used decls are required.
7927 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7928 return true;
7929
7930 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7931 // Forward declarations aren't required.
7932 if (!FD->doesThisDeclarationHaveABody())
7933 return FD->doesDeclarationForceExternallyVisibleDefinition();
7934
7935 // Constructors and destructors are required.
7936 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7937 return true;
7938
7939 // The key function for a class is required. This rule only comes
7940 // into play when inline functions can be key functions, though.
7941 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7942 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7943 const CXXRecordDecl *RD = MD->getParent();
7944 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7945 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7946 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7947 return true;
7948 }
7949 }
7950 }
7951
7952 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7953
7954 // static, static inline, always_inline, and extern inline functions can
7955 // always be deferred. Normal inline functions can be deferred in C99/C++.
7956 // Implicit template instantiations can also be deferred in C++.
7957 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
7958 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
7959 return false;
7960 return true;
7961 }
7962
7963 const VarDecl *VD = cast<VarDecl>(D);
7964 assert(VD->isFileVarDecl() && "Expected file scoped var");
7965
7966 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7967 return false;
7968
7969 // Variables that can be needed in other TUs are required.
7970 GVALinkage L = GetGVALinkageForVariable(VD);
7971 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7972 return true;
7973
7974 // Variables that have destruction with side-effects are required.
7975 if (VD->getType().isDestructedType())
7976 return true;
7977
7978 // Variables that have initialization with side-effects are required.
7979 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7980 return true;
7981
7982 return false;
7983 }
7984
getDefaultCallingConvention(bool IsVariadic,bool IsCXXMethod) const7985 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
7986 bool IsCXXMethod) const {
7987 // Pass through to the C++ ABI object
7988 if (IsCXXMethod)
7989 return ABI->getDefaultMethodCallConv(IsVariadic);
7990
7991 return (LangOpts.MRTD && !IsVariadic) ? CC_X86StdCall : CC_C;
7992 }
7993
isNearlyEmpty(const CXXRecordDecl * RD) const7994 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
7995 // Pass through to the C++ ABI object
7996 return ABI->isNearlyEmpty(RD);
7997 }
7998
createMangleContext()7999 MangleContext *ASTContext::createMangleContext() {
8000 switch (Target->getCXXABI().getKind()) {
8001 case TargetCXXABI::GenericAArch64:
8002 case TargetCXXABI::GenericItanium:
8003 case TargetCXXABI::GenericARM:
8004 case TargetCXXABI::iOS:
8005 return ItaniumMangleContext::create(*this, getDiagnostics());
8006 case TargetCXXABI::Microsoft:
8007 return MicrosoftMangleContext::create(*this, getDiagnostics());
8008 }
8009 llvm_unreachable("Unsupported ABI");
8010 }
8011
~CXXABI()8012 CXXABI::~CXXABI() {}
8013
getSideTableAllocatedMemory() const8014 size_t ASTContext::getSideTableAllocatedMemory() const {
8015 return ASTRecordLayouts.getMemorySize() +
8016 llvm::capacity_in_bytes(ObjCLayouts) +
8017 llvm::capacity_in_bytes(KeyFunctions) +
8018 llvm::capacity_in_bytes(ObjCImpls) +
8019 llvm::capacity_in_bytes(BlockVarCopyInits) +
8020 llvm::capacity_in_bytes(DeclAttrs) +
8021 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8022 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8023 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8024 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8025 llvm::capacity_in_bytes(OverriddenMethods) +
8026 llvm::capacity_in_bytes(Types) +
8027 llvm::capacity_in_bytes(VariableArrayTypes) +
8028 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
8029 }
8030
8031 /// getIntTypeForBitwidth -
8032 /// sets integer QualTy according to specified details:
8033 /// bitwidth, signed/unsigned.
8034 /// Returns empty type if there is no appropriate target types.
getIntTypeForBitwidth(unsigned DestWidth,unsigned Signed) const8035 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8036 unsigned Signed) const {
8037 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8038 CanQualType QualTy = getFromTargetType(Ty);
8039 if (!QualTy && DestWidth == 128)
8040 return Signed ? Int128Ty : UnsignedInt128Ty;
8041 return QualTy;
8042 }
8043
8044 /// getRealTypeForBitwidth -
8045 /// sets floating point QualTy according to specified bitwidth.
8046 /// Returns empty type if there is no appropriate target types.
getRealTypeForBitwidth(unsigned DestWidth) const8047 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8048 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8049 switch (Ty) {
8050 case TargetInfo::Float:
8051 return FloatTy;
8052 case TargetInfo::Double:
8053 return DoubleTy;
8054 case TargetInfo::LongDouble:
8055 return LongDoubleTy;
8056 case TargetInfo::NoFloat:
8057 return QualType();
8058 }
8059
8060 llvm_unreachable("Unhandled TargetInfo::RealType value");
8061 }
8062
setManglingNumber(const NamedDecl * ND,unsigned Number)8063 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8064 if (Number > 1)
8065 MangleNumbers[ND] = Number;
8066 }
8067
getManglingNumber(const NamedDecl * ND) const8068 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8069 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8070 MangleNumbers.find(ND);
8071 return I != MangleNumbers.end() ? I->second : 1;
8072 }
8073
8074 MangleNumberingContext &
getManglingNumberContext(const DeclContext * DC)8075 ASTContext::getManglingNumberContext(const DeclContext *DC) {
8076 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8077 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8078 if (!MCtx)
8079 MCtx = createMangleNumberingContext();
8080 return *MCtx;
8081 }
8082
createMangleNumberingContext() const8083 MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8084 return ABI->createMangleNumberingContext();
8085 }
8086
setParameterIndex(const ParmVarDecl * D,unsigned int index)8087 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8088 ParamIndices[D] = index;
8089 }
8090
getParameterIndex(const ParmVarDecl * D) const8091 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8092 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8093 assert(I != ParamIndices.end() &&
8094 "ParmIndices lacks entry set by ParmVarDecl");
8095 return I->second;
8096 }
8097
8098 APValue *
getMaterializedTemporaryValue(const MaterializeTemporaryExpr * E,bool MayCreate)8099 ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8100 bool MayCreate) {
8101 assert(E && E->getStorageDuration() == SD_Static &&
8102 "don't need to cache the computed value for this temporary");
8103 if (MayCreate)
8104 return &MaterializedTemporaryValues[E];
8105
8106 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8107 MaterializedTemporaryValues.find(E);
8108 return I == MaterializedTemporaryValues.end() ? 0 : &I->second;
8109 }
8110
AtomicUsesUnsupportedLibcall(const AtomicExpr * E) const8111 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8112 const llvm::Triple &T = getTargetInfo().getTriple();
8113 if (!T.isOSDarwin())
8114 return false;
8115
8116 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8117 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8118 return false;
8119
8120 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8121 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8122 uint64_t Size = sizeChars.getQuantity();
8123 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8124 unsigned Align = alignChars.getQuantity();
8125 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8126 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8127 }
8128
8129 namespace {
8130
8131 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8132 /// parents as defined by the \c RecursiveASTVisitor.
8133 ///
8134 /// Note that the relationship described here is purely in terms of AST
8135 /// traversal - there are other relationships (for example declaration context)
8136 /// in the AST that are better modeled by special matchers.
8137 ///
8138 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8139 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8140
8141 public:
8142 /// \brief Builds and returns the translation unit's parent map.
8143 ///
8144 /// The caller takes ownership of the returned \c ParentMap.
buildMap(TranslationUnitDecl & TU)8145 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8146 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8147 Visitor.TraverseDecl(&TU);
8148 return Visitor.Parents;
8149 }
8150
8151 private:
8152 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8153
ParentMapASTVisitor(ASTContext::ParentMap * Parents)8154 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8155 }
8156
shouldVisitTemplateInstantiations() const8157 bool shouldVisitTemplateInstantiations() const {
8158 return true;
8159 }
shouldVisitImplicitCode() const8160 bool shouldVisitImplicitCode() const {
8161 return true;
8162 }
8163 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8164 // are not triggered during data recursion.
shouldUseDataRecursionFor(clang::Stmt * S) const8165 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8166 return false;
8167 }
8168
8169 template <typename T>
TraverseNode(T * Node,bool (VisitorBase::* traverse)(T *))8170 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
8171 if (Node == NULL)
8172 return true;
8173 if (ParentStack.size() > 0)
8174 // FIXME: Currently we add the same parent multiple times, for example
8175 // when we visit all subexpressions of template instantiations; this is
8176 // suboptimal, bug benign: the only way to visit those is with
8177 // hasAncestor / hasParent, and those do not create new matches.
8178 // The plan is to enable DynTypedNode to be storable in a map or hash
8179 // map. The main problem there is to implement hash functions /
8180 // comparison operators for all types that DynTypedNode supports that
8181 // do not have pointer identity.
8182 (*Parents)[Node].push_back(ParentStack.back());
8183 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8184 bool Result = (this ->* traverse) (Node);
8185 ParentStack.pop_back();
8186 return Result;
8187 }
8188
TraverseDecl(Decl * DeclNode)8189 bool TraverseDecl(Decl *DeclNode) {
8190 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8191 }
8192
TraverseStmt(Stmt * StmtNode)8193 bool TraverseStmt(Stmt *StmtNode) {
8194 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8195 }
8196
8197 ASTContext::ParentMap *Parents;
8198 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8199
8200 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8201 };
8202
8203 } // end namespace
8204
8205 ASTContext::ParentVector
getParents(const ast_type_traits::DynTypedNode & Node)8206 ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8207 assert(Node.getMemoizationData() &&
8208 "Invariant broken: only nodes that support memoization may be "
8209 "used in the parent map.");
8210 if (!AllParents) {
8211 // We always need to run over the whole translation unit, as
8212 // hasAncestor can escape any subtree.
8213 AllParents.reset(
8214 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8215 }
8216 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8217 if (I == AllParents->end()) {
8218 return ParentVector();
8219 }
8220 return I->second;
8221 }
8222
8223 bool
ObjCMethodsAreEqual(const ObjCMethodDecl * MethodDecl,const ObjCMethodDecl * MethodImpl)8224 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8225 const ObjCMethodDecl *MethodImpl) {
8226 // No point trying to match an unavailable/deprecated mothod.
8227 if (MethodDecl->hasAttr<UnavailableAttr>()
8228 || MethodDecl->hasAttr<DeprecatedAttr>())
8229 return false;
8230 if (MethodDecl->getObjCDeclQualifier() !=
8231 MethodImpl->getObjCDeclQualifier())
8232 return false;
8233 if (!hasSameType(MethodDecl->getResultType(),
8234 MethodImpl->getResultType()))
8235 return false;
8236
8237 if (MethodDecl->param_size() != MethodImpl->param_size())
8238 return false;
8239
8240 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8241 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8242 EF = MethodDecl->param_end();
8243 IM != EM && IF != EF; ++IM, ++IF) {
8244 const ParmVarDecl *DeclVar = (*IF);
8245 const ParmVarDecl *ImplVar = (*IM);
8246 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8247 return false;
8248 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8249 return false;
8250 }
8251 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8252
8253 }
8254