Bug Summary

File:tools/clang/lib/AST/ASTContext.cpp
Warning:line 9425, column 15
Potential leak of memory pointed to by 'Vector'

Annotated Source Code

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