clang 19.0.0git
ASTContext.cpp
Go to the documentation of this file.
1//===- ASTContext.cpp - Context to hold long-lived AST nodes --------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the ASTContext interface.
10//
11//===----------------------------------------------------------------------===//
12
14#include "CXXABI.h"
15#include "Interp/Context.h"
16#include "clang/AST/APValue.h"
20#include "clang/AST/Attr.h"
22#include "clang/AST/CharUnits.h"
23#include "clang/AST/Comment.h"
24#include "clang/AST/Decl.h"
25#include "clang/AST/DeclBase.h"
26#include "clang/AST/DeclCXX.h"
28#include "clang/AST/DeclObjC.h"
33#include "clang/AST/Expr.h"
34#include "clang/AST/ExprCXX.h"
37#include "clang/AST/Mangle.h"
43#include "clang/AST/Stmt.h"
47#include "clang/AST/Type.h"
48#include "clang/AST/TypeLoc.h"
56#include "clang/Basic/LLVM.h"
58#include "clang/Basic/Linkage.h"
59#include "clang/Basic/Module.h"
69#include "llvm/ADT/APFixedPoint.h"
70#include "llvm/ADT/APInt.h"
71#include "llvm/ADT/APSInt.h"
72#include "llvm/ADT/ArrayRef.h"
73#include "llvm/ADT/DenseMap.h"
74#include "llvm/ADT/DenseSet.h"
75#include "llvm/ADT/FoldingSet.h"
76#include "llvm/ADT/PointerUnion.h"
77#include "llvm/ADT/STLExtras.h"
78#include "llvm/ADT/SmallPtrSet.h"
79#include "llvm/ADT/SmallVector.h"
80#include "llvm/ADT/StringExtras.h"
81#include "llvm/ADT/StringRef.h"
82#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
83#include "llvm/Support/Capacity.h"
84#include "llvm/Support/Casting.h"
85#include "llvm/Support/Compiler.h"
86#include "llvm/Support/ErrorHandling.h"
87#include "llvm/Support/MD5.h"
88#include "llvm/Support/MathExtras.h"
89#include "llvm/Support/raw_ostream.h"
90#include "llvm/TargetParser/Triple.h"
91#include <algorithm>
92#include <cassert>
93#include <cstddef>
94#include <cstdint>
95#include <cstdlib>
96#include <map>
97#include <memory>
98#include <optional>
99#include <string>
100#include <tuple>
101#include <utility>
102
103using namespace clang;
104
115
116/// \returns The locations that are relevant when searching for Doc comments
117/// related to \p D.
120 assert(D);
121
122 // User can not attach documentation to implicit declarations.
123 if (D->isImplicit())
124 return {};
125
126 // User can not attach documentation to implicit instantiations.
127 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
128 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
129 return {};
130 }
131
132 if (const auto *VD = dyn_cast<VarDecl>(D)) {
133 if (VD->isStaticDataMember() &&
134 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
135 return {};
136 }
137
138 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
139 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
140 return {};
141 }
142
143 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
144 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
145 if (TSK == TSK_ImplicitInstantiation ||
146 TSK == TSK_Undeclared)
147 return {};
148 }
149
150 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
151 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
152 return {};
153 }
154 if (const auto *TD = dyn_cast<TagDecl>(D)) {
155 // When tag declaration (but not definition!) is part of the
156 // decl-specifier-seq of some other declaration, it doesn't get comment
157 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
158 return {};
159 }
160 // TODO: handle comments for function parameters properly.
161 if (isa<ParmVarDecl>(D))
162 return {};
163
164 // TODO: we could look up template parameter documentation in the template
165 // documentation.
166 if (isa<TemplateTypeParmDecl>(D) ||
167 isa<NonTypeTemplateParmDecl>(D) ||
168 isa<TemplateTemplateParmDecl>(D))
169 return {};
170
172 // Find declaration location.
173 // For Objective-C declarations we generally don't expect to have multiple
174 // declarators, thus use declaration starting location as the "declaration
175 // location".
176 // For all other declarations multiple declarators are used quite frequently,
177 // so we use the location of the identifier as the "declaration location".
178 SourceLocation BaseLocation;
179 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
180 isa<ObjCPropertyDecl>(D) || isa<RedeclarableTemplateDecl>(D) ||
181 isa<ClassTemplateSpecializationDecl>(D) ||
182 // Allow association with Y across {} in `typedef struct X {} Y`.
183 isa<TypedefDecl>(D))
184 BaseLocation = D->getBeginLoc();
185 else
186 BaseLocation = D->getLocation();
187
188 if (!D->getLocation().isMacroID()) {
189 Locations.emplace_back(BaseLocation);
190 } else {
191 const auto *DeclCtx = D->getDeclContext();
192
193 // When encountering definitions generated from a macro (that are not
194 // contained by another declaration in the macro) we need to try and find
195 // the comment at the location of the expansion but if there is no comment
196 // there we should retry to see if there is a comment inside the macro as
197 // well. To this end we return first BaseLocation to first look at the
198 // expansion site, the second value is the spelling location of the
199 // beginning of the declaration defined inside the macro.
200 if (!(DeclCtx &&
201 Decl::castFromDeclContext(DeclCtx)->getLocation().isMacroID())) {
202 Locations.emplace_back(SourceMgr.getExpansionLoc(BaseLocation));
203 }
204
205 // We use Decl::getBeginLoc() and not just BaseLocation here to ensure that
206 // we don't refer to the macro argument location at the expansion site (this
207 // can happen if the name's spelling is provided via macro argument), and
208 // always to the declaration itself.
209 Locations.emplace_back(SourceMgr.getSpellingLoc(D->getBeginLoc()));
210 }
211
212 return Locations;
213}
214
216 const Decl *D, const SourceLocation RepresentativeLocForDecl,
217 const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
218 // If the declaration doesn't map directly to a location in a file, we
219 // can't find the comment.
220 if (RepresentativeLocForDecl.isInvalid() ||
221 !RepresentativeLocForDecl.isFileID())
222 return nullptr;
223
224 // If there are no comments anywhere, we won't find anything.
225 if (CommentsInTheFile.empty())
226 return nullptr;
227
228 // Decompose the location for the declaration and find the beginning of the
229 // file buffer.
230 const std::pair<FileID, unsigned> DeclLocDecomp =
231 SourceMgr.getDecomposedLoc(RepresentativeLocForDecl);
232
233 // Slow path.
234 auto OffsetCommentBehindDecl =
235 CommentsInTheFile.lower_bound(DeclLocDecomp.second);
236
237 // First check whether we have a trailing comment.
238 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
239 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
240 if ((CommentBehindDecl->isDocumentation() ||
241 LangOpts.CommentOpts.ParseAllComments) &&
242 CommentBehindDecl->isTrailingComment() &&
243 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
244 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
245
246 // Check that Doxygen trailing comment comes after the declaration, starts
247 // on the same line and in the same file as the declaration.
248 if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) ==
249 Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first,
250 OffsetCommentBehindDecl->first)) {
251 return CommentBehindDecl;
252 }
253 }
254 }
255
256 // The comment just after the declaration was not a trailing comment.
257 // Let's look at the previous comment.
258 if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
259 return nullptr;
260
261 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
262 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
263
264 // Check that we actually have a non-member Doxygen comment.
265 if (!(CommentBeforeDecl->isDocumentation() ||
266 LangOpts.CommentOpts.ParseAllComments) ||
267 CommentBeforeDecl->isTrailingComment())
268 return nullptr;
269
270 // Decompose the end of the comment.
271 const unsigned CommentEndOffset =
272 Comments.getCommentEndOffset(CommentBeforeDecl);
273
274 // Get the corresponding buffer.
275 bool Invalid = false;
276 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
277 &Invalid).data();
278 if (Invalid)
279 return nullptr;
280
281 // Extract text between the comment and declaration.
282 StringRef Text(Buffer + CommentEndOffset,
283 DeclLocDecomp.second - CommentEndOffset);
284
285 // There should be no other declarations or preprocessor directives between
286 // comment and declaration.
287 if (Text.find_last_of(";{}#@") != StringRef::npos)
288 return nullptr;
289
290 return CommentBeforeDecl;
291}
292
294 const auto DeclLocs = getDeclLocsForCommentSearch(D, SourceMgr);
295
296 for (const auto DeclLoc : DeclLocs) {
297 // If the declaration doesn't map directly to a location in a file, we
298 // can't find the comment.
299 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
300 continue;
301
304 CommentsLoaded = true;
305 }
306
307 if (Comments.empty())
308 continue;
309
310 const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first;
311 if (!File.isValid())
312 continue;
313
314 const auto CommentsInThisFile = Comments.getCommentsInFile(File);
315 if (!CommentsInThisFile || CommentsInThisFile->empty())
316 continue;
317
318 if (RawComment *Comment =
319 getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile))
320 return Comment;
321 }
322
323 return nullptr;
324}
325
327 assert(LangOpts.RetainCommentsFromSystemHeaders ||
328 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
329 Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
330}
331
332/// If we have a 'templated' declaration for a template, adjust 'D' to
333/// refer to the actual template.
334/// If we have an implicit instantiation, adjust 'D' to refer to template.
335static const Decl &adjustDeclToTemplate(const Decl &D) {
336 if (const auto *FD = dyn_cast<FunctionDecl>(&D)) {
337 // Is this function declaration part of a function template?
338 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
339 return *FTD;
340
341 // Nothing to do if function is not an implicit instantiation.
342 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
343 return D;
344
345 // Function is an implicit instantiation of a function template?
346 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
347 return *FTD;
348
349 // Function is instantiated from a member definition of a class template?
350 if (const FunctionDecl *MemberDecl =
352 return *MemberDecl;
353
354 return D;
355 }
356 if (const auto *VD = dyn_cast<VarDecl>(&D)) {
357 // Static data member is instantiated from a member definition of a class
358 // template?
359 if (VD->isStaticDataMember())
360 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
361 return *MemberDecl;
362
363 return D;
364 }
365 if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) {
366 // Is this class declaration part of a class template?
367 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
368 return *CTD;
369
370 // Class is an implicit instantiation of a class template or partial
371 // specialization?
372 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
373 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
374 return D;
375 llvm::PointerUnion<ClassTemplateDecl *,
378 return PU.is<ClassTemplateDecl *>()
379 ? *static_cast<const Decl *>(PU.get<ClassTemplateDecl *>())
380 : *static_cast<const Decl *>(
382 }
383
384 // Class is instantiated from a member definition of a class template?
385 if (const MemberSpecializationInfo *Info =
386 CRD->getMemberSpecializationInfo())
387 return *Info->getInstantiatedFrom();
388
389 return D;
390 }
391 if (const auto *ED = dyn_cast<EnumDecl>(&D)) {
392 // Enum is instantiated from a member definition of a class template?
393 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
394 return *MemberDecl;
395
396 return D;
397 }
398 // FIXME: Adjust alias templates?
399 return D;
400}
401
403 const Decl *D,
404 const Decl **OriginalDecl) const {
405 if (!D) {
406 if (OriginalDecl)
407 OriginalDecl = nullptr;
408 return nullptr;
409 }
410
411 D = &adjustDeclToTemplate(*D);
412
413 // Any comment directly attached to D?
414 {
415 auto DeclComment = DeclRawComments.find(D);
416 if (DeclComment != DeclRawComments.end()) {
417 if (OriginalDecl)
418 *OriginalDecl = D;
419 return DeclComment->second;
420 }
421 }
422
423 // Any comment attached to any redeclaration of D?
424 const Decl *CanonicalD = D->getCanonicalDecl();
425 if (!CanonicalD)
426 return nullptr;
427
428 {
429 auto RedeclComment = RedeclChainComments.find(CanonicalD);
430 if (RedeclComment != RedeclChainComments.end()) {
431 if (OriginalDecl)
432 *OriginalDecl = RedeclComment->second;
433 auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second);
434 assert(CommentAtRedecl != DeclRawComments.end() &&
435 "This decl is supposed to have comment attached.");
436 return CommentAtRedecl->second;
437 }
438 }
439
440 // Any redeclarations of D that we haven't checked for comments yet?
441 // We can't use DenseMap::iterator directly since it'd get invalid.
442 auto LastCheckedRedecl = [this, CanonicalD]() -> const Decl * {
443 return CommentlessRedeclChains.lookup(CanonicalD);
444 }();
445
446 for (const auto Redecl : D->redecls()) {
447 assert(Redecl);
448 // Skip all redeclarations that have been checked previously.
449 if (LastCheckedRedecl) {
450 if (LastCheckedRedecl == Redecl) {
451 LastCheckedRedecl = nullptr;
452 }
453 continue;
454 }
455 const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl);
456 if (RedeclComment) {
457 cacheRawCommentForDecl(*Redecl, *RedeclComment);
458 if (OriginalDecl)
459 *OriginalDecl = Redecl;
460 return RedeclComment;
461 }
462 CommentlessRedeclChains[CanonicalD] = Redecl;
463 }
464
465 if (OriginalDecl)
466 *OriginalDecl = nullptr;
467 return nullptr;
468}
469
471 const RawComment &Comment) const {
472 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
473 DeclRawComments.try_emplace(&OriginalD, &Comment);
474 const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl();
475 RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD);
476 CommentlessRedeclChains.erase(CanonicalDecl);
477}
478
479static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
481 const DeclContext *DC = ObjCMethod->getDeclContext();
482 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
483 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
484 if (!ID)
485 return;
486 // Add redeclared method here.
487 for (const auto *Ext : ID->known_extensions()) {
488 if (ObjCMethodDecl *RedeclaredMethod =
489 Ext->getMethod(ObjCMethod->getSelector(),
490 ObjCMethod->isInstanceMethod()))
491 Redeclared.push_back(RedeclaredMethod);
492 }
493 }
494}
495
497 const Preprocessor *PP) {
498 if (Comments.empty() || Decls.empty())
499 return;
500
501 FileID File;
502 for (const Decl *D : Decls) {
503 if (D->isInvalidDecl())
504 continue;
505
506 D = &adjustDeclToTemplate(*D);
507 SourceLocation Loc = D->getLocation();
508 if (Loc.isValid()) {
509 // See if there are any new comments that are not attached to a decl.
510 // The location doesn't have to be precise - we care only about the file.
511 File = SourceMgr.getDecomposedLoc(Loc).first;
512 break;
513 }
514 }
515
516 if (File.isInvalid())
517 return;
518
519 auto CommentsInThisFile = Comments.getCommentsInFile(File);
520 if (!CommentsInThisFile || CommentsInThisFile->empty() ||
521 CommentsInThisFile->rbegin()->second->isAttached())
522 return;
523
524 // There is at least one comment not attached to a decl.
525 // Maybe it should be attached to one of Decls?
526 //
527 // Note that this way we pick up not only comments that precede the
528 // declaration, but also comments that *follow* the declaration -- thanks to
529 // the lookahead in the lexer: we've consumed the semicolon and looked
530 // ahead through comments.
531 for (const Decl *D : Decls) {
532 assert(D);
533 if (D->isInvalidDecl())
534 continue;
535
536 D = &adjustDeclToTemplate(*D);
537
538 if (DeclRawComments.count(D) > 0)
539 continue;
540
541 const auto DeclLocs = getDeclLocsForCommentSearch(D, SourceMgr);
542
543 for (const auto DeclLoc : DeclLocs) {
544 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
545 continue;
546
547 if (RawComment *const DocComment = getRawCommentForDeclNoCacheImpl(
548 D, DeclLoc, *CommentsInThisFile)) {
549 cacheRawCommentForDecl(*D, *DocComment);
550 comments::FullComment *FC = DocComment->parse(*this, PP, D);
551 ParsedComments[D->getCanonicalDecl()] = FC;
552 break;
553 }
554 }
555 }
556}
557
559 const Decl *D) const {
560 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
561 ThisDeclInfo->CommentDecl = D;
562 ThisDeclInfo->IsFilled = false;
563 ThisDeclInfo->fill();
564 ThisDeclInfo->CommentDecl = FC->getDecl();
565 if (!ThisDeclInfo->TemplateParameters)
566 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
568 new (*this) comments::FullComment(FC->getBlocks(),
569 ThisDeclInfo);
570 return CFC;
571}
572
575 return RC ? RC->parse(*this, nullptr, D) : nullptr;
576}
577
579 const Decl *D,
580 const Preprocessor *PP) const {
581 if (!D || D->isInvalidDecl())
582 return nullptr;
583 D = &adjustDeclToTemplate(*D);
584
585 const Decl *Canonical = D->getCanonicalDecl();
586 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
587 ParsedComments.find(Canonical);
588
589 if (Pos != ParsedComments.end()) {
590 if (Canonical != D) {
591 comments::FullComment *FC = Pos->second;
593 return CFC;
594 }
595 return Pos->second;
596 }
597
598 const Decl *OriginalDecl = nullptr;
599
600 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
601 if (!RC) {
602 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
604 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
605 if (OMD && OMD->isPropertyAccessor())
606 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
607 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
608 return cloneFullComment(FC, D);
609 if (OMD)
610 addRedeclaredMethods(OMD, Overridden);
611 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
612 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
613 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
614 return cloneFullComment(FC, D);
615 }
616 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
617 // Attach any tag type's documentation to its typedef if latter
618 // does not have one of its own.
619 QualType QT = TD->getUnderlyingType();
620 if (const auto *TT = QT->getAs<TagType>())
621 if (const Decl *TD = TT->getDecl())
623 return cloneFullComment(FC, D);
624 }
625 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
626 while (IC->getSuperClass()) {
627 IC = IC->getSuperClass();
629 return cloneFullComment(FC, D);
630 }
631 }
632 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
633 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
635 return cloneFullComment(FC, D);
636 }
637 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
638 if (!(RD = RD->getDefinition()))
639 return nullptr;
640 // Check non-virtual bases.
641 for (const auto &I : RD->bases()) {
642 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
643 continue;
644 QualType Ty = I.getType();
645 if (Ty.isNull())
646 continue;
648 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
649 continue;
650
652 return cloneFullComment(FC, D);
653 }
654 }
655 // Check virtual bases.
656 for (const auto &I : RD->vbases()) {
657 if (I.getAccessSpecifier() != AS_public)
658 continue;
659 QualType Ty = I.getType();
660 if (Ty.isNull())
661 continue;
662 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
663 if (!(VirtualBase= VirtualBase->getDefinition()))
664 continue;
666 return cloneFullComment(FC, D);
667 }
668 }
669 }
670 return nullptr;
671 }
672
673 // If the RawComment was attached to other redeclaration of this Decl, we
674 // should parse the comment in context of that other Decl. This is important
675 // because comments can contain references to parameter names which can be
676 // different across redeclarations.
677 if (D != OriginalDecl && OriginalDecl)
678 return getCommentForDecl(OriginalDecl, PP);
679
680 comments::FullComment *FC = RC->parse(*this, PP, D);
681 ParsedComments[Canonical] = FC;
682 return FC;
683}
684
685void
686ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
687 const ASTContext &C,
689 ID.AddInteger(Parm->getDepth());
690 ID.AddInteger(Parm->getPosition());
691 ID.AddBoolean(Parm->isParameterPack());
692
694 ID.AddInteger(Params->size());
696 PEnd = Params->end();
697 P != PEnd; ++P) {
698 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
699 ID.AddInteger(0);
700 ID.AddBoolean(TTP->isParameterPack());
701 if (TTP->isExpandedParameterPack()) {
702 ID.AddBoolean(true);
703 ID.AddInteger(TTP->getNumExpansionParameters());
704 } else
705 ID.AddBoolean(false);
706 continue;
707 }
708
709 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
710 ID.AddInteger(1);
711 ID.AddBoolean(NTTP->isParameterPack());
712 ID.AddPointer(C.getUnconstrainedType(C.getCanonicalType(NTTP->getType()))
713 .getAsOpaquePtr());
714 if (NTTP->isExpandedParameterPack()) {
715 ID.AddBoolean(true);
716 ID.AddInteger(NTTP->getNumExpansionTypes());
717 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
718 QualType T = NTTP->getExpansionType(I);
719 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
720 }
721 } else
722 ID.AddBoolean(false);
723 continue;
724 }
725
726 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
727 ID.AddInteger(2);
728 Profile(ID, C, TTP);
729 }
730}
731
733ASTContext::getCanonicalTemplateTemplateParmDecl(
734 TemplateTemplateParmDecl *TTP) const {
735 // Check if we already have a canonical template template parameter.
736 llvm::FoldingSetNodeID ID;
737 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
738 void *InsertPos = nullptr;
739 CanonicalTemplateTemplateParm *Canonical
740 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
741 if (Canonical)
742 return Canonical->getParam();
743
744 // Build a canonical template parameter list.
746 SmallVector<NamedDecl *, 4> CanonParams;
747 CanonParams.reserve(Params->size());
749 PEnd = Params->end();
750 P != PEnd; ++P) {
751 // Note that, per C++20 [temp.over.link]/6, when determining whether
752 // template-parameters are equivalent, constraints are ignored.
753 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
756 TTP->getDepth(), TTP->getIndex(), nullptr, false,
757 TTP->isParameterPack(), /*HasTypeConstraint=*/false,
759 ? std::optional<unsigned>(TTP->getNumExpansionParameters())
760 : std::nullopt);
761 CanonParams.push_back(NewTTP);
762 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
763 QualType T = getUnconstrainedType(getCanonicalType(NTTP->getType()));
766 if (NTTP->isExpandedParameterPack()) {
767 SmallVector<QualType, 2> ExpandedTypes;
769 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
770 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
771 ExpandedTInfos.push_back(
772 getTrivialTypeSourceInfo(ExpandedTypes.back()));
773 }
774
778 NTTP->getDepth(),
779 NTTP->getPosition(), nullptr,
780 T,
781 TInfo,
782 ExpandedTypes,
783 ExpandedTInfos);
784 } else {
788 NTTP->getDepth(),
789 NTTP->getPosition(), nullptr,
790 T,
791 NTTP->isParameterPack(),
792 TInfo);
793 }
794 CanonParams.push_back(Param);
795 } else
796 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
797 cast<TemplateTemplateParmDecl>(*P)));
798 }
799
802 TTP->getPosition(), TTP->isParameterPack(), nullptr,
804 CanonParams, SourceLocation(),
805 /*RequiresClause=*/nullptr));
806
807 // Get the new insert position for the node we care about.
808 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
809 assert(!Canonical && "Shouldn't be in the map!");
810 (void)Canonical;
811
812 // Create the canonical template template parameter entry.
813 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
814 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
815 return CanonTTP;
816}
817
819 auto Kind = getTargetInfo().getCXXABI().getKind();
820 return getLangOpts().CXXABI.value_or(Kind);
821}
822
823CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
824 if (!LangOpts.CPlusPlus) return nullptr;
825
826 switch (getCXXABIKind()) {
827 case TargetCXXABI::AppleARM64:
828 case TargetCXXABI::Fuchsia:
829 case TargetCXXABI::GenericARM: // Same as Itanium at this level
830 case TargetCXXABI::iOS:
831 case TargetCXXABI::WatchOS:
832 case TargetCXXABI::GenericAArch64:
833 case TargetCXXABI::GenericMIPS:
834 case TargetCXXABI::GenericItanium:
835 case TargetCXXABI::WebAssembly:
836 case TargetCXXABI::XL:
837 return CreateItaniumCXXABI(*this);
838 case TargetCXXABI::Microsoft:
839 return CreateMicrosoftCXXABI(*this);
840 }
841 llvm_unreachable("Invalid CXXABI type!");
842}
843
845 if (!InterpContext) {
846 InterpContext.reset(new interp::Context(*this));
847 }
848 return *InterpContext.get();
849}
850
852 if (!ParentMapCtx)
853 ParentMapCtx.reset(new ParentMapContext(*this));
854 return *ParentMapCtx.get();
855}
856
858 const LangOptions &LangOpts) {
859 switch (LangOpts.getAddressSpaceMapMangling()) {
861 return TI.useAddressSpaceMapMangling();
863 return true;
865 return false;
866 }
867 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
868}
869
871 IdentifierTable &idents, SelectorTable &sels,
872 Builtin::Context &builtins, TranslationUnitKind TUKind)
873 : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize),
874 DependentSizedArrayTypes(this_()), DependentSizedExtVectorTypes(this_()),
875 DependentAddressSpaceTypes(this_()), DependentVectorTypes(this_()),
876 DependentSizedMatrixTypes(this_()),
877 FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize),
878 DependentTypeOfExprTypes(this_()), DependentDecltypeTypes(this_()),
879 TemplateSpecializationTypes(this_()),
880 DependentTemplateSpecializationTypes(this_()), AutoTypes(this_()),
881 DependentBitIntTypes(this_()), SubstTemplateTemplateParmPacks(this_()),
882 CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
883 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
884 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
885 LangOpts.XRayNeverInstrumentFiles,
886 LangOpts.XRayAttrListFiles, SM)),
887 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
888 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
889 BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this),
890 Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
891 CompCategories(this_()), LastSDM(nullptr, 0) {
893}
894
896 // Release the DenseMaps associated with DeclContext objects.
897 // FIXME: Is this the ideal solution?
898 ReleaseDeclContextMaps();
899
900 // Call all of the deallocation functions on all of their targets.
901 for (auto &Pair : Deallocations)
902 (Pair.first)(Pair.second);
903 Deallocations.clear();
904
905 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
906 // because they can contain DenseMaps.
907 for (llvm::DenseMap<const ObjCContainerDecl*,
908 const ASTRecordLayout*>::iterator
909 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
910 // Increment in loop to prevent using deallocated memory.
911 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
912 R->Destroy(*this);
913 ObjCLayouts.clear();
914
915 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
916 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
917 // Increment in loop to prevent using deallocated memory.
918 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
919 R->Destroy(*this);
920 }
921 ASTRecordLayouts.clear();
922
923 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
924 AEnd = DeclAttrs.end();
925 A != AEnd; ++A)
926 A->second->~AttrVec();
927 DeclAttrs.clear();
928
929 for (const auto &Value : ModuleInitializers)
930 Value.second->~PerModuleInitializers();
931 ModuleInitializers.clear();
932}
933
935
936void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
937 TraversalScope = TopLevelDecls;
939}
940
941void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
942 Deallocations.push_back({Callback, Data});
943}
944
945void
947 ExternalSource = std::move(Source);
948}
949
951 llvm::errs() << "\n*** AST Context Stats:\n";
952 llvm::errs() << " " << Types.size() << " types total.\n";
953
954 unsigned counts[] = {
955#define TYPE(Name, Parent) 0,
956#define ABSTRACT_TYPE(Name, Parent)
957#include "clang/AST/TypeNodes.inc"
958 0 // Extra
959 };
960
961 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
962 Type *T = Types[i];
963 counts[(unsigned)T->getTypeClass()]++;
964 }
965
966 unsigned Idx = 0;
967 unsigned TotalBytes = 0;
968#define TYPE(Name, Parent) \
969 if (counts[Idx]) \
970 llvm::errs() << " " << counts[Idx] << " " << #Name \
971 << " types, " << sizeof(Name##Type) << " each " \
972 << "(" << counts[Idx] * sizeof(Name##Type) \
973 << " bytes)\n"; \
974 TotalBytes += counts[Idx] * sizeof(Name##Type); \
975 ++Idx;
976#define ABSTRACT_TYPE(Name, Parent)
977#include "clang/AST/TypeNodes.inc"
978
979 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
980
981 // Implicit special member functions.
982 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
984 << " implicit default constructors created\n";
985 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
987 << " implicit copy constructors created\n";
989 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
991 << " implicit move constructors created\n";
992 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
994 << " implicit copy assignment operators created\n";
996 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
998 << " implicit move assignment operators created\n";
999 llvm::errs() << NumImplicitDestructorsDeclared << "/"
1001 << " implicit destructors created\n";
1002
1003 if (ExternalSource) {
1004 llvm::errs() << "\n";
1006 }
1007
1008 BumpAlloc.PrintStats();
1009}
1010
1012 bool NotifyListeners) {
1013 if (NotifyListeners)
1014 if (auto *Listener = getASTMutationListener())
1016
1017 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
1018}
1019
1021 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1022 if (It == MergedDefModules.end())
1023 return;
1024
1025 auto &Merged = It->second;
1027 for (Module *&M : Merged)
1028 if (!Found.insert(M).second)
1029 M = nullptr;
1030 llvm::erase(Merged, nullptr);
1031}
1032
1035 auto MergedIt =
1036 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
1037 if (MergedIt == MergedDefModules.end())
1038 return std::nullopt;
1039 return MergedIt->second;
1040}
1041
1042void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1043 if (LazyInitializers.empty())
1044 return;
1045
1046 auto *Source = Ctx.getExternalSource();
1047 assert(Source && "lazy initializers but no external source");
1048
1049 auto LazyInits = std::move(LazyInitializers);
1050 LazyInitializers.clear();
1051
1052 for (auto ID : LazyInits)
1053 Initializers.push_back(Source->GetExternalDecl(ID));
1054
1055 assert(LazyInitializers.empty() &&
1056 "GetExternalDecl for lazy module initializer added more inits");
1057}
1058
1060 // One special case: if we add a module initializer that imports another
1061 // module, and that module's only initializer is an ImportDecl, simplify.
1062 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1063 auto It = ModuleInitializers.find(ID->getImportedModule());
1064
1065 // Maybe the ImportDecl does nothing at all. (Common case.)
1066 if (It == ModuleInitializers.end())
1067 return;
1068
1069 // Maybe the ImportDecl only imports another ImportDecl.
1070 auto &Imported = *It->second;
1071 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1072 Imported.resolve(*this);
1073 auto *OnlyDecl = Imported.Initializers.front();
1074 if (isa<ImportDecl>(OnlyDecl))
1075 D = OnlyDecl;
1076 }
1077 }
1078
1079 auto *&Inits = ModuleInitializers[M];
1080 if (!Inits)
1081 Inits = new (*this) PerModuleInitializers;
1082 Inits->Initializers.push_back(D);
1083}
1084
1086 auto *&Inits = ModuleInitializers[M];
1087 if (!Inits)
1088 Inits = new (*this) PerModuleInitializers;
1089 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1090 IDs.begin(), IDs.end());
1091}
1092
1094 auto It = ModuleInitializers.find(M);
1095 if (It == ModuleInitializers.end())
1096 return std::nullopt;
1097
1098 auto *Inits = It->second;
1099 Inits->resolve(*this);
1100 return Inits->Initializers;
1101}
1102
1104 assert(M->isNamedModule());
1105 assert(!CurrentCXXNamedModule &&
1106 "We should set named module for ASTContext for only once");
1107 CurrentCXXNamedModule = M;
1108}
1109
1111 if (!ExternCContext)
1112 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1113
1114 return ExternCContext;
1115}
1116
1119 const IdentifierInfo *II) const {
1120 auto *BuiltinTemplate =
1122 BuiltinTemplate->setImplicit();
1123 getTranslationUnitDecl()->addDecl(BuiltinTemplate);
1124
1125 return BuiltinTemplate;
1126}
1127
1130 if (!MakeIntegerSeqDecl)
1133 return MakeIntegerSeqDecl;
1134}
1135
1138 if (!TypePackElementDecl)
1141 return TypePackElementDecl;
1142}
1143
1145 RecordDecl::TagKind TK) const {
1146 SourceLocation Loc;
1147 RecordDecl *NewDecl;
1148 if (getLangOpts().CPlusPlus)
1149 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1150 Loc, &Idents.get(Name));
1151 else
1152 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1153 &Idents.get(Name));
1154 NewDecl->setImplicit();
1155 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1156 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1157 return NewDecl;
1158}
1159
1161 StringRef Name) const {
1164 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1165 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1166 NewDecl->setImplicit();
1167 return NewDecl;
1168}
1169
1171 if (!Int128Decl)
1172 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1173 return Int128Decl;
1174}
1175
1177 if (!UInt128Decl)
1178 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1179 return UInt128Decl;
1180}
1181
1182void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1183 auto *Ty = new (*this, alignof(BuiltinType)) BuiltinType(K);
1185 Types.push_back(Ty);
1186}
1187
1189 const TargetInfo *AuxTarget) {
1190 assert((!this->Target || this->Target == &Target) &&
1191 "Incorrect target reinitialization");
1192 assert(VoidTy.isNull() && "Context reinitialized?");
1193
1194 this->Target = &Target;
1195 this->AuxTarget = AuxTarget;
1196
1197 ABI.reset(createCXXABI(Target));
1198 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1199
1200 // C99 6.2.5p19.
1201 InitBuiltinType(VoidTy, BuiltinType::Void);
1202
1203 // C99 6.2.5p2.
1204 InitBuiltinType(BoolTy, BuiltinType::Bool);
1205 // C99 6.2.5p3.
1206 if (LangOpts.CharIsSigned)
1207 InitBuiltinType(CharTy, BuiltinType::Char_S);
1208 else
1209 InitBuiltinType(CharTy, BuiltinType::Char_U);
1210 // C99 6.2.5p4.
1211 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1212 InitBuiltinType(ShortTy, BuiltinType::Short);
1213 InitBuiltinType(IntTy, BuiltinType::Int);
1214 InitBuiltinType(LongTy, BuiltinType::Long);
1215 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1216
1217 // C99 6.2.5p6.
1218 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1219 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1220 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1221 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1222 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1223
1224 // C99 6.2.5p10.
1225 InitBuiltinType(FloatTy, BuiltinType::Float);
1226 InitBuiltinType(DoubleTy, BuiltinType::Double);
1227 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1228
1229 // GNU extension, __float128 for IEEE quadruple precision
1230 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1231
1232 // __ibm128 for IBM extended precision
1233 InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128);
1234
1235 // C11 extension ISO/IEC TS 18661-3
1236 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1237
1238 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1239 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1240 InitBuiltinType(AccumTy, BuiltinType::Accum);
1241 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1242 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1243 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1244 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1245 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1246 InitBuiltinType(FractTy, BuiltinType::Fract);
1247 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1248 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1249 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1250 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1251 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1252 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1253 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1254 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1255 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1256 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1257 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1258 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1259 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1260 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1261 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1262 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
1263
1264 // GNU extension, 128-bit integers.
1265 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1266 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1267
1268 // C++ 3.9.1p5
1269 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1270 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1271 else // -fshort-wchar makes wchar_t be unsigned.
1272 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1273 if (LangOpts.CPlusPlus && LangOpts.WChar)
1275 else {
1276 // C99 (or C++ using -fno-wchar).
1277 WideCharTy = getFromTargetType(Target.getWCharType());
1278 }
1279
1280 WIntTy = getFromTargetType(Target.getWIntType());
1281
1282 // C++20 (proposed)
1283 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1284
1285 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1286 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1287 else // C99
1288 Char16Ty = getFromTargetType(Target.getChar16Type());
1289
1290 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1291 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1292 else // C99
1293 Char32Ty = getFromTargetType(Target.getChar32Type());
1294
1295 // Placeholder type for type-dependent expressions whose type is
1296 // completely unknown. No code should ever check a type against
1297 // DependentTy and users should never see it; however, it is here to
1298 // help diagnose failures to properly check for type-dependent
1299 // expressions.
1300 InitBuiltinType(DependentTy, BuiltinType::Dependent);
1301
1302 // Placeholder type for functions.
1303 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1304
1305 // Placeholder type for bound members.
1306 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1307
1308 // Placeholder type for pseudo-objects.
1309 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1310
1311 // "any" type; useful for debugger-like clients.
1312 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1313
1314 // Placeholder type for unbridged ARC casts.
1315 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1316
1317 // Placeholder type for builtin functions.
1318 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1319
1320 // Placeholder type for OMP array sections.
1321 if (LangOpts.OpenMP) {
1322 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1323 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1324 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1325 }
1326 // Placeholder type for OpenACC array sections.
1327 if (LangOpts.OpenACC) {
1328 // FIXME: Once we implement OpenACC array sections in Sema, this will either
1329 // be combined with the OpenMP type, or given its own type. In the meantime,
1330 // just use the OpenMP type so that parsing can work.
1331 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1332 }
1333 if (LangOpts.MatrixTypes)
1334 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1335
1336 // Builtin types for 'id', 'Class', and 'SEL'.
1337 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1338 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1339 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1340
1341 if (LangOpts.OpenCL) {
1342#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1343 InitBuiltinType(SingletonId, BuiltinType::Id);
1344#include "clang/Basic/OpenCLImageTypes.def"
1345
1346 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1347 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1348 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1349 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1350 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1351
1352#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1353 InitBuiltinType(Id##Ty, BuiltinType::Id);
1354#include "clang/Basic/OpenCLExtensionTypes.def"
1355 }
1356
1357 if (Target.hasAArch64SVETypes()) {
1358#define SVE_TYPE(Name, Id, SingletonId) \
1359 InitBuiltinType(SingletonId, BuiltinType::Id);
1360#include "clang/Basic/AArch64SVEACLETypes.def"
1361 }
1362
1363 if (Target.getTriple().isPPC64()) {
1364#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1365 InitBuiltinType(Id##Ty, BuiltinType::Id);
1366#include "clang/Basic/PPCTypes.def"
1367#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1368 InitBuiltinType(Id##Ty, BuiltinType::Id);
1369#include "clang/Basic/PPCTypes.def"
1370 }
1371
1372 if (Target.hasRISCVVTypes()) {
1373#define RVV_TYPE(Name, Id, SingletonId) \
1374 InitBuiltinType(SingletonId, BuiltinType::Id);
1375#include "clang/Basic/RISCVVTypes.def"
1376 }
1377
1378 if (Target.getTriple().isWasm() && Target.hasFeature("reference-types")) {
1379#define WASM_TYPE(Name, Id, SingletonId) \
1380 InitBuiltinType(SingletonId, BuiltinType::Id);
1381#include "clang/Basic/WebAssemblyReferenceTypes.def"
1382 }
1383
1384 // Builtin type for __objc_yes and __objc_no
1385 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1387
1388 ObjCConstantStringType = QualType();
1389
1390 ObjCSuperType = QualType();
1391
1392 // void * type
1393 if (LangOpts.OpenCLGenericAddressSpace) {
1394 auto Q = VoidTy.getQualifiers();
1398 } else {
1400 }
1401
1402 // nullptr type (C++0x 2.14.7)
1403 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1404
1405 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1406 InitBuiltinType(HalfTy, BuiltinType::Half);
1407
1408 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1409
1410 // Builtin type used to help define __builtin_va_list.
1411 VaListTagDecl = nullptr;
1412
1413 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1414 if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1417 }
1418}
1419
1421 return SourceMgr.getDiagnostics();
1422}
1423
1425 AttrVec *&Result = DeclAttrs[D];
1426 if (!Result) {
1427 void *Mem = Allocate(sizeof(AttrVec));
1428 Result = new (Mem) AttrVec;
1429 }
1430
1431 return *Result;
1432}
1433
1434/// Erase the attributes corresponding to the given declaration.
1436 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1437 if (Pos != DeclAttrs.end()) {
1438 Pos->second->~AttrVec();
1439 DeclAttrs.erase(Pos);
1440 }
1441}
1442
1443// FIXME: Remove ?
1446 assert(Var->isStaticDataMember() && "Not a static data member");
1448 .dyn_cast<MemberSpecializationInfo *>();
1449}
1450
1453 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1454 TemplateOrInstantiation.find(Var);
1455 if (Pos == TemplateOrInstantiation.end())
1456 return {};
1457
1458 return Pos->second;
1459}
1460
1461void
1464 SourceLocation PointOfInstantiation) {
1465 assert(Inst->isStaticDataMember() && "Not a static data member");
1466 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1468 Tmpl, TSK, PointOfInstantiation));
1469}
1470
1471void
1474 assert(!TemplateOrInstantiation[Inst] &&
1475 "Already noted what the variable was instantiated from");
1476 TemplateOrInstantiation[Inst] = TSI;
1477}
1478
1479NamedDecl *
1481 return InstantiatedFromUsingDecl.lookup(UUD);
1482}
1483
1484void
1486 assert((isa<UsingDecl>(Pattern) ||
1487 isa<UnresolvedUsingValueDecl>(Pattern) ||
1488 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1489 "pattern decl is not a using decl");
1490 assert((isa<UsingDecl>(Inst) ||
1491 isa<UnresolvedUsingValueDecl>(Inst) ||
1492 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1493 "instantiation did not produce a using decl");
1494 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1495 InstantiatedFromUsingDecl[Inst] = Pattern;
1496}
1497
1500 return InstantiatedFromUsingEnumDecl.lookup(UUD);
1501}
1502
1504 UsingEnumDecl *Pattern) {
1505 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
1506 InstantiatedFromUsingEnumDecl[Inst] = Pattern;
1507}
1508
1511 return InstantiatedFromUsingShadowDecl.lookup(Inst);
1512}
1513
1514void
1516 UsingShadowDecl *Pattern) {
1517 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1518 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1519}
1520
1522 return InstantiatedFromUnnamedFieldDecl.lookup(Field);
1523}
1524
1526 FieldDecl *Tmpl) {
1527 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1528 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1529 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1530 "Already noted what unnamed field was instantiated from");
1531
1532 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1533}
1534
1537 return overridden_methods(Method).begin();
1538}
1539
1542 return overridden_methods(Method).end();
1543}
1544
1545unsigned
1547 auto Range = overridden_methods(Method);
1548 return Range.end() - Range.begin();
1549}
1550
1553 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1554 OverriddenMethods.find(Method->getCanonicalDecl());
1555 if (Pos == OverriddenMethods.end())
1556 return overridden_method_range(nullptr, nullptr);
1557 return overridden_method_range(Pos->second.begin(), Pos->second.end());
1558}
1559
1561 const CXXMethodDecl *Overridden) {
1562 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1563 OverriddenMethods[Method].push_back(Overridden);
1564}
1565
1567 const NamedDecl *D,
1568 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1569 assert(D);
1570
1571 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1572 Overridden.append(overridden_methods_begin(CXXMethod),
1573 overridden_methods_end(CXXMethod));
1574 return;
1575 }
1576
1577 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1578 if (!Method)
1579 return;
1580
1582 Method->getOverriddenMethods(OverDecls);
1583 Overridden.append(OverDecls.begin(), OverDecls.end());
1584}
1585
1587 assert(!Import->getNextLocalImport() &&
1588 "Import declaration already in the chain");
1589 assert(!Import->isFromASTFile() && "Non-local import declaration");
1590 if (!FirstLocalImport) {
1591 FirstLocalImport = Import;
1592 LastLocalImport = Import;
1593 return;
1594 }
1595
1596 LastLocalImport->setNextLocalImport(Import);
1597 LastLocalImport = Import;
1598}
1599
1600//===----------------------------------------------------------------------===//
1601// Type Sizing and Analysis
1602//===----------------------------------------------------------------------===//
1603
1604/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1605/// scalar floating point type.
1606const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1607 switch (T->castAs<BuiltinType>()->getKind()) {
1608 default:
1609 llvm_unreachable("Not a floating point type!");
1610 case BuiltinType::BFloat16:
1611 return Target->getBFloat16Format();
1612 case BuiltinType::Float16:
1613 return Target->getHalfFormat();
1614 case BuiltinType::Half:
1615 // For HLSL, when the native half type is disabled, half will be treat as
1616 // float.
1617 if (getLangOpts().HLSL)
1618 if (getLangOpts().NativeHalfType)
1619 return Target->getHalfFormat();
1620 else
1621 return Target->getFloatFormat();
1622 else
1623 return Target->getHalfFormat();
1624 case BuiltinType::Float: return Target->getFloatFormat();
1625 case BuiltinType::Double: return Target->getDoubleFormat();
1626 case BuiltinType::Ibm128:
1627 return Target->getIbm128Format();
1628 case BuiltinType::LongDouble:
1629 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1630 return AuxTarget->getLongDoubleFormat();
1631 return Target->getLongDoubleFormat();
1632 case BuiltinType::Float128:
1633 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1634 return AuxTarget->getFloat128Format();
1635 return Target->getFloat128Format();
1636 }
1637}
1638
1639CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1640 unsigned Align = Target->getCharWidth();
1641
1642 const unsigned AlignFromAttr = D->getMaxAlignment();
1643 if (AlignFromAttr)
1644 Align = AlignFromAttr;
1645
1646 // __attribute__((aligned)) can increase or decrease alignment
1647 // *except* on a struct or struct member, where it only increases
1648 // alignment unless 'packed' is also specified.
1649 //
1650 // It is an error for alignas to decrease alignment, so we can
1651 // ignore that possibility; Sema should diagnose it.
1652 bool UseAlignAttrOnly;
1653 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D))
1654 UseAlignAttrOnly =
1655 FD->hasAttr<PackedAttr>() || FD->getParent()->hasAttr<PackedAttr>();
1656 else
1657 UseAlignAttrOnly = AlignFromAttr != 0;
1658 // If we're using the align attribute only, just ignore everything
1659 // else about the declaration and its type.
1660 if (UseAlignAttrOnly) {
1661 // do nothing
1662 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1663 QualType T = VD->getType();
1664 if (const auto *RT = T->getAs<ReferenceType>()) {
1665 if (ForAlignof)
1666 T = RT->getPointeeType();
1667 else
1668 T = getPointerType(RT->getPointeeType());
1669 }
1670 QualType BaseT = getBaseElementType(T);
1671 if (T->isFunctionType())
1672 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1673 else if (!BaseT->isIncompleteType()) {
1674 // Adjust alignments of declarations with array type by the
1675 // large-array alignment on the target.
1676 if (const ArrayType *arrayType = getAsArrayType(T)) {
1677 unsigned MinWidth = Target->getLargeArrayMinWidth();
1678 if (!ForAlignof && MinWidth) {
1679 if (isa<VariableArrayType>(arrayType))
1680 Align = std::max(Align, Target->getLargeArrayAlign());
1681 else if (isa<ConstantArrayType>(arrayType) &&
1682 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1683 Align = std::max(Align, Target->getLargeArrayAlign());
1684 }
1685 }
1686 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1687 if (BaseT.getQualifiers().hasUnaligned())
1688 Align = Target->getCharWidth();
1689 }
1690
1691 // Ensure miminum alignment for global variables.
1692 if (const auto *VD = dyn_cast<VarDecl>(D))
1693 if (VD->hasGlobalStorage() && !ForAlignof) {
1694 uint64_t TypeSize =
1695 !BaseT->isIncompleteType() ? getTypeSize(T.getTypePtr()) : 0;
1696 Align = std::max(Align, getMinGlobalAlignOfVar(TypeSize, VD));
1697 }
1698
1699 // Fields can be subject to extra alignment constraints, like if
1700 // the field is packed, the struct is packed, or the struct has a
1701 // a max-field-alignment constraint (#pragma pack). So calculate
1702 // the actual alignment of the field within the struct, and then
1703 // (as we're expected to) constrain that by the alignment of the type.
1704 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1705 const RecordDecl *Parent = Field->getParent();
1706 // We can only produce a sensible answer if the record is valid.
1707 if (!Parent->isInvalidDecl()) {
1708 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1709
1710 // Start with the record's overall alignment.
1711 unsigned FieldAlign = toBits(Layout.getAlignment());
1712
1713 // Use the GCD of that and the offset within the record.
1714 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1715 if (Offset > 0) {
1716 // Alignment is always a power of 2, so the GCD will be a power of 2,
1717 // which means we get to do this crazy thing instead of Euclid's.
1718 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1719 if (LowBitOfOffset < FieldAlign)
1720 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1721 }
1722
1723 Align = std::min(Align, FieldAlign);
1724 }
1725 }
1726 }
1727
1728 // Some targets have hard limitation on the maximum requestable alignment in
1729 // aligned attribute for static variables.
1730 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1731 const auto *VD = dyn_cast<VarDecl>(D);
1732 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1733 Align = std::min(Align, MaxAlignedAttr);
1734
1735 return toCharUnitsFromBits(Align);
1736}
1737
1739 return toCharUnitsFromBits(Target->getExnObjectAlignment());
1740}
1741
1742// getTypeInfoDataSizeInChars - Return the size of a type, in
1743// chars. If the type is a record, its data size is returned. This is
1744// the size of the memcpy that's performed when assigning this type
1745// using a trivial copy/move assignment operator.
1748
1749 // In C++, objects can sometimes be allocated into the tail padding
1750 // of a base-class subobject. We decide whether that's possible
1751 // during class layout, so here we can just trust the layout results.
1752 if (getLangOpts().CPlusPlus) {
1753 if (const auto *RT = T->getAs<RecordType>();
1754 RT && !RT->getDecl()->isInvalidDecl()) {
1755 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1756 Info.Width = layout.getDataSize();
1757 }
1758 }
1759
1760 return Info;
1761}
1762
1763/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1764/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1767 const ConstantArrayType *CAT) {
1768 TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
1769 uint64_t Size = CAT->getSize().getZExtValue();
1770 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1771 (uint64_t)(-1)/Size) &&
1772 "Overflow in array type char size evaluation");
1773 uint64_t Width = EltInfo.Width.getQuantity() * Size;
1774 unsigned Align = EltInfo.Align.getQuantity();
1775 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1777 Width = llvm::alignTo(Width, Align);
1780 EltInfo.AlignRequirement);
1781}
1782
1784 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1785 return getConstantArrayInfoInChars(*this, CAT);
1786 TypeInfo Info = getTypeInfo(T);
1789}
1790
1792 return getTypeInfoInChars(T.getTypePtr());
1793}
1794
1796 // HLSL doesn't promote all small integer types to int, it
1797 // just uses the rank-based promotion rules for all types.
1798 if (getLangOpts().HLSL)
1799 return false;
1800
1801 if (const auto *BT = T->getAs<BuiltinType>())
1802 switch (BT->getKind()) {
1803 case BuiltinType::Bool:
1804 case BuiltinType::Char_S:
1805 case BuiltinType::Char_U:
1806 case BuiltinType::SChar:
1807 case BuiltinType::UChar:
1808 case BuiltinType::Short:
1809 case BuiltinType::UShort:
1810 case BuiltinType::WChar_S:
1811 case BuiltinType::WChar_U:
1812 case BuiltinType::Char8:
1813 case BuiltinType::Char16:
1814 case BuiltinType::Char32:
1815 return true;
1816 default:
1817 return false;
1818 }
1819
1820 // Enumerated types are promotable to their compatible integer types
1821 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
1822 if (const auto *ET = T->getAs<EnumType>()) {
1823 if (T->isDependentType() || ET->getDecl()->getPromotionType().isNull() ||
1824 ET->getDecl()->isScoped())
1825 return false;
1826
1827 return true;
1828 }
1829
1830 return false;
1831}
1832
1835}
1836
1838 return isAlignmentRequired(T.getTypePtr());
1839}
1840
1842 bool NeedsPreferredAlignment) const {
1843 // An alignment on a typedef overrides anything else.
1844 if (const auto *TT = T->getAs<TypedefType>())
1845 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1846 return Align;
1847
1848 // If we have an (array of) complete type, we're done.
1849 T = getBaseElementType(T);
1850 if (!T->isIncompleteType())
1851 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
1852
1853 // If we had an array type, its element type might be a typedef
1854 // type with an alignment attribute.
1855 if (const auto *TT = T->getAs<TypedefType>())
1856 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1857 return Align;
1858
1859 // Otherwise, see if the declaration of the type had an attribute.
1860 if (const auto *TT = T->getAs<TagType>())
1861 return TT->getDecl()->getMaxAlignment();
1862
1863 return 0;
1864}
1865
1867 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1868 if (I != MemoizedTypeInfo.end())
1869 return I->second;
1870
1871 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1872 TypeInfo TI = getTypeInfoImpl(T);
1873 MemoizedTypeInfo[T] = TI;
1874 return TI;
1875}
1876
1877/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1878/// method does not work on incomplete types.
1879///
1880/// FIXME: Pointers into different addr spaces could have different sizes and
1881/// alignment requirements: getPointerInfo should take an AddrSpace, this
1882/// should take a QualType, &c.
1883TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1884 uint64_t Width = 0;
1885 unsigned Align = 8;
1888 switch (T->getTypeClass()) {
1889#define TYPE(Class, Base)
1890#define ABSTRACT_TYPE(Class, Base)
1891#define NON_CANONICAL_TYPE(Class, Base)
1892#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1893#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1894 case Type::Class: \
1895 assert(!T->isDependentType() && "should not see dependent types here"); \
1896 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1897#include "clang/AST/TypeNodes.inc"
1898 llvm_unreachable("Should not see dependent types");
1899
1900 case Type::FunctionNoProto:
1901 case Type::FunctionProto:
1902 // GCC extension: alignof(function) = 32 bits
1903 Width = 0;
1904 Align = 32;
1905 break;
1906
1907 case Type::IncompleteArray:
1908 case Type::VariableArray:
1909 case Type::ConstantArray: {
1910 // Model non-constant sized arrays as size zero, but track the alignment.
1911 uint64_t Size = 0;
1912 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1913 Size = CAT->getSize().getZExtValue();
1914
1915 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
1916 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
1917 "Overflow in array type bit size evaluation");
1918 Width = EltInfo.Width * Size;
1919 Align = EltInfo.Align;
1920 AlignRequirement = EltInfo.AlignRequirement;
1921 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1922 getTargetInfo().getPointerWidth(LangAS::Default) == 64)
1923 Width = llvm::alignTo(Width, Align);
1924 break;
1925 }
1926
1927 case Type::ExtVector:
1928 case Type::Vector: {
1929 const auto *VT = cast<VectorType>(T);
1930 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1931 Width = VT->isExtVectorBoolType() ? VT->getNumElements()
1932 : EltInfo.Width * VT->getNumElements();
1933 // Enforce at least byte size and alignment.
1934 Width = std::max<unsigned>(8, Width);
1935 Align = std::max<unsigned>(8, Width);
1936
1937 // If the alignment is not a power of 2, round up to the next power of 2.
1938 // This happens for non-power-of-2 length vectors.
1939 if (Align & (Align-1)) {
1940 Align = llvm::bit_ceil(Align);
1941 Width = llvm::alignTo(Width, Align);
1942 }
1943 // Adjust the alignment based on the target max.
1944 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1945 if (TargetVectorAlign && TargetVectorAlign < Align)
1946 Align = TargetVectorAlign;
1947 if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
1948 // Adjust the alignment for fixed-length SVE vectors. This is important
1949 // for non-power-of-2 vector lengths.
1950 Align = 128;
1951 else if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
1952 // Adjust the alignment for fixed-length SVE predicates.
1953 Align = 16;
1954 else if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
1955 VT->getVectorKind() == VectorKind::RVVFixedLengthMask)
1956 // Adjust the alignment for fixed-length RVV vectors.
1957 Align = std::min<unsigned>(64, Width);
1958 break;
1959 }
1960
1961 case Type::ConstantMatrix: {
1962 const auto *MT = cast<ConstantMatrixType>(T);
1963 TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
1964 // The internal layout of a matrix value is implementation defined.
1965 // Initially be ABI compatible with arrays with respect to alignment and
1966 // size.
1967 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
1968 Align = ElementInfo.Align;
1969 break;
1970 }
1971
1972 case Type::Builtin:
1973 switch (cast<BuiltinType>(T)->getKind()) {
1974 default: llvm_unreachable("Unknown builtin type!");
1975 case BuiltinType::Void:
1976 // GCC extension: alignof(void) = 8 bits.
1977 Width = 0;
1978 Align = 8;
1979 break;
1980 case BuiltinType::Bool:
1981 Width = Target->getBoolWidth();
1982 Align = Target->getBoolAlign();
1983 break;
1984 case BuiltinType::Char_S:
1985 case BuiltinType::Char_U:
1986 case BuiltinType::UChar:
1987 case BuiltinType::SChar:
1988 case BuiltinType::Char8:
1989 Width = Target->getCharWidth();
1990 Align = Target->getCharAlign();
1991 break;
1992 case BuiltinType::WChar_S:
1993 case BuiltinType::WChar_U:
1994 Width = Target->getWCharWidth();
1995 Align = Target->getWCharAlign();
1996 break;
1997 case BuiltinType::Char16:
1998 Width = Target->getChar16Width();
1999 Align = Target->getChar16Align();
2000 break;
2001 case BuiltinType::Char32:
2002 Width = Target->getChar32Width();
2003 Align = Target->getChar32Align();
2004 break;
2005 case BuiltinType::UShort:
2006 case BuiltinType::Short:
2007 Width = Target->getShortWidth();
2008 Align = Target->getShortAlign();
2009 break;
2010 case BuiltinType::UInt:
2011 case BuiltinType::Int:
2012 Width = Target->getIntWidth();
2013 Align = Target->getIntAlign();
2014 break;
2015 case BuiltinType::ULong:
2016 case BuiltinType::Long:
2017 Width = Target->getLongWidth();
2018 Align = Target->getLongAlign();
2019 break;
2020 case BuiltinType::ULongLong:
2021 case BuiltinType::LongLong:
2022 Width = Target->getLongLongWidth();
2023 Align = Target->getLongLongAlign();
2024 break;
2025 case BuiltinType::Int128:
2026 case BuiltinType::UInt128:
2027 Width = 128;
2028 Align = Target->getInt128Align();
2029 break;
2030 case BuiltinType::ShortAccum:
2031 case BuiltinType::UShortAccum:
2032 case BuiltinType::SatShortAccum:
2033 case BuiltinType::SatUShortAccum:
2034 Width = Target->getShortAccumWidth();
2035 Align = Target->getShortAccumAlign();
2036 break;
2037 case BuiltinType::Accum:
2038 case BuiltinType::UAccum:
2039 case BuiltinType::SatAccum:
2040 case BuiltinType::SatUAccum:
2041 Width = Target->getAccumWidth();
2042 Align = Target->getAccumAlign();
2043 break;
2044 case BuiltinType::LongAccum:
2045 case BuiltinType::ULongAccum:
2046 case BuiltinType::SatLongAccum:
2047 case BuiltinType::SatULongAccum:
2048 Width = Target->getLongAccumWidth();
2049 Align = Target->getLongAccumAlign();
2050 break;
2051 case BuiltinType::ShortFract:
2052 case BuiltinType::UShortFract:
2053 case BuiltinType::SatShortFract:
2054 case BuiltinType::SatUShortFract:
2055 Width = Target->getShortFractWidth();
2056 Align = Target->getShortFractAlign();
2057 break;
2058 case BuiltinType::Fract:
2059 case BuiltinType::UFract:
2060 case BuiltinType::SatFract:
2061 case BuiltinType::SatUFract:
2062 Width = Target->getFractWidth();
2063 Align = Target->getFractAlign();
2064 break;
2065 case BuiltinType::LongFract:
2066 case BuiltinType::ULongFract:
2067 case BuiltinType::SatLongFract:
2068 case BuiltinType::SatULongFract:
2069 Width = Target->getLongFractWidth();
2070 Align = Target->getLongFractAlign();
2071 break;
2072 case BuiltinType::BFloat16:
2073 if (Target->hasBFloat16Type()) {
2074 Width = Target->getBFloat16Width();
2075 Align = Target->getBFloat16Align();
2076 } else if ((getLangOpts().SYCLIsDevice ||
2077 (getLangOpts().OpenMP &&
2078 getLangOpts().OpenMPIsTargetDevice)) &&
2079 AuxTarget->hasBFloat16Type()) {
2080 Width = AuxTarget->getBFloat16Width();
2081 Align = AuxTarget->getBFloat16Align();
2082 }
2083 break;
2084 case BuiltinType::Float16:
2085 case BuiltinType::Half:
2086 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2087 !getLangOpts().OpenMPIsTargetDevice) {
2088 Width = Target->getHalfWidth();
2089 Align = Target->getHalfAlign();
2090 } else {
2091 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2092 "Expected OpenMP device compilation.");
2093 Width = AuxTarget->getHalfWidth();
2094 Align = AuxTarget->getHalfAlign();
2095 }
2096 break;
2097 case BuiltinType::Float:
2098 Width = Target->getFloatWidth();
2099 Align = Target->getFloatAlign();
2100 break;
2101 case BuiltinType::Double:
2102 Width = Target->getDoubleWidth();
2103 Align = Target->getDoubleAlign();
2104 break;
2105 case BuiltinType::Ibm128:
2106 Width = Target->getIbm128Width();
2107 Align = Target->getIbm128Align();
2108 break;
2109 case BuiltinType::LongDouble:
2110 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2111 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2112 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2113 Width = AuxTarget->getLongDoubleWidth();
2114 Align = AuxTarget->getLongDoubleAlign();
2115 } else {
2116 Width = Target->getLongDoubleWidth();
2117 Align = Target->getLongDoubleAlign();
2118 }
2119 break;
2120 case BuiltinType::Float128:
2121 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2122 !getLangOpts().OpenMPIsTargetDevice) {
2123 Width = Target->getFloat128Width();
2124 Align = Target->getFloat128Align();
2125 } else {
2126 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2127 "Expected OpenMP device compilation.");
2128 Width = AuxTarget->getFloat128Width();
2129 Align = AuxTarget->getFloat128Align();
2130 }
2131 break;
2132 case BuiltinType::NullPtr:
2133 // C++ 3.9.1p11: sizeof(nullptr_t) == sizeof(void*)
2134 Width = Target->getPointerWidth(LangAS::Default);
2135 Align = Target->getPointerAlign(LangAS::Default);
2136 break;
2137 case BuiltinType::ObjCId:
2138 case BuiltinType::ObjCClass:
2139 case BuiltinType::ObjCSel:
2140 Width = Target->getPointerWidth(LangAS::Default);
2141 Align = Target->getPointerAlign(LangAS::Default);
2142 break;
2143 case BuiltinType::OCLSampler:
2144 case BuiltinType::OCLEvent:
2145 case BuiltinType::OCLClkEvent:
2146 case BuiltinType::OCLQueue:
2147 case BuiltinType::OCLReserveID:
2148#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2149 case BuiltinType::Id:
2150#include "clang/Basic/OpenCLImageTypes.def"
2151#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2152 case BuiltinType::Id:
2153#include "clang/Basic/OpenCLExtensionTypes.def"
2154 AS = Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
2155 Width = Target->getPointerWidth(AS);
2156 Align = Target->getPointerAlign(AS);
2157 break;
2158 // The SVE types are effectively target-specific. The length of an
2159 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2160 // of 128 bits. There is one predicate bit for each vector byte, so the
2161 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2162 //
2163 // Because the length is only known at runtime, we use a dummy value
2164 // of 0 for the static length. The alignment values are those defined
2165 // by the Procedure Call Standard for the Arm Architecture.
2166#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \
2167 IsSigned, IsFP, IsBF) \
2168 case BuiltinType::Id: \
2169 Width = 0; \
2170 Align = 128; \
2171 break;
2172#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \
2173 case BuiltinType::Id: \
2174 Width = 0; \
2175 Align = 16; \
2176 break;
2177#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId) \
2178 case BuiltinType::Id: \
2179 Width = 0; \
2180 Align = 16; \
2181 break;
2182#include "clang/Basic/AArch64SVEACLETypes.def"
2183#define PPC_VECTOR_TYPE(Name, Id, Size) \
2184 case BuiltinType::Id: \
2185 Width = Size; \
2186 Align = Size; \
2187 break;
2188#include "clang/Basic/PPCTypes.def"
2189#define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \
2190 IsFP, IsBF) \
2191 case BuiltinType::Id: \
2192 Width = 0; \
2193 Align = ElBits; \
2194 break;
2195#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2196 case BuiltinType::Id: \
2197 Width = 0; \
2198 Align = 8; \
2199 break;
2200#include "clang/Basic/RISCVVTypes.def"
2201#define WASM_TYPE(Name, Id, SingletonId) \
2202 case BuiltinType::Id: \
2203 Width = 0; \
2204 Align = 8; \
2205 break;
2206#include "clang/Basic/WebAssemblyReferenceTypes.def"
2207 }
2208 break;
2209 case Type::ObjCObjectPointer:
2210 Width = Target->getPointerWidth(LangAS::Default);
2211 Align = Target->getPointerAlign(LangAS::Default);
2212 break;
2213 case Type::BlockPointer:
2214 AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
2215 Width = Target->getPointerWidth(AS);
2216 Align = Target->getPointerAlign(AS);
2217 break;
2218 case Type::LValueReference:
2219 case Type::RValueReference:
2220 // alignof and sizeof should never enter this code path here, so we go
2221 // the pointer route.
2222 AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
2223 Width = Target->getPointerWidth(AS);
2224 Align = Target->getPointerAlign(AS);
2225 break;
2226 case Type::Pointer:
2227 AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
2228 Width = Target->getPointerWidth(AS);
2229 Align = Target->getPointerAlign(AS);
2230 break;
2231 case Type::MemberPointer: {
2232 const auto *MPT = cast<MemberPointerType>(T);
2233 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2234 Width = MPI.Width;
2235 Align = MPI.Align;
2236 break;
2237 }
2238 case Type::Complex: {
2239 // Complex types have the same alignment as their elements, but twice the
2240 // size.
2241 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2242 Width = EltInfo.Width * 2;
2243 Align = EltInfo.Align;
2244 break;
2245 }
2246 case Type::ObjCObject:
2247 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2248 case Type::Adjusted:
2249 case Type::Decayed:
2250 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2251 case Type::ObjCInterface: {
2252 const auto *ObjCI = cast<ObjCInterfaceType>(T);
2253 if (ObjCI->getDecl()->isInvalidDecl()) {
2254 Width = 8;
2255 Align = 8;
2256 break;
2257 }
2258 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2259 Width = toBits(Layout.getSize());
2260 Align = toBits(Layout.getAlignment());
2261 break;
2262 }
2263 case Type::BitInt: {
2264 const auto *EIT = cast<BitIntType>(T);
2265 Align = std::clamp<unsigned>(llvm::PowerOf2Ceil(EIT->getNumBits()),
2266 getCharWidth(), Target->getLongLongAlign());
2267 Width = llvm::alignTo(EIT->getNumBits(), Align);
2268 break;
2269 }
2270 case Type::Record:
2271 case Type::Enum: {
2272 const auto *TT = cast<TagType>(T);
2273
2274 if (TT->getDecl()->isInvalidDecl()) {
2275 Width = 8;
2276 Align = 8;
2277 break;
2278 }
2279
2280 if (const auto *ET = dyn_cast<EnumType>(TT)) {
2281 const EnumDecl *ED = ET->getDecl();
2282 TypeInfo Info =
2284 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2285 Info.Align = AttrAlign;
2287 }
2288 return Info;
2289 }
2290
2291 const auto *RT = cast<RecordType>(TT);
2292 const RecordDecl *RD = RT->getDecl();
2293 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2294 Width = toBits(Layout.getSize());
2295 Align = toBits(Layout.getAlignment());
2296 AlignRequirement = RD->hasAttr<AlignedAttr>()
2299 break;
2300 }
2301
2302 case Type::SubstTemplateTypeParm:
2303 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
2304 getReplacementType().getTypePtr());
2305
2306 case Type::Auto:
2307 case Type::DeducedTemplateSpecialization: {
2308 const auto *A = cast<DeducedType>(T);
2309 assert(!A->getDeducedType().isNull() &&
2310 "cannot request the size of an undeduced or dependent auto type");
2311 return getTypeInfo(A->getDeducedType().getTypePtr());
2312 }
2313
2314 case Type::Paren:
2315 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2316
2317 case Type::MacroQualified:
2318 return getTypeInfo(
2319 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2320
2321 case Type::ObjCTypeParam:
2322 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2323
2324 case Type::Using:
2325 return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr());
2326
2327 case Type::Typedef: {
2328 const auto *TT = cast<TypedefType>(T);
2329 TypeInfo Info = getTypeInfo(TT->desugar().getTypePtr());
2330 // If the typedef has an aligned attribute on it, it overrides any computed
2331 // alignment we have. This violates the GCC documentation (which says that
2332 // attribute(aligned) can only round up) but matches its implementation.
2333 if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) {
2334 Align = AttrAlign;
2335 AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2336 } else {
2337 Align = Info.Align;
2338 AlignRequirement = Info.AlignRequirement;
2339 }
2340 Width = Info.Width;
2341 break;
2342 }
2343
2344 case Type::Elaborated:
2345 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
2346
2347 case Type::Attributed:
2348 return getTypeInfo(
2349 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2350
2351 case Type::BTFTagAttributed:
2352 return getTypeInfo(
2353 cast<BTFTagAttributedType>(T)->getWrappedType().getTypePtr());
2354
2355 case Type::Atomic: {
2356 // Start with the base type information.
2357 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2358 Width = Info.Width;
2359 Align = Info.Align;
2360
2361 if (!Width) {
2362 // An otherwise zero-sized type should still generate an
2363 // atomic operation.
2364 Width = Target->getCharWidth();
2365 assert(Align);
2366 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2367 // If the size of the type doesn't exceed the platform's max
2368 // atomic promotion width, make the size and alignment more
2369 // favorable to atomic operations:
2370
2371 // Round the size up to a power of 2.
2372 Width = llvm::bit_ceil(Width);
2373
2374 // Set the alignment equal to the size.
2375 Align = static_cast<unsigned>(Width);
2376 }
2377 }
2378 break;
2379
2380 case Type::Pipe:
2381 Width = Target->getPointerWidth(LangAS::opencl_global);
2382 Align = Target->getPointerAlign(LangAS::opencl_global);
2383 break;
2384 }
2385
2386 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2387 return TypeInfo(Width, Align, AlignRequirement);
2388}
2389
2391 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2392 if (I != MemoizedUnadjustedAlign.end())
2393 return I->second;
2394
2395 unsigned UnadjustedAlign;
2396 if (const auto *RT = T->getAs<RecordType>()) {
2397 const RecordDecl *RD = RT->getDecl();
2398 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2399 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2400 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2401 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2402 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2403 } else {
2404 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2405 }
2406
2407 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2408 return UnadjustedAlign;
2409}
2410
2412 unsigned SimdAlign = llvm::OpenMPIRBuilder::getOpenMPDefaultSimdAlign(
2413 getTargetInfo().getTriple(), Target->getTargetOpts().FeatureMap);
2414 return SimdAlign;
2415}
2416
2417/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2419 return CharUnits::fromQuantity(BitSize / getCharWidth());
2420}
2421
2422/// toBits - Convert a size in characters to a size in characters.
2423int64_t ASTContext::toBits(CharUnits CharSize) const {
2424 return CharSize.getQuantity() * getCharWidth();
2425}
2426
2427/// getTypeSizeInChars - Return the size of the specified type, in characters.
2428/// This method does not work on incomplete types.
2430 return getTypeInfoInChars(T).Width;
2431}
2433 return getTypeInfoInChars(T).Width;
2434}
2435
2436/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2437/// characters. This method does not work on incomplete types.
2440}
2443}
2444
2445/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2446/// type, in characters, before alignment adjustments. This method does
2447/// not work on incomplete types.
2450}
2453}
2454
2455/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2456/// type for the current target in bits. This can be different than the ABI
2457/// alignment in cases where it is beneficial for performance or backwards
2458/// compatibility preserving to overalign a data type. (Note: despite the name,
2459/// the preferred alignment is ABI-impacting, and not an optimization.)
2460unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
2461 TypeInfo TI = getTypeInfo(T);
2462 unsigned ABIAlign = TI.Align;
2463
2464 T = T->getBaseElementTypeUnsafe();
2465
2466 // The preferred alignment of member pointers is that of a pointer.
2467 if (T->isMemberPointerType())
2468 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2469
2470 if (!Target->allowsLargerPreferedTypeAlignment())
2471 return ABIAlign;
2472
2473 if (const auto *RT = T->getAs<RecordType>()) {
2474 const RecordDecl *RD = RT->getDecl();
2475
2476 // When used as part of a typedef, or together with a 'packed' attribute,
2477 // the 'aligned' attribute can be used to decrease alignment. Note that the
2478 // 'packed' case is already taken into consideration when computing the
2479 // alignment, we only need to handle the typedef case here.
2481 RD->isInvalidDecl())
2482 return ABIAlign;
2483
2484 unsigned PreferredAlign = static_cast<unsigned>(
2485 toBits(getASTRecordLayout(RD).PreferredAlignment));
2486 assert(PreferredAlign >= ABIAlign &&
2487 "PreferredAlign should be at least as large as ABIAlign.");
2488 return PreferredAlign;
2489 }
2490
2491 // Double (and, for targets supporting AIX `power` alignment, long double) and
2492 // long long should be naturally aligned (despite requiring less alignment) if
2493 // possible.
2494 if (const auto *CT = T->getAs<ComplexType>())
2495 T = CT->getElementType().getTypePtr();
2496 if (const auto *ET = T->getAs<EnumType>())
2497 T = ET->getDecl()->getIntegerType().getTypePtr();
2498 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2499 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2500 T->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2501 (T->isSpecificBuiltinType(BuiltinType::LongDouble) &&
2502 Target->defaultsToAIXPowerAlignment()))
2503 // Don't increase the alignment if an alignment attribute was specified on a
2504 // typedef declaration.
2505 if (!TI.isAlignRequired())
2506 return std::max(ABIAlign, (unsigned)getTypeSize(T));
2507
2508 return ABIAlign;
2509}
2510
2511/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2512/// for __attribute__((aligned)) on this target, to be used if no alignment
2513/// value is specified.
2516}
2517
2518/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2519/// to a global variable of the specified type.
2521 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2522 return std::max(getPreferredTypeAlign(T),
2523 getMinGlobalAlignOfVar(TypeSize, VD));
2524}
2525
2526/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2527/// should be given to a global variable of the specified type.
2529 const VarDecl *VD) const {
2531}
2532
2534 const VarDecl *VD) const {
2535 // Make the default handling as that of a non-weak definition in the
2536 // current translation unit.
2537 bool HasNonWeakDef = !VD || (VD->hasDefinition() && !VD->isWeak());
2538 return getTargetInfo().getMinGlobalAlign(Size, HasNonWeakDef);
2539}
2540
2542 CharUnits Offset = CharUnits::Zero();
2543 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2544 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2545 Offset += Layout->getBaseClassOffset(Base);
2546 Layout = &getASTRecordLayout(Base);
2547 }
2548 return Offset;
2549}
2550
2552 const ValueDecl *MPD = MP.getMemberPointerDecl();
2555 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2556 const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext());
2557 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2558 const CXXRecordDecl *Base = RD;
2559 const CXXRecordDecl *Derived = Path[I];
2560 if (DerivedMember)
2561 std::swap(Base, Derived);
2563 RD = Path[I];
2564 }
2565 if (DerivedMember)
2567 return ThisAdjustment;
2568}
2569
2570/// DeepCollectObjCIvars -
2571/// This routine first collects all declared, but not synthesized, ivars in
2572/// super class and then collects all ivars, including those synthesized for
2573/// current class. This routine is used for implementation of current class
2574/// when all ivars, declared and synthesized are known.
2576 bool leafClass,
2578 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2579 DeepCollectObjCIvars(SuperClass, false, Ivars);
2580 if (!leafClass) {
2581 llvm::append_range(Ivars, OI->ivars());
2582 } else {
2583 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2584 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2585 Iv= Iv->getNextIvar())
2586 Ivars.push_back(Iv);
2587 }
2588}
2589
2590/// CollectInheritedProtocols - Collect all protocols in current class and
2591/// those inherited by it.
2594 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2595 // We can use protocol_iterator here instead of
2596 // all_referenced_protocol_iterator since we are walking all categories.
2597 for (auto *Proto : OI->all_referenced_protocols()) {
2598 CollectInheritedProtocols(Proto, Protocols);
2599 }
2600
2601 // Categories of this Interface.
2602 for (const auto *Cat : OI->visible_categories())
2603 CollectInheritedProtocols(Cat, Protocols);
2604
2605 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2606 while (SD) {
2607 CollectInheritedProtocols(SD, Protocols);
2608 SD = SD->getSuperClass();
2609 }
2610 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2611 for (auto *Proto : OC->protocols()) {
2612 CollectInheritedProtocols(Proto, Protocols);
2613 }
2614 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2615 // Insert the protocol.
2616 if (!Protocols.insert(
2617 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2618 return;
2619
2620 for (auto *Proto : OP->protocols())
2621 CollectInheritedProtocols(Proto, Protocols);
2622 }
2623}
2624
2626 const RecordDecl *RD,
2627 bool CheckIfTriviallyCopyable) {
2628 assert(RD->isUnion() && "Must be union type");
2629 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2630
2631 for (const auto *Field : RD->fields()) {
2632 if (!Context.hasUniqueObjectRepresentations(Field->getType(),
2633 CheckIfTriviallyCopyable))
2634 return false;
2635 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2636 if (FieldSize != UnionSize)
2637 return false;
2638 }
2639 return !RD->field_empty();
2640}
2641
2642static int64_t getSubobjectOffset(const FieldDecl *Field,
2643 const ASTContext &Context,
2644 const clang::ASTRecordLayout & /*Layout*/) {
2645 return Context.getFieldOffset(Field);
2646}
2647
2648static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
2649 const ASTContext &Context,
2650 const clang::ASTRecordLayout &Layout) {
2651 return Context.toBits(Layout.getBaseClassOffset(RD));
2652}
2653
2654static std::optional<int64_t>
2656 const RecordDecl *RD,
2657 bool CheckIfTriviallyCopyable);
2658
2659static std::optional<int64_t>
2660getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context,
2661 bool CheckIfTriviallyCopyable) {
2662 if (Field->getType()->isRecordType()) {
2663 const RecordDecl *RD = Field->getType()->getAsRecordDecl();
2664 if (!RD->isUnion())
2665 return structHasUniqueObjectRepresentations(Context, RD,
2666 CheckIfTriviallyCopyable);
2667 }
2668
2669 // A _BitInt type may not be unique if it has padding bits
2670 // but if it is a bitfield the padding bits are not used.
2671 bool IsBitIntType = Field->getType()->isBitIntType();
2672 if (!Field->getType()->isReferenceType() && !IsBitIntType &&
2673 !Context.hasUniqueObjectRepresentations(Field->getType(),
2674 CheckIfTriviallyCopyable))
2675 return std::nullopt;
2676
2677 int64_t FieldSizeInBits =
2678 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2679 if (Field->isBitField()) {
2680 // If we have explicit padding bits, they don't contribute bits
2681 // to the actual object representation, so return 0.
2682 if (Field->isUnnamedBitfield())
2683 return 0;
2684
2685 int64_t BitfieldSize = Field->getBitWidthValue(Context);
2686 if (IsBitIntType) {
2687 if ((unsigned)BitfieldSize >
2688 cast<BitIntType>(Field->getType())->getNumBits())
2689 return std::nullopt;
2690 } else if (BitfieldSize > FieldSizeInBits) {
2691 return std::nullopt;
2692 }
2693 FieldSizeInBits = BitfieldSize;
2694 } else if (IsBitIntType && !Context.hasUniqueObjectRepresentations(
2695 Field->getType(), CheckIfTriviallyCopyable)) {
2696 return std::nullopt;
2697 }
2698 return FieldSizeInBits;
2699}
2700
2701static std::optional<int64_t>
2703 bool CheckIfTriviallyCopyable) {
2704 return structHasUniqueObjectRepresentations(Context, RD,
2705 CheckIfTriviallyCopyable);
2706}
2707
2708template <typename RangeT>
2710 const RangeT &Subobjects, int64_t CurOffsetInBits,
2711 const ASTContext &Context, const clang::ASTRecordLayout &Layout,
2712 bool CheckIfTriviallyCopyable) {
2713 for (const auto *Subobject : Subobjects) {
2714 std::optional<int64_t> SizeInBits =
2715 getSubobjectSizeInBits(Subobject, Context, CheckIfTriviallyCopyable);
2716 if (!SizeInBits)
2717 return std::nullopt;
2718 if (*SizeInBits != 0) {
2719 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
2720 if (Offset != CurOffsetInBits)
2721 return std::nullopt;
2722 CurOffsetInBits += *SizeInBits;
2723 }
2724 }
2725 return CurOffsetInBits;
2726}
2727
2728static std::optional<int64_t>
2730 const RecordDecl *RD,
2731 bool CheckIfTriviallyCopyable) {
2732 assert(!RD->isUnion() && "Must be struct/class type");
2733 const auto &Layout = Context.getASTRecordLayout(RD);
2734
2735 int64_t CurOffsetInBits = 0;
2736 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2737 if (ClassDecl->isDynamicClass())
2738 return std::nullopt;
2739
2741 for (const auto &Base : ClassDecl->bases()) {
2742 // Empty types can be inherited from, and non-empty types can potentially
2743 // have tail padding, so just make sure there isn't an error.
2744 Bases.emplace_back(Base.getType()->getAsCXXRecordDecl());
2745 }
2746
2747 llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
2748 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
2749 });
2750
2751 std::optional<int64_t> OffsetAfterBases =
2753 Bases, CurOffsetInBits, Context, Layout, CheckIfTriviallyCopyable);
2754 if (!OffsetAfterBases)
2755 return std::nullopt;
2756 CurOffsetInBits = *OffsetAfterBases;
2757 }
2758
2759 std::optional<int64_t> OffsetAfterFields =
2761 RD->fields(), CurOffsetInBits, Context, Layout,
2762 CheckIfTriviallyCopyable);
2763 if (!OffsetAfterFields)
2764 return std::nullopt;
2765 CurOffsetInBits = *OffsetAfterFields;
2766
2767 return CurOffsetInBits;
2768}
2769
2771 QualType Ty, bool CheckIfTriviallyCopyable) const {
2772 // C++17 [meta.unary.prop]:
2773 // The predicate condition for a template specialization
2774 // has_unique_object_representations<T> shall be satisfied if and only if:
2775 // (9.1) - T is trivially copyable, and
2776 // (9.2) - any two objects of type T with the same value have the same
2777 // object representation, where:
2778 // - two objects of array or non-union class type are considered to have
2779 // the same value if their respective sequences of direct subobjects
2780 // have the same values, and
2781 // - two objects of union type are considered to have the same value if
2782 // they have the same active member and the corresponding members have
2783 // the same value.
2784 // The set of scalar types for which this condition holds is
2785 // implementation-defined. [ Note: If a type has padding bits, the condition
2786 // does not hold; otherwise, the condition holds true for unsigned integral
2787 // types. -- end note ]
2788 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2789
2790 // Arrays are unique only if their element type is unique.
2791 if (Ty->isArrayType())
2793 CheckIfTriviallyCopyable);
2794
2795 // (9.1) - T is trivially copyable...
2796 if (CheckIfTriviallyCopyable && !Ty.isTriviallyCopyableType(*this))
2797 return false;
2798
2799 // All integrals and enums are unique.
2800 if (Ty->isIntegralOrEnumerationType()) {
2801 // Except _BitInt types that have padding bits.
2802 if (const auto *BIT = Ty->getAs<BitIntType>())
2803 return getTypeSize(BIT) == BIT->getNumBits();
2804
2805 return true;
2806 }
2807
2808 // All other pointers are unique.
2809 if (Ty->isPointerType())
2810 return true;
2811
2812 if (const auto *MPT = Ty->getAs<MemberPointerType>())
2813 return !ABI->getMemberPointerInfo(MPT).HasPadding;
2814
2815 if (Ty->isRecordType()) {
2816 const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl();
2817
2818 if (Record->isInvalidDecl())
2819 return false;
2820
2821 if (Record->isUnion())
2823 CheckIfTriviallyCopyable);
2824
2825 std::optional<int64_t> StructSize = structHasUniqueObjectRepresentations(
2826 *this, Record, CheckIfTriviallyCopyable);
2827
2828 return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(Ty));
2829 }
2830
2831 // FIXME: More cases to handle here (list by rsmith):
2832 // vectors (careful about, eg, vector of 3 foo)
2833 // _Complex int and friends
2834 // _Atomic T
2835 // Obj-C block pointers
2836 // Obj-C object pointers
2837 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2838 // clk_event_t, queue_t, reserve_id_t)
2839 // There're also Obj-C class types and the Obj-C selector type, but I think it
2840 // makes sense for those to return false here.
2841
2842 return false;
2843}
2844
2846 unsigned count = 0;
2847 // Count ivars declared in class extension.
2848 for (const auto *Ext : OI->known_extensions())
2849 count += Ext->ivar_size();
2850
2851 // Count ivar defined in this class's implementation. This
2852 // includes synthesized ivars.
2853 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
2854 count += ImplDecl->ivar_size();
2855
2856 return count;
2857}
2858
2860 if (!E)
2861 return false;
2862
2863 // nullptr_t is always treated as null.
2864 if (E->getType()->isNullPtrType()) return true;
2865
2866 if (E->getType()->isAnyPointerType() &&
2869 return true;
2870
2871 // Unfortunately, __null has type 'int'.
2872 if (isa<GNUNullExpr>(E)) return true;
2873
2874 return false;
2875}
2876
2877/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
2878/// exists.
2880 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2881 I = ObjCImpls.find(D);
2882 if (I != ObjCImpls.end())
2883 return cast<ObjCImplementationDecl>(I->second);
2884 return nullptr;
2885}
2886
2887/// Get the implementation of ObjCCategoryDecl, or nullptr if none
2888/// exists.
2890 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2891 I = ObjCImpls.find(D);
2892 if (I != ObjCImpls.end())
2893 return cast<ObjCCategoryImplDecl>(I->second);
2894 return nullptr;
2895}
2896
2897/// Set the implementation of ObjCInterfaceDecl.
2899 ObjCImplementationDecl *ImplD) {
2900 assert(IFaceD && ImplD && "Passed null params");
2901 ObjCImpls[IFaceD] = ImplD;
2902}
2903
2904/// Set the implementation of ObjCCategoryDecl.
2906 ObjCCategoryImplDecl *ImplD) {
2907 assert(CatD && ImplD && "Passed null params");
2908 ObjCImpls[CatD] = ImplD;
2909}
2910
2911const ObjCMethodDecl *
2913 return ObjCMethodRedecls.lookup(MD);
2914}
2915
2917 const ObjCMethodDecl *Redecl) {
2918 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2919 ObjCMethodRedecls[MD] = Redecl;
2920}
2921
2923 const NamedDecl *ND) const {
2924 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
2925 return ID;
2926 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
2927 return CD->getClassInterface();
2928 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
2929 return IMD->getClassInterface();
2930
2931 return nullptr;
2932}
2933
2934/// Get the copy initialization expression of VarDecl, or nullptr if
2935/// none exists.
2937 assert(VD && "Passed null params");
2938 assert(VD->hasAttr<BlocksAttr>() &&
2939 "getBlockVarCopyInits - not __block var");
2940 auto I = BlockVarCopyInits.find(VD);
2941 if (I != BlockVarCopyInits.end())
2942 return I->second;
2943 return {nullptr, false};
2944}
2945
2946/// Set the copy initialization expression of a block var decl.
2948 bool CanThrow) {
2949 assert(VD && CopyExpr && "Passed null params");
2950 assert(VD->hasAttr<BlocksAttr>() &&
2951 "setBlockVarCopyInits - not __block var");
2952 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
2953}
2954
2956 unsigned DataSize) const {
2957 if (!DataSize)
2958 DataSize = TypeLoc::getFullDataSizeForType(T);
2959 else
2960 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
2961 "incorrect data size provided to CreateTypeSourceInfo!");
2962
2963 auto *TInfo =
2964 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2965 new (TInfo) TypeSourceInfo(T, DataSize);
2966 return TInfo;
2967}
2968
2970 SourceLocation L) const {
2972 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
2973 return DI;
2974}
2975
2976const ASTRecordLayout &
2978 return getObjCLayout(D, nullptr);
2979}
2980
2981const ASTRecordLayout &
2983 const ObjCImplementationDecl *D) const {
2984 return getObjCLayout(D->getClassInterface(), D);
2985}
2986
2989 bool &AnyNonCanonArgs) {
2990 SmallVector<TemplateArgument, 16> CanonArgs(Args);
2991 for (auto &Arg : CanonArgs) {
2992 TemplateArgument OrigArg = Arg;
2993 Arg = C.getCanonicalTemplateArgument(Arg);
2994 AnyNonCanonArgs |= !Arg.structurallyEquals(OrigArg);
2995 }
2996 return CanonArgs;
2997}
2998
2999//===----------------------------------------------------------------------===//
3000// Type creation/memoization methods
3001//===----------------------------------------------------------------------===//
3002
3004ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
3005 unsigned fastQuals = quals.getFastQualifiers();
3006 quals.removeFastQualifiers();
3007
3008 // Check if we've already instantiated this type.
3009 llvm::FoldingSetNodeID ID;
3010 ExtQuals::Profile(ID, baseType, quals);
3011 void *insertPos = nullptr;
3012 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
3013 assert(eq->getQualifiers() == quals);
3014 return QualType(eq, fastQuals);
3015 }
3016
3017 // If the base type is not canonical, make the appropriate canonical type.
3018 QualType canon;
3019 if (!baseType->isCanonicalUnqualified()) {
3020 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
3021 canonSplit.Quals.addConsistentQualifiers(quals);
3022 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
3023
3024 // Re-find the insert position.
3025 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
3026 }
3027
3028 auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
3029 ExtQualNodes.InsertNode(eq, insertPos);
3030 return QualType(eq, fastQuals);
3031}
3032
3034 LangAS AddressSpace) const {
3035 QualType CanT = getCanonicalType(T);
3036 if (CanT.getAddressSpace() == AddressSpace)
3037 return T;
3038
3039 // If we are composing extended qualifiers together, merge together
3040 // into one ExtQuals node.
3041 QualifierCollector Quals;
3042 const Type *TypeNode = Quals.strip(T);
3043
3044 // If this type already has an address space specified, it cannot get
3045 // another one.
3046 assert(!Quals.hasAddressSpace() &&
3047 "Type cannot be in multiple addr spaces!");
3048 Quals.addAddressSpace(AddressSpace);
3049
3050 return getExtQualType(TypeNode, Quals);
3051}
3052
3054 // If the type is not qualified with an address space, just return it
3055 // immediately.
3056 if (!T.hasAddressSpace())
3057 return T;
3058
3059 // If we are composing extended qualifiers together, merge together
3060 // into one ExtQuals node.
3061 QualifierCollector Quals;
3062 const Type *TypeNode;
3063
3064 while (T.hasAddressSpace()) {
3065 TypeNode = Quals.strip(T);
3066
3067 // If the type no longer has an address space after stripping qualifiers,
3068 // jump out.
3069 if (!QualType(TypeNode, 0).hasAddressSpace())
3070 break;
3071
3072 // There might be sugar in the way. Strip it and try again.
3073 T = T.getSingleStepDesugaredType(*this);
3074 }
3075
3076 Quals.removeAddressSpace();
3077
3078 // Removal of the address space can mean there are no longer any
3079 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3080 // or required.
3081 if (Quals.hasNonFastQualifiers())
3082 return getExtQualType(TypeNode, Quals);
3083 else
3084 return QualType(TypeNode, Quals.getFastQualifiers());
3085}
3086
3088 Qualifiers::GC GCAttr) const {
3089 QualType CanT = getCanonicalType(T);
3090 if (CanT.getObjCGCAttr() == GCAttr)
3091 return T;
3092
3093 if (const auto *ptr = T->getAs<PointerType>()) {
3094 QualType Pointee = ptr->getPointeeType();
3095 if (Pointee->isAnyPointerType()) {
3096 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
3097 return getPointerType(ResultType);
3098 }
3099 }
3100
3101 // If we are composing extended qualifiers together, merge together
3102 // into one ExtQuals node.
3103 QualifierCollector Quals;
3104 const Type *TypeNode = Quals.strip(T);
3105
3106 // If this type already has an ObjCGC specified, it cannot get
3107 // another one.
3108 assert(!Quals.hasObjCGCAttr() &&
3109 "Type cannot have multiple ObjCGCs!");
3110 Quals.addObjCGCAttr(GCAttr);
3111
3112 return getExtQualType(TypeNode, Quals);
3113}
3114
3116 if (const PointerType *Ptr = T->getAs<PointerType>()) {
3117 QualType Pointee = Ptr->getPointeeType();
3118 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
3119 return getPointerType(removeAddrSpaceQualType(Pointee));
3120 }
3121 }
3122 return T;
3123}
3124
3126 FunctionType::ExtInfo Info) {
3127 if (T->getExtInfo() == Info)
3128 return T;
3129
3131 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
3132 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
3133 } else {
3134 const auto *FPT = cast<FunctionProtoType>(T);
3135 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3136 EPI.ExtInfo = Info;
3137 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
3138 }
3139
3140 return cast<FunctionType>(Result.getTypePtr());
3141}
3142
3144 QualType ResultType) {
3145 FD = FD->getMostRecentDecl();
3146 while (true) {
3147 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
3148 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3149 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
3150 if (FunctionDecl *Next = FD->getPreviousDecl())
3151 FD = Next;
3152 else
3153 break;
3154 }
3156 L->DeducedReturnType(FD, ResultType);
3157}
3158
3159/// Get a function type and produce the equivalent function type with the
3160/// specified exception specification. Type sugar that can be present on a
3161/// declaration of a function with an exception specification is permitted
3162/// and preserved. Other type sugar (for instance, typedefs) is not.
3164 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
3165 // Might have some parens.
3166 if (const auto *PT = dyn_cast<ParenType>(Orig))
3167 return getParenType(
3168 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
3169
3170 // Might be wrapped in a macro qualified type.
3171 if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig))
3172 return getMacroQualifiedType(
3173 getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI),
3174 MQT->getMacroIdentifier());
3175
3176 // Might have a calling-convention attribute.
3177 if (const auto *AT = dyn_cast<AttributedType>(Orig))
3178 return getAttributedType(
3179 AT->getAttrKind(),
3180 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
3181 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
3182
3183 // Anything else must be a function type. Rebuild it with the new exception
3184 // specification.
3185 const auto *Proto = Orig->castAs<FunctionProtoType>();
3186 return getFunctionType(
3187 Proto->getReturnType(), Proto->getParamTypes(),
3188 Proto->getExtProtoInfo().withExceptionSpec(ESI));
3189}
3190
3192 QualType U) const {
3193 return hasSameType(T, U) ||
3194 (getLangOpts().CPlusPlus17 &&
3197}
3198
3200 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3201 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3202 SmallVector<QualType, 16> Args(Proto->param_types().size());
3203 for (unsigned i = 0, n = Args.size(); i != n; ++i)
3204 Args[i] = removePtrSizeAddrSpace(Proto->param_types()[i]);
3205 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3206 }
3207
3208 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3209 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3210 return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3211 }
3212
3213 return T;
3214}
3215
3217 return hasSameType(T, U) ||
3220}
3221
3224 bool AsWritten) {
3225 // Update the type.
3226 QualType Updated =
3228 FD->setType(Updated);
3229
3230 if (!AsWritten)
3231 return;
3232
3233 // Update the type in the type source information too.
3234 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3235 // If the type and the type-as-written differ, we may need to update
3236 // the type-as-written too.
3237 if (TSInfo->getType() != FD->getType())
3238 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
3239
3240 // FIXME: When we get proper type location information for exceptions,
3241 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3242 // up the TypeSourceInfo;
3243 assert(TypeLoc::getFullDataSizeForType(Updated) ==
3244 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3245 "TypeLoc size mismatch from updating exception specification");
3246 TSInfo->overrideType(Updated);
3247 }
3248}
3249
3250/// getComplexType - Return the uniqued reference to the type for a complex
3251/// number with the specified element type.
3253 // Unique pointers, to guarantee there is only one pointer of a particular
3254 // structure.
3255 llvm::FoldingSetNodeID ID;
3256 ComplexType::Profile(ID, T);
3257
3258 void *InsertPos = nullptr;
3259 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3260 return QualType(CT, 0);
3261
3262 // If the pointee type isn't canonical, this won't be a canonical type either,
3263 // so fill in the canonical type field.
3264 QualType Canonical;
3265 if (!T.isCanonical()) {
3266 Canonical = getComplexType(getCanonicalType(T));
3267
3268 // Get the new insert position for the node we care about.
3269 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3270 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3271 }
3272 auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
3273 Types.push_back(New);
3274 ComplexTypes.InsertNode(New, InsertPos);
3275 return QualType(New, 0);
3276}
3277
3278/// getPointerType - Return the uniqued reference to the type for a pointer to
3279/// the specified type.
3281 // Unique pointers, to guarantee there is only one pointer of a particular
3282 // structure.
3283 llvm::FoldingSetNodeID ID;
3284 PointerType::Profile(ID, T);
3285
3286 void *InsertPos = nullptr;
3287 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3288 return QualType(PT, 0);
3289
3290 // If the pointee type isn't canonical, this won't be a canonical type either,
3291 // so fill in the canonical type field.
3292 QualType Canonical;
3293 if (!T.isCanonical()) {
3294 Canonical = getPointerType(getCanonicalType(T));
3295
3296 // Get the new insert position for the node we care about.
3297 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3298 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3299 }
3300 auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
3301 Types.push_back(New);
3302 PointerTypes.InsertNode(New, InsertPos);
3303 return QualType(New, 0);
3304}
3305
3307 llvm::FoldingSetNodeID ID;
3308 AdjustedType::Profile(ID, Orig, New);
3309 void *InsertPos = nullptr;
3310 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3311 if (AT)
3312 return QualType(AT, 0);
3313
3314 QualType Canonical = getCanonicalType(New);
3315
3316 // Get the new insert position for the node we care about.
3317 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3318 assert(!AT && "Shouldn't be in the map!");
3319
3320 AT = new (*this, alignof(AdjustedType))
3321 AdjustedType(Type::Adjusted, Orig, New, Canonical);
3322 Types.push_back(AT);
3323 AdjustedTypes.InsertNode(AT, InsertPos);
3324 return QualType(AT, 0);
3325}
3326
3328 llvm::FoldingSetNodeID ID;
3329 AdjustedType::Profile(ID, Orig, Decayed);
3330 void *InsertPos = nullptr;
3331 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3332 if (AT)
3333 return QualType(AT, 0);
3334
3335 QualType Canonical = getCanonicalType(Decayed);
3336
3337 // Get the new insert position for the node we care about.
3338 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3339 assert(!AT && "Shouldn't be in the map!");
3340
3341 AT = new (*this, alignof(DecayedType)) DecayedType(Orig, Decayed, Canonical);
3342 Types.push_back(AT);
3343 AdjustedTypes.InsertNode(AT, InsertPos);
3344 return QualType(AT, 0);
3345}
3346
3348 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
3349
3350 QualType Decayed;
3351
3352 // C99 6.7.5.3p7:
3353 // A declaration of a parameter as "array of type" shall be
3354 // adjusted to "qualified pointer to type", where the type
3355 // qualifiers (if any) are those specified within the [ and ] of
3356 // the array type derivation.
3357 if (T->isArrayType())
3358 Decayed = getArrayDecayedType(T);
3359
3360 // C99 6.7.5.3p8:
3361 // A declaration of a parameter as "function returning type"
3362 // shall be adjusted to "pointer to function returning type", as
3363 // in 6.3.2.1.
3364 if (T->isFunctionType())
3365 Decayed = getPointerType(T);
3366
3367 return getDecayedType(T, Decayed);
3368}
3369
3370/// getBlockPointerType - Return the uniqued reference to the type for
3371/// a pointer to the specified block.
3373 assert(T->isFunctionType() && "block of function types only");
3374 // Unique pointers, to guarantee there is only one block of a particular
3375 // structure.
3376 llvm::FoldingSetNodeID ID;
3378
3379 void *InsertPos = nullptr;
3380 if (BlockPointerType *PT =
3381 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3382 return QualType(PT, 0);
3383
3384 // If the block pointee type isn't canonical, this won't be a canonical
3385 // type either so fill in the canonical type field.
3386 QualType Canonical;
3387 if (!T.isCanonical()) {
3388 Canonical = getBlockPointerType(getCanonicalType(T));
3389
3390 // Get the new insert position for the node we care about.
3391 BlockPointerType *NewIP =
3392 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3393 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3394 }
3395 auto *New =
3396 new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
3397 Types.push_back(New);
3398 BlockPointerTypes.InsertNode(New, InsertPos);
3399 return QualType(New, 0);
3400}
3401
3402/// getLValueReferenceType - Return the uniqued reference to the type for an
3403/// lvalue reference to the specified type.
3405ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
3406 assert((!T->isPlaceholderType() ||
3407 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
3408 "Unresolved placeholder type");
3409
3410 // Unique pointers, to guarantee there is only one pointer of a particular
3411 // structure.
3412 llvm::FoldingSetNodeID ID;
3413 ReferenceType::Profile(ID, T, SpelledAsLValue);
3414
3415 void *InsertPos = nullptr;
3416 if (LValueReferenceType *RT =
3417 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3418 return QualType(RT, 0);
3419
3420 const auto *InnerRef = T->getAs<ReferenceType>();
3421
3422 // If the referencee type isn't canonical, this won't be a canonical type
3423 // either, so fill in the canonical type field.
3424 QualType Canonical;
3425 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
3426 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3427 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
3428
3429 // Get the new insert position for the node we care about.
3430 LValueReferenceType *NewIP =
3431 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3432 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3433 }
3434
3435 auto *New = new (*this, alignof(LValueReferenceType))
3436 LValueReferenceType(T, Canonical, SpelledAsLValue);
3437 Types.push_back(New);
3438 LValueReferenceTypes.InsertNode(New, InsertPos);
3439
3440 return QualType(New, 0);
3441}
3442
3443/// getRValueReferenceType - Return the uniqued reference to the type for an
3444/// rvalue reference to the specified type.
3446 assert((!T->isPlaceholderType() ||
3447 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
3448 "Unresolved placeholder type");
3449
3450 // Unique pointers, to guarantee there is only one pointer of a particular
3451 // structure.
3452 llvm::FoldingSetNodeID ID;
3453 ReferenceType::Profile(ID, T, false);
3454
3455 void *InsertPos = nullptr;
3456 if (RValueReferenceType *RT =
3457 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3458 return QualType(RT, 0);
3459
3460 const auto *InnerRef = T->getAs<ReferenceType>();
3461
3462 // If the referencee type isn't canonical, this won't be a canonical type
3463 // either, so fill in the canonical type field.
3464 QualType Canonical;
3465 if (InnerRef || !T.isCanonical()) {
3466 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3467 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
3468
3469 // Get the new insert position for the node we care about.
3470 RValueReferenceType *NewIP =
3471 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3472 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3473 }
3474
3475 auto *New = new (*this, alignof(RValueReferenceType))
3476 RValueReferenceType(T, Canonical);
3477 Types.push_back(New);
3478 RValueReferenceTypes.InsertNode(New, InsertPos);
3479 return QualType(New, 0);
3480}
3481
3482/// getMemberPointerType - Return the uniqued reference to the type for a
3483/// member pointer to the specified type, in the specified class.
3485 // Unique pointers, to guarantee there is only one pointer of a particular
3486 // structure.
3487 llvm::FoldingSetNodeID ID;
3488 MemberPointerType::Profile(ID, T, Cls);
3489
3490 void *InsertPos = nullptr;
3491 if (MemberPointerType *PT =
3492 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3493 return QualType(PT, 0);
3494
3495 // If the pointee or class type isn't canonical, this won't be a canonical
3496 // type either, so fill in the canonical type field.
3497 QualType Canonical;
3498 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
3500
3501 // Get the new insert position for the node we care about.
3502 MemberPointerType *NewIP =
3503 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3504 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3505 }
3506 auto *New = new (*this, alignof(MemberPointerType))
3507 MemberPointerType(T, Cls, Canonical);
3508 Types.push_back(New);
3509 MemberPointerTypes.InsertNode(New, InsertPos);
3510 return QualType(New, 0);
3511}
3512
3513/// getConstantArrayType - Return the unique reference to the type for an
3514/// array of the specified element type.
3516 const llvm::APInt &ArySizeIn,
3517 const Expr *SizeExpr,
3519 unsigned IndexTypeQuals) const {
3520 assert((EltTy->isDependentType() ||
3521 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
3522 "Constant array of VLAs is illegal!");
3523
3524 // We only need the size as part of the type if it's instantiation-dependent.
3525 if (SizeExpr && !SizeExpr->isInstantiationDependent())
3526 SizeExpr = nullptr;
3527
3528 // Convert the array size into a canonical width matching the pointer size for
3529 // the target.
3530 llvm::APInt ArySize(ArySizeIn);
3531 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
3532
3533 llvm::FoldingSetNodeID ID;
3534 ConstantArrayType::Profile(ID, *this, EltTy, ArySize, SizeExpr, ASM,
3535 IndexTypeQuals);
3536
3537 void *InsertPos = nullptr;
3538 if (ConstantArrayType *ATP =
3539 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
3540 return QualType(ATP, 0);
3541
3542 // If the element type isn't canonical or has qualifiers, or the array bound
3543 // is instantiation-dependent, this won't be a canonical type either, so fill
3544 // in the canonical type field.
3545 QualType Canon;
3546 // FIXME: Check below should look for qualifiers behind sugar.
3547 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
3548 SplitQualType canonSplit = getCanonicalType(EltTy).split();
3549 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
3550 ASM, IndexTypeQuals);
3551 Canon = getQualifiedType(Canon, canonSplit.Quals);
3552
3553 // Get the new insert position for the node we care about.
3554 ConstantArrayType *NewIP =
3555 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
3556 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3557 }
3558
3559 void *Mem = Allocate(
3560 ConstantArrayType::totalSizeToAlloc<const Expr *>(SizeExpr ? 1 : 0),
3561 alignof(ConstantArrayType));
3562 auto *New = new (Mem)
3563 ConstantArrayType(EltTy, Canon, ArySize, SizeExpr, ASM, IndexTypeQuals);
3564 ConstantArrayTypes.InsertNode(New, InsertPos);
3565 Types.push_back(New);
3566 return QualType(New, 0);
3567}
3568
3569/// getVariableArrayDecayedType - Turns the given type, which may be
3570/// variably-modified, into the corresponding type with all the known
3571/// sizes replaced with [*].
3573 // Vastly most common case.
3574 if (!type->isVariablyModifiedType()) return type;
3575
3576 QualType result;
3577
3578 SplitQualType split = type.getSplitDesugaredType();
3579 const Type *ty = split.Ty;
3580 switch (ty->getTypeClass()) {
3581#define TYPE(Class, Base)
3582#define ABSTRACT_TYPE(Class, Base)
3583#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3584#include "clang/AST/TypeNodes.inc"
3585 llvm_unreachable("didn't desugar past all non-canonical types?");
3586
3587 // These types should never be variably-modified.
3588 case Type::Builtin:
3589 case Type::Complex:
3590 case Type::Vector:
3591 case Type::DependentVector:
3592 case Type::ExtVector:
3593 case Type::DependentSizedExtVector:
3594 case Type::ConstantMatrix:
3595 case Type::DependentSizedMatrix:
3596 case Type::DependentAddressSpace:
3597 case Type::ObjCObject:
3598 case Type::ObjCInterface:
3599 case Type::ObjCObjectPointer:
3600 case Type::Record:
3601 case Type::Enum:
3602 case Type::UnresolvedUsing:
3603 case Type::TypeOfExpr:
3604 case Type::TypeOf:
3605 case Type::Decltype:
3606 case Type::UnaryTransform:
3607 case Type::DependentName:
3608 case Type::InjectedClassName:
3609 case Type::TemplateSpecialization:
3610 case Type::DependentTemplateSpecialization:
3611 case Type::TemplateTypeParm:
3612 case Type::SubstTemplateTypeParmPack:
3613 case Type::Auto:
3614 case Type::DeducedTemplateSpecialization:
3615 case Type::PackExpansion:
3616 case Type::PackIndexing:
3617 case Type::BitInt:
3618 case Type::DependentBitInt:
3619 llvm_unreachable("type should never be variably-modified");
3620
3621 // These types can be variably-modified but should never need to
3622 // further decay.
3623 case Type::FunctionNoProto:
3624 case Type::FunctionProto:
3625 case Type::BlockPointer:
3626 case Type::MemberPointer:
3627 case Type::Pipe:
3628 return type;
3629
3630 // These types can be variably-modified. All these modifications
3631 // preserve structure except as noted by comments.
3632 // TODO: if we ever care about optimizing VLAs, there are no-op
3633 // optimizations available here.
3634 case Type::Pointer:
3636 cast<PointerType>(ty)->getPointeeType()));
3637 break;
3638
3639 case Type::LValueReference: {
3640 const auto *lv = cast<LValueReferenceType>(ty);
3641 result = getLValueReferenceType(
3642 getVariableArrayDecayedType(lv->getPointeeType()),
3643 lv->isSpelledAsLValue());
3644 break;
3645 }
3646
3647 case Type::RValueReference: {
3648 const auto *lv = cast<RValueReferenceType>(ty);
3649 result = getRValueReferenceType(
3650 getVariableArrayDecayedType(lv->getPointeeType()));
3651 break;
3652 }
3653
3654 case Type::Atomic: {
3655 const auto *at = cast<AtomicType>(ty);
3656 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3657 break;
3658 }
3659
3660 case Type::ConstantArray: {
3661 const auto *cat = cast<ConstantArrayType>(ty);
3662 result = getConstantArrayType(
3663 getVariableArrayDecayedType(cat->getElementType()),
3664 cat->getSize(),
3665 cat->getSizeExpr(),
3666 cat->getSizeModifier(),
3667 cat->getIndexTypeCVRQualifiers());
3668 break;
3669 }
3670
3671 case Type::DependentSizedArray: {
3672 const auto *dat = cast<DependentSizedArrayType>(ty);
3674 getVariableArrayDecayedType(dat->getElementType()),
3675 dat->getSizeExpr(),
3676 dat->getSizeModifier(),
3677 dat->getIndexTypeCVRQualifiers(),
3678 dat->getBracketsRange());
3679 break;
3680 }
3681
3682 // Turn incomplete types into [*] types.
3683 case Type::IncompleteArray: {
3684 const auto *iat = cast<IncompleteArrayType>(ty);
3685 result =
3687 /*size*/ nullptr, ArraySizeModifier::Normal,
3688 iat->getIndexTypeCVRQualifiers(), SourceRange());
3689 break;
3690 }
3691
3692 // Turn VLA types into [*] types.
3693 case Type::VariableArray: {
3694 const auto *vat = cast<VariableArrayType>(ty);
3695 result = getVariableArrayType(
3696 getVariableArrayDecayedType(vat->getElementType()),
3697 /*size*/ nullptr, ArraySizeModifier::Star,
3698 vat->getIndexTypeCVRQualifiers(), vat->getBracketsRange());
3699 break;
3700 }
3701 }
3702
3703 // Apply the top-level qualifiers from the original.
3704 return getQualifiedType(result, split.Quals);
3705}
3706
3707/// getVariableArrayType - Returns a non-unique reference to the type for a
3708/// variable array of the specified element type.
3711 unsigned IndexTypeQuals,
3712 SourceRange Brackets) const {
3713 // Since we don't unique expressions, it isn't possible to unique VLA's
3714 // that have an expression provided for their size.
3715 QualType Canon;
3716
3717 // Be sure to pull qualifiers off the element type.
3718 // FIXME: Check below should look for qualifiers behind sugar.
3719 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3720 SplitQualType canonSplit = getCanonicalType(EltTy).split();
3721 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
3722 IndexTypeQuals, Brackets);
3723 Canon = getQualifiedType(Canon, canonSplit.Quals);
3724 }
3725
3726 auto *New = new (*this, alignof(VariableArrayType))
3727 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
3728
3729 VariableArrayTypes.push_back(New);
3730 Types.push_back(New);
3731 return QualType(New, 0);
3732}
3733
3734/// getDependentSizedArrayType - Returns a non-unique reference to
3735/// the type for a dependently-sized array of the specified element
3736/// type.
3738 Expr *numElements,
3740 unsigned elementTypeQuals,
3741 SourceRange brackets) const {
3742 assert((!numElements || numElements->isTypeDependent() ||
3743 numElements->isValueDependent()) &&
3744 "Size must be type- or value-dependent!");
3745
3746 // Dependently-sized array types that do not have a specified number
3747 // of elements will have their sizes deduced from a dependent
3748 // initializer. We do no canonicalization here at all, which is okay
3749 // because they can't be used in most locations.
3750 if (!numElements) {
3751 auto *newType = new (*this, alignof(DependentSizedArrayType))
3752 DependentSizedArrayType(elementType, QualType(), numElements, ASM,
3753 elementTypeQuals, brackets);
3754 Types.push_back(newType);
3755 return QualType(newType, 0);
3756 }
3757
3758 // Otherwise, we actually build a new type every time, but we
3759 // also build a canonical type.
3760
3761 SplitQualType canonElementType = getCanonicalType(elementType).split();
3762
3763 void *insertPos = nullptr;
3764 llvm::FoldingSetNodeID ID;
3766 QualType(canonElementType.Ty, 0),
3767 ASM, elementTypeQuals, numElements);
3768
3769 // Look for an existing type with these properties.
3770 DependentSizedArrayType *canonTy =
3771 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3772
3773 // If we don't have one, build one.
3774 if (!canonTy) {
3775 canonTy = new (*this, alignof(DependentSizedArrayType))
3776 DependentSizedArrayType(QualType(canonElementType.Ty, 0), QualType(),
3777 numElements, ASM, elementTypeQuals, brackets);
3778 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3779 Types.push_back(canonTy);
3780 }
3781
3782 // Apply qualifiers from the element type to the array.
3783 QualType canon = getQualifiedType(QualType(canonTy,0),
3784 canonElementType.Quals);
3785
3786 // If we didn't need extra canonicalization for the element type or the size
3787 // expression, then just use that as our result.
3788 if (QualType(canonElementType.Ty, 0) == elementType &&
3789 canonTy->getSizeExpr() == numElements)
3790 return canon;
3791
3792 // Otherwise, we need to build a type which follows the spelling
3793 // of the element type.
3794 auto *sugaredType = new (*this, alignof(DependentSizedArrayType))
3795 DependentSizedArrayType(elementType, canon, numElements, ASM,
3796 elementTypeQuals, brackets);
3797 Types.push_back(sugaredType);
3798 return QualType(sugaredType, 0);
3799}
3800
3803 unsigned elementTypeQuals) const {
3804 llvm::FoldingSetNodeID ID;
3805 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
3806
3807 void *insertPos = nullptr;
3808 if (IncompleteArrayType *iat =
3809 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3810 return QualType(iat, 0);
3811
3812 // If the element type isn't canonical, this won't be a canonical type
3813 // either, so fill in the canonical type field. We also have to pull
3814 // qualifiers off the element type.
3815 QualType canon;
3816
3817 // FIXME: Check below should look for qualifiers behind sugar.
3818 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3819 SplitQualType canonSplit = getCanonicalType(elementType).split();
3820 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
3821 ASM, elementTypeQuals);
3822 canon = getQualifiedType(canon, canonSplit.Quals);
3823
3824 // Get the new insert position for the node we care about.
3825 IncompleteArrayType *existing =
3826 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3827 assert(!existing && "Shouldn't be in the map!"); (void) existing;
3828 }
3829
3830 auto *newType = new (*this, alignof(IncompleteArrayType))
3831 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
3832
3833 IncompleteArrayTypes.InsertNode(newType, insertPos);
3834 Types.push_back(newType);
3835 return QualType(newType, 0);
3836}
3837
3840#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
3841 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
3842 NUMVECTORS};
3843
3844#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
3845 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
3846
3847 switch (Ty->getKind()) {
3848 default:
3849 llvm_unreachable("Unsupported builtin vector type");
3850 case BuiltinType::SveInt8:
3851 return SVE_INT_ELTTY(8, 16, true, 1);
3852 case BuiltinType::SveUint8:
3853 return SVE_INT_ELTTY(8, 16, false, 1);
3854 case BuiltinType::SveInt8x2:
3855 return SVE_INT_ELTTY(8, 16, true, 2);
3856 case BuiltinType::SveUint8x2:
3857 return SVE_INT_ELTTY(8, 16, false, 2);
3858 case BuiltinType::SveInt8x3:
3859 return SVE_INT_ELTTY(8, 16, true, 3);
3860 case BuiltinType::SveUint8x3:
3861 return SVE_INT_ELTTY(8, 16, false, 3);
3862 case BuiltinType::SveInt8x4:
3863 return SVE_INT_ELTTY(8, 16, true, 4);
3864 case BuiltinType::SveUint8x4:
3865 return SVE_INT_ELTTY(8, 16, false, 4);
3866 case BuiltinType::SveInt16:
3867 return SVE_INT_ELTTY(16, 8, true, 1);
3868 case BuiltinType::SveUint16:
3869 return SVE_INT_ELTTY(16, 8, false, 1);
3870 case BuiltinType::SveInt16x2:
3871 return SVE_INT_ELTTY(16, 8, true, 2);
3872 case BuiltinType::SveUint16x2:
3873 return SVE_INT_ELTTY(16, 8, false, 2);
3874 case BuiltinType::SveInt16x3:
3875 return SVE_INT_ELTTY(16, 8, true, 3);
3876 case BuiltinType::SveUint16x3:
3877 return SVE_INT_ELTTY(16, 8, false, 3);
3878 case BuiltinType::SveInt16x4:
3879 return SVE_INT_ELTTY(16, 8, true, 4);
3880 case BuiltinType::SveUint16x4:
3881 return SVE_INT_ELTTY(16, 8, false, 4);
3882 case BuiltinType::SveInt32:
3883 return SVE_INT_ELTTY(32, 4, true, 1);
3884 case BuiltinType::SveUint32:
3885 return SVE_INT_ELTTY(32, 4, false, 1);
3886 case BuiltinType::SveInt32x2:
3887 return SVE_INT_ELTTY(32, 4, true, 2);
3888 case BuiltinType::SveUint32x2:
3889 return SVE_INT_ELTTY(32, 4, false, 2);
3890 case BuiltinType::SveInt32x3:
3891 return SVE_INT_ELTTY(32, 4, true, 3);
3892 case BuiltinType::SveUint32x3:
3893 return SVE_INT_ELTTY(32, 4, false, 3);
3894 case BuiltinType::SveInt32x4:
3895 return SVE_INT_ELTTY(32, 4, true, 4);
3896 case BuiltinType::SveUint32x4:
3897 return SVE_INT_ELTTY(32, 4, false, 4);
3898 case BuiltinType::SveInt64:
3899 return SVE_INT_ELTTY(64, 2, true, 1);
3900 case BuiltinType::SveUint64:
3901 return SVE_INT_ELTTY(64, 2, false, 1);
3902 case BuiltinType::SveInt64x2:
3903 return SVE_INT_ELTTY(64, 2, true, 2);
3904 case BuiltinType::SveUint64x2:
3905 return SVE_INT_ELTTY(64, 2, false, 2);
3906 case BuiltinType::SveInt64x3:
3907 return SVE_INT_ELTTY(64, 2, true, 3);
3908 case BuiltinType::SveUint64x3:
3909 return SVE_INT_ELTTY(64, 2, false, 3);
3910 case BuiltinType::SveInt64x4:
3911 return SVE_INT_ELTTY(64, 2, true, 4);
3912 case BuiltinType::SveUint64x4:
3913 return SVE_INT_ELTTY(64, 2, false, 4);
3914 case BuiltinType::SveBool:
3915 return SVE_ELTTY(BoolTy, 16, 1);
3916 case BuiltinType::SveBoolx2:
3917 return SVE_ELTTY(BoolTy, 16, 2);
3918 case BuiltinType::SveBoolx4:
3919 return SVE_ELTTY(BoolTy, 16, 4);
3920 case BuiltinType::SveFloat16:
3921 return SVE_ELTTY(HalfTy, 8, 1);
3922 case BuiltinType::SveFloat16x2:
3923 return SVE_ELTTY(HalfTy, 8, 2);
3924 case BuiltinType::SveFloat16x3:
3925 return SVE_ELTTY(HalfTy, 8, 3);
3926 case BuiltinType::SveFloat16x4:
3927 return SVE_ELTTY(HalfTy, 8, 4);
3928 case BuiltinType::SveFloat32:
3929 return SVE_ELTTY(FloatTy, 4, 1);
3930 case BuiltinType::SveFloat32x2:
3931 return SVE_ELTTY(FloatTy, 4, 2);
3932 case BuiltinType::SveFloat32x3:
3933 return SVE_ELTTY(FloatTy, 4, 3);
3934 case BuiltinType::SveFloat32x4:
3935 return SVE_ELTTY(FloatTy, 4, 4);
3936 case BuiltinType::SveFloat64:
3937 return SVE_ELTTY(DoubleTy, 2, 1);
3938 case BuiltinType::SveFloat64x2:
3939 return SVE_ELTTY(DoubleTy, 2, 2);
3940 case BuiltinType::SveFloat64x3:
3941 return SVE_ELTTY(DoubleTy, 2, 3);
3942 case BuiltinType::SveFloat64x4:
3943 return SVE_ELTTY(DoubleTy, 2, 4);
3944 case BuiltinType::SveBFloat16:
3945 return SVE_ELTTY(BFloat16Ty, 8, 1);
3946 case BuiltinType::SveBFloat16x2:
3947 return SVE_ELTTY(BFloat16Ty, 8, 2);
3948 case BuiltinType::SveBFloat16x3:
3949 return SVE_ELTTY(BFloat16Ty, 8, 3);
3950 case BuiltinType::SveBFloat16x4:
3951 return SVE_ELTTY(BFloat16Ty, 8, 4);
3952#define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
3953 IsSigned) \
3954 case BuiltinType::Id: \
3955 return {getIntTypeForBitwidth(ElBits, IsSigned), \
3956 llvm::ElementCount::getScalable(NumEls), NF};
3957#define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
3958 case BuiltinType::Id: \
3959 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
3960 llvm::ElementCount::getScalable(NumEls), NF};
3961#define RVV_VECTOR_TYPE_BFLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
3962 case BuiltinType::Id: \
3963 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
3964#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
3965 case BuiltinType::Id: \
3966 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
3967#include "clang/Basic/RISCVVTypes.def"
3968 }
3969}
3970
3971/// getExternrefType - Return a WebAssembly externref type, which represents an
3972/// opaque reference to a host value.
3974 if (Target->getTriple().isWasm() && Target->hasFeature("reference-types")) {
3975#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
3976 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
3977 return SingletonId;
3978#include "clang/Basic/WebAssemblyReferenceTypes.def"
3979 }
3980 llvm_unreachable(
3981 "shouldn't try to generate type externref outside WebAssembly target");
3982}
3983
3984/// getScalableVectorType - Return the unique reference to a scalable vector
3985/// type of the specified element type and size. VectorType must be a built-in
3986/// type.
3988 unsigned NumFields) const {
3989 if (Target->hasAArch64SVETypes()) {
3990 uint64_t EltTySize = getTypeSize(EltTy);
3991#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \
3992 IsSigned, IsFP, IsBF) \
3993 if (!EltTy->isBooleanType() && \
3994 ((EltTy->hasIntegerRepresentation() && \
3995 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
3996 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
3997 IsFP && !IsBF) || \
3998 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
3999 IsBF && !IsFP)) && \
4000 EltTySize == ElBits && NumElts == NumEls) { \
4001 return SingletonId; \
4002 }
4003#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \
4004 if (EltTy->isBooleanType() && NumElts == NumEls) \
4005 return SingletonId;
4006#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingleTonId)
4007#include "clang/Basic/AArch64SVEACLETypes.def"
4008 } else if (Target->hasRISCVVTypes()) {
4009 uint64_t EltTySize = getTypeSize(EltTy);
4010#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
4011 IsFP, IsBF) \
4012 if (!EltTy->isBooleanType() && \
4013 ((EltTy->hasIntegerRepresentation() && \
4014 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4015 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4016 IsFP && !IsBF) || \
4017 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4018 IsBF && !IsFP)) && \
4019 EltTySize == ElBits && NumElts == NumEls && NumFields == NF) \
4020 return SingletonId;
4021#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4022 if (EltTy->isBooleanType() && NumElts == NumEls) \
4023 return SingletonId;
4024#include "clang/Basic/RISCVVTypes.def"
4025 }
4026 return QualType();
4027}
4028
4029/// getVectorType - Return the unique reference to a vector type of
4030/// the specified element type and size. VectorType must be a built-in type.
4032 VectorKind VecKind) const {
4033 assert(vecType->isBuiltinType() ||
4034 (vecType->isBitIntType() &&
4035 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4036 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits()) &&
4037 vecType->castAs<BitIntType>()->getNumBits() >= 8));
4038
4039 // Check if we've already instantiated a vector of this type.
4040 llvm::FoldingSetNodeID ID;
4041 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
4042
4043 void *InsertPos = nullptr;
4044 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4045 return QualType(VTP, 0);
4046
4047 // If the element type isn't canonical, this won't be a canonical type either,
4048 // so fill in the canonical type field.
4049 QualType Canonical;
4050 if (!vecType.isCanonical()) {
4051 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
4052
4053 // Get the new insert position for the node we care about.
4054 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4055 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4056 }
4057 auto *New = new (*this, alignof(VectorType))
4058 VectorType(vecType, NumElts, Canonical, VecKind);
4059 VectorTypes.InsertNode(New, InsertPos);
4060 Types.push_back(New);
4061 return QualType(New, 0);
4062}
4063
4065 SourceLocation AttrLoc,
4066 VectorKind VecKind) const {
4067 llvm::FoldingSetNodeID ID;
4068 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
4069 VecKind);
4070 void *InsertPos = nullptr;
4071 DependentVectorType *Canon =
4072 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4074
4075 if (Canon) {
4076 New = new (*this, alignof(DependentVectorType)) DependentVectorType(
4077 VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4078 } else {
4079 QualType CanonVecTy = getCanonicalType(VecType);
4080 if (CanonVecTy == VecType) {
4081 New = new (*this, alignof(DependentVectorType))
4082 DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4083
4084 DependentVectorType *CanonCheck =
4085 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4086 assert(!CanonCheck &&
4087 "Dependent-sized vector_size canonical type broken");
4088 (void)CanonCheck;
4089 DependentVectorTypes.InsertNode(New, InsertPos);
4090 } else {
4091 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
4092 SourceLocation(), VecKind);
4093 New = new (*this, alignof(DependentVectorType))
4094 DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4095 }
4096 }
4097
4098 Types.push_back(New);
4099 return QualType(New, 0);
4100}
4101
4102/// getExtVectorType - Return the unique reference to an extended vector type of
4103/// the specified element type and size. VectorType must be a built-in type.
4105 unsigned NumElts) const {
4106 assert(vecType->isBuiltinType() || vecType->isDependentType() ||
4107 (vecType->isBitIntType() &&
4108 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4109 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits()) &&
4110 vecType->castAs<BitIntType>()->getNumBits() >= 8));
4111
4112 // Check if we've already instantiated a vector of this type.
4113 llvm::FoldingSetNodeID ID;
4114 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
4116 void *InsertPos = nullptr;
4117 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4118 return QualType(VTP, 0);
4119
4120 // If the element type isn't canonical, this won't be a canonical type either,
4121 // so fill in the canonical type field.
4122 QualType Canonical;
4123 if (!vecType.isCanonical()) {
4124 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
4125
4126 // Get the new insert position for the node we care about.
4127 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4128 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4129 }
4130 auto *New = new (*this, alignof(ExtVectorType))
4131 ExtVectorType(vecType, NumElts, Canonical);
4132 VectorTypes.InsertNode(New, InsertPos);
4133 Types.push_back(New);
4134 return QualType(New, 0);
4135}
4136
4139 Expr *SizeExpr,
4140 SourceLocation AttrLoc) const {
4141 llvm::FoldingSetNodeID ID;
4143 SizeExpr);
4144
4145 void *InsertPos = nullptr;
4147 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4149 if (Canon) {
4150 // We already have a canonical version of this array type; use it as
4151 // the canonical type for a newly-built type.
4152 New = new (*this, alignof(DependentSizedExtVectorType))
4153 DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr,
4154 AttrLoc);
4155 } else {
4156 QualType CanonVecTy = getCanonicalType(vecType);
4157 if (CanonVecTy == vecType) {
4158 New = new (*this, alignof(DependentSizedExtVectorType))
4159 DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
4160
4161 DependentSizedExtVectorType *CanonCheck
4162 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4163 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4164 (void)CanonCheck;
4165 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
4166 } else {
4167 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4168 SourceLocation());
4169 New = new (*this, alignof(DependentSizedExtVectorType))
4170 DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc);
4171 }
4172 }
4173
4174 Types.push_back(New);
4175 return QualType(New, 0);
4176}
4177
4179 unsigned NumColumns) const {
4180 llvm::FoldingSetNodeID ID;
4181 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
4182 Type::ConstantMatrix);
4183
4184 assert(MatrixType::isValidElementType(ElementTy) &&
4185 "need a valid element type");
4186 assert(ConstantMatrixType::isDimensionValid(NumRows) &&
4188 "need valid matrix dimensions");
4189 void *InsertPos = nullptr;
4190 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
4191 return QualType(MTP, 0);
4192
4193 QualType Canonical;
4194 if (!ElementTy.isCanonical()) {
4195 Canonical =
4196 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
4197
4198 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4199 assert(!NewIP && "Matrix type shouldn't already exist in the map");
4200 (void)NewIP;
4201 }
4202
4203 auto *New = new (*this, alignof(ConstantMatrixType))
4204 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4205 MatrixTypes.InsertNode(New, InsertPos);
4206 Types.push_back(New);
4207 return QualType(New, 0);
4208}
4209
4211 Expr *RowExpr,
4212 Expr *ColumnExpr,
4213 SourceLocation AttrLoc) const {
4214 QualType CanonElementTy = getCanonicalType(ElementTy);
4215 llvm::FoldingSetNodeID ID;
4216 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4217 ColumnExpr);
4218
4219 void *InsertPos = nullptr;
4221 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4222
4223 if (!Canon) {
4224 Canon = new (*this, alignof(DependentSizedMatrixType))
4225 DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr,
4226 ColumnExpr, AttrLoc);
4227#ifndef NDEBUG
4228 DependentSizedMatrixType *CanonCheck =
4229 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4230 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4231#endif
4232 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
4233 Types.push_back(Canon);
4234 }
4235
4236 // Already have a canonical version of the matrix type
4237 //
4238 // If it exactly matches the requested type, use it directly.
4239 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4240 Canon->getRowExpr() == ColumnExpr)
4241 return QualType(Canon, 0);
4242
4243 // Use Canon as the canonical type for newly-built type.
4244 DependentSizedMatrixType *New = new (*this, alignof(DependentSizedMatrixType))
4245 DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr,
4246 ColumnExpr, AttrLoc);
4247 Types.push_back(New);
4248 return QualType(New, 0);
4249}
4250
4252 Expr *AddrSpaceExpr,
4253 SourceLocation AttrLoc) const {
4254 assert(AddrSpaceExpr->isInstantiationDependent());
4255
4256 QualType canonPointeeType = getCanonicalType(PointeeType);
4257
4258 void *insertPos = nullptr;
4259 llvm::FoldingSetNodeID ID;
4260 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4261 AddrSpaceExpr);
4262
4263 DependentAddressSpaceType *canonTy =
4264 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
4265
4266 if (!canonTy) {
4267 canonTy = new (*this, alignof(DependentAddressSpaceType))
4268 DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr,
4269 AttrLoc);
4270 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
4271 Types.push_back(canonTy);
4272 }
4273
4274 if (canonPointeeType == PointeeType &&
4275 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4276 return QualType(canonTy, 0);
4277
4278 auto *sugaredType = new (*this, alignof(DependentAddressSpaceType))
4279 DependentAddressSpaceType(PointeeType, QualType(canonTy, 0),
4280 AddrSpaceExpr, AttrLoc);
4281 Types.push_back(sugaredType);
4282 return QualType(sugaredType, 0);
4283}
4284
4285/// Determine whether \p T is canonical as the result type of a function.
4287 return T.isCanonical() &&
4290}
4291
4292/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4295 const FunctionType::ExtInfo &Info) const {
4296 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
4297 // functionality creates a function without a prototype regardless of
4298 // language mode (so it makes them even in C++). Once the rewriter has been
4299 // fixed, this assertion can be enabled again.
4300 //assert(!LangOpts.requiresStrictPrototypes() &&
4301 // "strict prototypes are disabled");
4302
4303 // Unique functions, to guarantee there is only one function of a particular
4304 // structure.
4305 llvm::FoldingSetNodeID ID;
4306 FunctionNoProtoType::Profile(ID, ResultTy, Info);
4307
4308 void *InsertPos = nullptr;
4309 if (FunctionNoProtoType *FT =
4310 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
4311 return QualType(FT, 0);
4312
4313 QualType Canonical;
4314 if (!isCanonicalResultType(ResultTy)) {
4315 Canonical =
4317
4318 // Get the new insert position for the node we care about.
4319 FunctionNoProtoType *NewIP =
4320 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4321 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4322 }
4323
4324 auto *New = new (*this, alignof(FunctionNoProtoType))
4325 FunctionNoProtoType(ResultTy, Canonical, Info);
4326 Types.push_back(New);
4327 FunctionNoProtoTypes.InsertNode(New, InsertPos);
4328 return QualType(New, 0);
4329}
4330
4333 CanQualType CanResultType = getCanonicalType(ResultType);
4334
4335 // Canonical result types do not have ARC lifetime qualifiers.
4336 if (CanResultType.getQualifiers().hasObjCLifetime()) {
4337 Qualifiers Qs = CanResultType.getQualifiers();
4338 Qs.removeObjCLifetime();
4340 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
4341 }
4342
4343 return CanResultType;
4344}
4345
4347 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
4348 if (ESI.Type == EST_None)
4349 return true;
4350 if (!NoexceptInType)
4351 return false;
4352
4353 // C++17 onwards: exception specification is part of the type, as a simple
4354 // boolean "can this function type throw".
4355 if (ESI.Type == EST_BasicNoexcept)
4356 return true;
4357
4358 // A noexcept(expr) specification is (possibly) canonical if expr is
4359 // value-dependent.
4360 if (ESI.Type == EST_DependentNoexcept)
4361 return true;
4362
4363 // A dynamic exception specification is canonical if it only contains pack
4364 // expansions (so we can't tell whether it's non-throwing) and all its
4365 // contained types are canonical.
4366 if (ESI.Type == EST_Dynamic) {
4367 bool AnyPackExpansions = false;
4368 for (QualType ET : ESI.Exceptions) {
4369 if (!ET.isCanonical())
4370 return false;
4371 if (ET->getAs<PackExpansionType>())
4372 AnyPackExpansions = true;
4373 }
4374 return AnyPackExpansions;
4375 }
4376
4377 return false;
4378}
4379
4380QualType ASTContext::getFunctionTypeInternal(
4381 QualType ResultTy, ArrayRef<QualType> ArgArray,
4382 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
4383 size_t NumArgs = ArgArray.size();
4384
4385 // Unique functions, to guarantee there is only one function of a particular
4386 // structure.
4387 llvm::FoldingSetNodeID ID;
4388 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
4389 *this, true);
4390
4391 QualType Canonical;
4392 bool Unique = false;
4393
4394 void *InsertPos = nullptr;
4395 if (FunctionProtoType *FPT =
4396 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
4397 QualType Existing = QualType(FPT, 0);
4398
4399 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
4400 // it so long as our exception specification doesn't contain a dependent
4401 // noexcept expression, or we're just looking for a canonical type.
4402 // Otherwise, we're going to need to create a type
4403 // sugar node to hold the concrete expression.
4404 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
4405 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
4406 return Existing;
4407
4408 // We need a new type sugar node for this one, to hold the new noexcept
4409 // expression. We do no canonicalization here, but that's OK since we don't
4410 // expect to see the same noexcept expression much more than once.
4411 Canonical = getCanonicalType(Existing);
4412 Unique = true;
4413 }
4414
4415 bool NoexceptInType = getLangOpts().CPlusPlus17;
4416 bool IsCanonicalExceptionSpec =
4418
4419 // Determine whether the type being created is already canonical or not.
4420 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
4421 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
4422 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
4423 if (!ArgArray[i].isCanonicalAsParam())
4424 isCanonical = false;
4425
4426 if (OnlyWantCanonical)
4427 assert(isCanonical &&
4428 "given non-canonical parameters constructing canonical type");
4429
4430 // If this type isn't canonical, get the canonical version of it if we don't
4431 // already have it. The exception spec is only partially part of the
4432 // canonical type, and only in C++17 onwards.
4433 if (!isCanonical && Canonical.isNull()) {
4434 SmallVector<QualType, 16> CanonicalArgs;
4435 CanonicalArgs.reserve(NumArgs);
4436 for (unsigned i = 0; i != NumArgs; ++i)
4437 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
4438
4439 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
4440 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
4441 CanonicalEPI.HasTrailingReturn = false;
4442
4443 if (IsCanonicalExceptionSpec) {
4444 // Exception spec is already OK.
4445 } else if (NoexceptInType) {
4446 switch (EPI.ExceptionSpec.Type) {
4448 // We don't know yet. It shouldn't matter what we pick here; no-one
4449 // should ever look at this.
4450 [[fallthrough]];
4451 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
4452 CanonicalEPI.ExceptionSpec.Type = EST_None;
4453 break;
4454
4455 // A dynamic exception specification is almost always "not noexcept",
4456 // with the exception that a pack expansion might expand to no types.
4457 case EST_Dynamic: {
4458 bool AnyPacks = false;
4459 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
4460 if (ET->getAs<PackExpansionType>())
4461 AnyPacks = true;
4462 ExceptionTypeStorage.push_back(getCanonicalType(ET));
4463 }
4464 if (!AnyPacks)
4465 CanonicalEPI.ExceptionSpec.Type = EST_None;
4466 else {
4467 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
4468 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
4469 }
4470 break;
4471 }
4472
4473 case EST_DynamicNone:
4474 case EST_BasicNoexcept:
4475 case EST_NoexceptTrue:
4476 case EST_NoThrow:
4477 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
4478 break;
4479
4481 llvm_unreachable("dependent noexcept is already canonical");
4482 }
4483 } else {
4485 }
4486
4487 // Adjust the canonical function result type.
4488 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
4489 Canonical =
4490 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
4491
4492 // Get the new insert position for the node we care about.
4493 FunctionProtoType *NewIP =
4494 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4495 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4496 }
4497
4498 // Compute the needed size to hold this FunctionProtoType and the
4499 // various trailing objects.
4500 auto ESH = FunctionProtoType::getExceptionSpecSize(
4501 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
4502 size_t Size = FunctionProtoType::totalSizeToAlloc<
4507 EPI.requiresFunctionProtoTypeArmAttributes(), ESH.NumExceptionType,
4508 ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
4509 EPI.ExtParameterInfos ? NumArgs : 0,
4510 EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0);
4511
4512 auto *FTP = (FunctionProtoType *)Allocate(Size, alignof(FunctionProtoType));
4514 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
4515 Types.push_back(FTP);
4516 if (!Unique)
4517 FunctionProtoTypes.InsertNode(FTP, InsertPos);
4518 return QualType(FTP, 0);
4519}
4520
4521QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
4522 llvm::FoldingSetNodeID ID;
4523 PipeType::Profile(ID, T, ReadOnly);
4524
4525 void *InsertPos = nullptr;
4526 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
4527 return QualType(PT, 0);
4528
4529 // If the pipe element type isn't canonical, this won't be a canonical type
4530 // either, so fill in the canonical type field.
4531 QualType Canonical;
4532 if (!T.isCanonical()) {
4533 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
4534
4535 // Get the new insert position for the node we care about.
4536 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
4537 assert(!NewIP && "Shouldn't be in the map!");
4538 (void)NewIP;
4539 }
4540 auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly);
4541 Types.push_back(New);
4542 PipeTypes.InsertNode(New, InsertPos);
4543 return QualType(New, 0);
4544}
4545
4547 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
4548 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
4549 : Ty;
4550}
4551
4553 return getPipeType(T, true);
4554}
4555
4557 return getPipeType(T, false);
4558}
4559
4560QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
4561 llvm::FoldingSetNodeID ID;
4562 BitIntType::Profile(ID, IsUnsigned, NumBits);
4563
4564 void *InsertPos = nullptr;
4565 if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
4566 return QualType(EIT, 0);
4567
4568 auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits);
4569 BitIntTypes.InsertNode(New, InsertPos);
4570 Types.push_back(New);
4571 return QualType(New, 0);
4572}
4573
4575 Expr *NumBitsExpr) const {
4576 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
4577 llvm::FoldingSetNodeID ID;
4578 DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
4579
4580 void *InsertPos = nullptr;
4581 if (DependentBitIntType *Existing =
4582 DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
4583 return QualType(Existing, 0);
4584
4585 auto *New = new (*this, alignof(DependentBitIntType))
4586 DependentBitIntType(IsUnsigned, NumBitsExpr);
4587 DependentBitIntTypes.InsertNode(New, InsertPos);
4588
4589 Types.push_back(New);
4590 return QualType(New, 0);
4591}
4592
4593#ifndef NDEBUG
4595 if (!isa<CXXRecordDecl>(D)) return false;
4596 const auto *RD = cast<CXXRecordDecl>(D);
4597 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
4598 return true;
4599 if (RD->getDescribedClassTemplate() &&
4600 !isa<ClassTemplateSpecializationDecl>(RD))
4601 return true;
4602 return false;
4603}
4604#endif
4605
4606/// getInjectedClassNameType - Return the unique reference to the
4607/// injected class name type for the specified templated declaration.
4609 QualType TST) const {
4611 if (Decl->TypeForDecl) {
4612 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
4613 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
4614 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
4615 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4616 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
4617 } else {
4618 Type *newType = new (*this, alignof(InjectedClassNameType))
4620 Decl->TypeForDecl = newType;
4621 Types.push_back(newType);
4622 }
4623 return QualType(Decl->TypeForDecl, 0);
4624}
4625
4626/// getTypeDeclType - Return the unique reference to the type for the
4627/// specified type declaration.
4628QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
4629 assert(Decl && "Passed null for Decl param");
4630 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
4631
4632 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
4633 return getTypedefType(Typedef);
4634
4635 assert(!isa<TemplateTypeParmDecl>(Decl) &&
4636 "Template type parameter types are always available.");
4637
4638 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
4639 assert(Record->isFirstDecl() && "struct/union has previous declaration");
4641 return getRecordType(Record);
4642 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
4643 assert(Enum->isFirstDecl() && "enum has previous declaration");
4644 return getEnumType(Enum);
4645 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
4646 return getUnresolvedUsingType(Using);
4647 } else
4648 llvm_unreachable("TypeDecl without a type?");
4649
4650 return QualType(Decl->TypeForDecl, 0);
4651}
4652
4653/// getTypedefType - Return the unique reference to the type for the
4654/// specified typedef name decl.
4656 QualType Underlying) const {
4657 if (!Decl->TypeForDecl) {
4658 if (Underlying.isNull())
4659 Underlying = Decl->getUnderlyingType();
4660 auto *NewType = new (*this, alignof(TypedefType)) TypedefType(
4661 Type::Typedef, Decl, QualType(), getCanonicalType(Underlying));
4662 Decl->TypeForDecl = NewType;
4663 Types.push_back(NewType);
4664 return QualType(NewType, 0);
4665 }
4666 if (Underlying.isNull() || Decl->getUnderlyingType() == Underlying)
4667 return QualType(Decl->TypeForDecl, 0);
4668 assert(hasSameType(Decl->getUnderlyingType(), Underlying));
4669
4670 llvm::FoldingSetNodeID ID;
4671 TypedefType::Profile(ID, Decl, Underlying);
4672
4673 void *InsertPos = nullptr;
4674 if (TypedefType *T = TypedefTypes.FindNodeOrInsertPos(ID, InsertPos)) {
4675 assert(!T->typeMatchesDecl() &&
4676 "non-divergent case should be handled with TypeDecl");
4677 return QualType(T, 0);
4678 }
4679
4680 void *Mem = Allocate(TypedefType::totalSizeToAlloc<QualType>(true),
4681 alignof(TypedefType));
4682 auto *NewType = new (Mem) TypedefType(Type::Typedef, Decl, Underlying,
4683 getCanonicalType(Underlying));
4684 TypedefTypes.InsertNode(NewType, InsertPos);
4685 Types.push_back(NewType);
4686 return QualType(NewType, 0);
4687}
4688
4690 QualType Underlying) const {
4691 llvm::FoldingSetNodeID ID;
4692 UsingType::Profile(ID, Found, Underlying);
4693
4694 void *InsertPos = nullptr;
4695 if (UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos))
4696 return QualType(T, 0);
4697
4698 const Type *TypeForDecl =
4699 cast<TypeDecl>(Found->getTargetDecl())->getTypeForDecl();
4700
4701 assert(!Underlying.hasLocalQualifiers());
4702 QualType Canon = Underlying->getCanonicalTypeInternal();
4703 assert(TypeForDecl->getCanonicalTypeInternal() == Canon);
4704
4705 if (Underlying.getTypePtr() == TypeForDecl)
4706 Underlying = QualType();
4707 void *Mem =
4708 Allocate(UsingType::totalSizeToAlloc<QualType>(!Underlying.isNull()),
4709 alignof(UsingType));
4710 UsingType *NewType = new (Mem) UsingType(Found, Underlying, Canon);
4711 Types.push_back(NewType);
4712 UsingTypes.InsertNode(NewType, InsertPos);
4713 return QualType(NewType, 0);
4714}
4715
4717 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4718
4719 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
4720 if (PrevDecl->TypeForDecl)
4721 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
4722
4723 auto *newType = new (*this, alignof(RecordType)) RecordType(Decl);
4724 Decl->TypeForDecl = newType;
4725 Types.push_back(newType);
4726 return QualType(newType, 0);
4727}
4728
4730 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4731
4732 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
4733 if (PrevDecl->TypeForDecl)
4734 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
4735
4736 auto *newType = new (*this, alignof(EnumType)) EnumType(Decl);
4737 Decl->TypeForDecl = newType;
4738 Types.push_back(newType);
4739 return QualType(newType, 0);
4740}
4741
4743 const UnresolvedUsingTypenameDecl *Decl) const {
4744 if (Decl->TypeForDecl)
4745 return QualType(Decl->TypeForDecl, 0);
4746
4747 if (const UnresolvedUsingTypenameDecl *CanonicalDecl =
4749 if (CanonicalDecl->TypeForDecl)
4750 return QualType(Decl->TypeForDecl = CanonicalDecl->TypeForDecl, 0);
4751
4752 Type *newType =
4753 new (*this, alignof(UnresolvedUsingType)) UnresolvedUsingType(Decl);
4754 Decl->TypeForDecl = newType;
4755 Types.push_back(newType);
4756 return QualType(newType, 0);
4757}
4758
4760 QualType modifiedType,
4761 QualType equivalentType) const {
4762 llvm::FoldingSetNodeID id;
4763 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
4764
4765 void *insertPos = nullptr;
4766 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
4767 if (type) return QualType(type, 0);
4768
4769 QualType canon = getCanonicalType(equivalentType);
4770 type = new (*this, alignof(AttributedType))
4771 AttributedType(canon, attrKind, modifiedType, equivalentType);
4772
4773 Types.push_back(type);
4774 AttributedTypes.InsertNode(type, insertPos);
4775
4776 return QualType(type, 0);
4777}
4778
4779QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
4780 QualType Wrapped) {
4781 llvm::FoldingSetNodeID ID;
4782 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
4783
4784 void *InsertPos = nullptr;
4786 BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
4787 if (Ty)
4788 return QualType(Ty, 0);
4789
4790 QualType Canon = getCanonicalType(Wrapped);
4791 Ty = new (*this, alignof(BTFTagAttributedType))
4792 BTFTagAttributedType(Canon, Wrapped, BTFAttr);
4793
4794 Types.push_back(Ty);
4795 BTFTagAttributedTypes.InsertNode(Ty, InsertPos);
4796
4797 return QualType(Ty, 0);
4798}
4799
4800/// Retrieve a substitution-result type.
4802 QualType Replacement, Decl *AssociatedDecl, unsigned Index,
4803 std::optional<unsigned> PackIndex) const {
4804 llvm::FoldingSetNodeID ID;
4805 SubstTemplateTypeParmType::Profile(ID, Replacement, AssociatedDecl, Index,
4806 PackIndex);
4807 void *InsertPos = nullptr;
4808 SubstTemplateTypeParmType *SubstParm =
4809 SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4810
4811 if (!SubstParm) {
4812 void *Mem = Allocate(SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
4813 !Replacement.isCanonical()),
4814 alignof(SubstTemplateTypeParmType));
4815 SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
4816 Index, PackIndex);
4817 Types.push_back(SubstParm);
4818 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
4819 }
4820
4821 return QualType(SubstParm, 0);
4822}
4823
4824/// Retrieve a
4827 unsigned Index, bool Final,
4828 const TemplateArgument &ArgPack) {
4829#ifndef NDEBUG
4830 for (const auto &P : ArgPack.pack_elements())
4831 assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type");
4832#endif
4833
4834 llvm::FoldingSetNodeID ID;
4835 SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
4836 ArgPack);
4837 void *InsertPos = nullptr;
4838 if (SubstTemplateTypeParmPackType *SubstParm =
4839 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
4840 return QualType(SubstParm, 0);
4841
4842 QualType Canon;
4843 {
4844 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
4845 if (!AssociatedDecl->isCanonicalDecl() ||
4846 !CanonArgPack.structurallyEquals(ArgPack)) {
4848 AssociatedDecl->getCanonicalDecl(), Index, Final, CanonArgPack);
4849 [[maybe_unused]] const auto *Nothing =
4850 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
4851 assert(!Nothing);
4852 }
4853 }
4854
4855 auto *SubstParm = new (*this, alignof(SubstTemplateTypeParmPackType))
4856 SubstTemplateTypeParmPackType(Canon, AssociatedDecl, Index, Final,
4857 ArgPack);
4858 Types.push_back(SubstParm);
4859 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
4860 return QualType(SubstParm, 0);
4861}
4862
4863/// Retrieve the template type parameter type for a template
4864/// parameter or parameter pack with the given depth, index, and (optionally)
4865/// name.
4866QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
4867 bool ParameterPack,
4868 TemplateTypeParmDecl *TTPDecl) const {
4869 llvm::FoldingSetNodeID ID;
4870 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
4871 void *InsertPos = nullptr;
4872 TemplateTypeParmType *TypeParm
4873 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4874
4875 if (TypeParm)
4876 return QualType(TypeParm, 0);
4877
4878 if (TTPDecl) {
4879 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
4880 TypeParm = new (*this, alignof(TemplateTypeParmType))
4881 TemplateTypeParmType(TTPDecl, Canon);
4882
4883 TemplateTypeParmType *TypeCheck
4884 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4885 assert(!TypeCheck && "Template type parameter canonical type broken");
4886 (void)TypeCheck;
4887 } else
4888 TypeParm = new (*this, alignof(TemplateTypeParmType))
4889 TemplateTypeParmType(Depth, Index, ParameterPack);
4890
4891 Types.push_back(TypeParm);
4892 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
4893
4894 return QualType(TypeParm, 0);
4895}
4896
4899 SourceLocation NameLoc,
4900 const TemplateArgumentListInfo &Args,
4901 QualType Underlying) const {
4902 assert(!Name.getAsDependentTemplateName() &&
4903 "No dependent template names here!");
4904 QualType TST =
4905 getTemplateSpecializationType(Name, Args.arguments(), Underlying);
4906
4911 TL.setTemplateNameLoc(NameLoc);
4912 TL.setLAngleLoc(Args.getLAngleLoc());
4913 TL.setRAngleLoc(Args.getRAngleLoc());
4914 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
4915 TL.setArgLocInfo(i, Args[i].getLocInfo());
4916 return DI;
4917}
4918
4922 QualType Underlying) const {
4923 assert(!Template.getAsDependentTemplateName() &&
4924 "No dependent template names here!");
4925
4927 ArgVec.reserve(Args.size());
4928 for (const TemplateArgumentLoc &Arg : Args)
4929 ArgVec.push_back(Arg.getArgument());
4930
4931 return getTemplateSpecializationType(Template, ArgVec, Underlying);
4932}
4933
4934#ifndef NDEBUG
4936 for (const TemplateArgument &Arg : Args)
4937 if (Arg.isPackExpansion())
4938 return true;
4939
4940 return true;
4941}
4942#endif
4943
4947 QualType Underlying) const {
4948 assert(!Template.getAsDependentTemplateName() &&
4949 "No dependent template names here!");
4950 // Look through qualified template names.
4952 Template = QTN->getUnderlyingTemplate();
4953
4954 const auto *TD = Template.getAsTemplateDecl();
4955 bool IsTypeAlias = TD && TD->isTypeAlias();
4956 QualType CanonType;
4957 if (!Underlying.isNull())
4958 CanonType = getCanonicalType(Underlying);
4959 else {
4960 // We can get here with an alias template when the specialization contains
4961 // a pack expansion that does not match up with a parameter pack.
4962 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
4963 "Caller must compute aliased type");
4964 IsTypeAlias = false;
4965 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
4966 }
4967
4968 // Allocate the (non-canonical) template specialization type, but don't
4969 // try to unique it: these types typically have location information that
4970 // we don't unique and don't want to lose.
4971 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
4972 sizeof(TemplateArgument) * Args.size() +
4973 (IsTypeAlias ? sizeof(QualType) : 0),
4975 auto *Spec
4976 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
4977 IsTypeAlias ? Underlying : QualType());
4978
4979 Types.push_back(Spec);
4980 return QualType(Spec, 0);
4981}
4982
4984 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
4985 assert(!Template.getAsDependentTemplateName() &&
4986 "No dependent template names here!");
4987
4988 // Look through qualified template names.
4990 Template = TemplateName(QTN->getUnderlyingTemplate());
4991
4992 // Build the canonical template specialization type.
4993 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
4994 bool AnyNonCanonArgs = false;
4995 auto CanonArgs =
4996 ::getCanonicalTemplateArguments(*this, Args, AnyNonCanonArgs);
4997
4998 // Determine whether this canonical template specialization type already
4999 // exists.
5000 llvm::FoldingSetNodeID ID;
5001 TemplateSpecializationType::Profile(ID, CanonTemplate,
5002 CanonArgs, *this);
5003
5004 void *InsertPos = nullptr;
5006 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
5007
5008 if (!Spec) {
5009 // Allocate a new canonical template specialization type.
5010 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
5011 sizeof(TemplateArgument) * CanonArgs.size()),
5013 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
5014 CanonArgs,
5015 QualType(), QualType());
5016 Types.push_back(Spec);
5017 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
5018 }
5019
5020 assert(Spec->isDependentType() &&
5021 "Non-dependent template-id type must have a canonical type");
5022 return QualType(Spec, 0);
5023}
5024
5027 QualType NamedType,
5028 TagDecl *OwnedTagDecl) const {
5029 llvm::FoldingSetNodeID ID;
5030 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
5031
5032 void *InsertPos = nullptr;
5033 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
5034 if (T)
5035 return QualType(T, 0);
5036
5037 QualType Canon = NamedType;
5038 if (!Canon.isCanonical()) {
5039 Canon = getCanonicalType(NamedType);
5040 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
5041 assert(!CheckT && "Elaborated canonical type broken");
5042 (void)CheckT;
5043 }
5044
5045 void *Mem =
5046 Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
5047 alignof(ElaboratedType));
5048 T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
5049
5050 Types.push_back(T);
5051 ElaboratedTypes.InsertNode(T, InsertPos);
5052 return QualType(T, 0);
5053}
5054
5057 llvm::FoldingSetNodeID ID;
5058 ParenType::Profile(ID, InnerType);
5059
5060 void *InsertPos = nullptr;
5061 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
5062 if (T)
5063 return QualType(T, 0);
5064
5065 QualType Canon = InnerType;
5066 if (!Canon.isCanonical()) {
5067 Canon = getCanonicalType(InnerType);
5068 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
5069 assert(!CheckT && "Paren canonical type broken");
5070 (void)CheckT;
5071 }
5072
5073 T = new (*this, alignof(ParenType)) ParenType(InnerType, Canon);
5074 Types.push_back(T);
5075 ParenTypes.InsertNode(T, InsertPos);
5076 return QualType(T, 0);
5077}
5078
5081 const IdentifierInfo *MacroII) const {
5082 QualType Canon = UnderlyingTy;
5083 if (!Canon.isCanonical())
5084 Canon = getCanonicalType(UnderlyingTy);
5085
5086 auto *newType = new (*this, alignof(MacroQualifiedType))
5087 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
5088 Types.push_back(newType);
5089 return QualType(newType, 0);
5090}
5091
5094 const IdentifierInfo *Name,
5095 QualType Canon) const {
5096 if (Canon.isNull()) {
5098 if (CanonNNS != NNS)
5099 Canon = getDependentNameType(Keyword, CanonNNS, Name);
5100 }
5101
5102 llvm::FoldingSetNodeID ID;
5103 DependentNameType::Profile(ID, Keyword, NNS, Name);
5104
5105 void *InsertPos = nullptr;
5107 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
5108 if (T)
5109 return QualType(T, 0);
5110
5111 T = new (*this, alignof(DependentNameType))
5112 DependentNameType(Keyword, NNS, Name, Canon);
5113 Types.push_back(T);
5114 DependentNameTypes.InsertNode(T, InsertPos);
5115 return QualType(T, 0);
5116}
5117
5120 const IdentifierInfo *Name, ArrayRef<TemplateArgumentLoc> Args) const {
5121 // TODO: avoid this copy
5123 for (unsigned I = 0, E = Args.size(); I != E; ++I)
5124 ArgCopy.push_back(Args[I].getArgument());
5125 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
5126}
5127
5130 ElaboratedTypeKeyword Keyword,
5132 const IdentifierInfo *Name,
5133 ArrayRef<TemplateArgument> Args) const {
5134 assert((!NNS || NNS->isDependent()) &&
5135 "nested-name-specifier must be dependent");
5136
5137 llvm::FoldingSetNodeID ID;
5138 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
5139 Name, Args);
5140
5141 void *InsertPos = nullptr;
5143 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
5144 if (T)
5145 return QualType(T, 0);
5146
5148
5149 ElaboratedTypeKeyword CanonKeyword = Keyword;
5150 if (Keyword == ElaboratedTypeKeyword::None)
5151 CanonKeyword = ElaboratedTypeKeyword::Typename;
5152
5153 bool AnyNonCanonArgs = false;
5154 auto CanonArgs =
5155 ::getCanonicalTemplateArguments(*this, Args, AnyNonCanonArgs);
5156
5157 QualType Canon;
5158 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
5159 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
5160 Name,
5161 CanonArgs);
5162
5163 // Find the insert position again.
5164 [[maybe_unused]] auto *Nothing =
5165 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
5166 assert(!Nothing && "canonical type broken");
5167 }
5168
5169 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
5170 sizeof(TemplateArgument) * Args.size()),
5172 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
5173 Name, Args, Canon);
5174 Types.push_back(T);
5175 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
5176 return QualType(T, 0);
5177}
5178
5180 TemplateArgument Arg;
5181 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
5182 QualType ArgType = getTypeDeclType(TTP);
5183 if (TTP->isParameterPack())
5184 ArgType = getPackExpansionType(ArgType, std::nullopt);
5185
5186 Arg = TemplateArgument(ArgType);
5187 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5188 QualType T =
5189 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
5190 // For class NTTPs, ensure we include the 'const' so the type matches that
5191 // of a real template argument.
5192 // FIXME: It would be more faithful to model this as something like an
5193 // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
5194 if (T->isRecordType())
5195 T.addConst();
5196 Expr *E = new (*this) DeclRefExpr(
5197 *this, NTTP, /*RefersToEnclosingVariableOrCapture*/ false, T,
5198 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
5199
5200 if (NTTP->isParameterPack())
5201 E = new (*this)
5202 PackExpansionExpr(DependentTy, E, NTTP->getLocation(), std::nullopt);
5203 Arg = TemplateArgument(E);
5204 } else {
5205 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
5206 if (TTP->isParameterPack())
5207 Arg = TemplateArgument(TemplateName(TTP), std::optional<unsigned>());
5208 else
5209 Arg = TemplateArgument(TemplateName(TTP));
5210 }
5211
5212 if (Param->isTemplateParameterPack())
5213 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
5214
5215 return Arg;
5216}
5217
5218void
5221 Args.reserve(Args.size() + Params->size());
5222
5223 for (NamedDecl *Param : *Params)
5224 Args.push_back(getInjectedTemplateArg(Param));
5225}
5226
5228 std::optional<unsigned> NumExpansions,
5229 bool ExpectPackInType) {
5230 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
5231 "Pack expansions must expand one or more parameter packs");
5232
5233 llvm::FoldingSetNodeID ID;
5234 PackExpansionType::Profile(ID, Pattern, NumExpansions);
5235
5236 void *InsertPos = nullptr;
5237 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
5238 if (T)
5239 return QualType(T, 0);
5240
5241 QualType Canon;
5242 if (!Pattern.isCanonical()) {
5243 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
5244 /*ExpectPackInType=*/false);
5245
5246 // Find the insert position again, in case we inserted an element into
5247 // PackExpansionTypes and invalidated our insert position.
5248 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
5249 }
5250
5251 T = new (*this, alignof(PackExpansionType))
5252 PackExpansionType(Pattern, Canon, NumExpansions);
5253 Types.push_back(T);
5254 PackExpansionTypes.InsertNode(T, InsertPos);
5255 return QualType(T, 0);
5256}
5257
5258/// CmpProtocolNames - Comparison predicate for sorting protocols
5259/// alphabetically.
5260static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
5261 ObjCProtocolDecl *const *RHS) {
5262 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
5263}
5264
5266 if (Protocols.empty()) return true;
5267
5268 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
5269 return false;
5270
5271 for (unsigned i = 1; i != Protocols.size(); ++i)
5272 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
5273 Protocols[i]->getCanonicalDecl() != Protocols[i])
5274 return false;
5275 return true;
5276}
5277
5278static void
5280 // Sort protocols, keyed by name.
5281 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
5282
5283 // Canonicalize.
5284 for (ObjCProtocolDecl *&P : Protocols)
5285 P = P->getCanonicalDecl();
5286
5287 // Remove duplicates.
5288 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
5289 Protocols.erase(ProtocolsEnd, Protocols.end());
5290}
5291
5293 ObjCProtocolDecl * const *Protocols,
5294 unsigned NumProtocols) const {
5295 return getObjCObjectType(BaseType, {},
5296 llvm::ArrayRef(Protocols, NumProtocols),
5297 /*isKindOf=*/false);
5298}
5299
5301 QualType baseType,
5302 ArrayRef<QualType> typeArgs,
5304 bool isKindOf) const {
5305 // If the base type is an interface and there aren't any protocols or
5306 // type arguments to add, then the interface type will do just fine.
5307 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
5308 isa<ObjCInterfaceType>(baseType))
5309 return baseType;
5310
5311 // Look in the folding set for an existing type.
5312 llvm::FoldingSetNodeID ID;
5313 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
5314 void *InsertPos = nullptr;
5315 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
5316 return QualType(QT, 0);
5317
5318 // Determine the type arguments to be used for canonicalization,
5319 // which may be explicitly specified here or written on the base
5320 // type.
5321 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
5322 if (effectiveTypeArgs.empty()) {
5323 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
5324 effectiveTypeArgs = baseObject->getTypeArgs();
5325 }
5326
5327 // Build the canonical type, which has the canonical base type and a
5328 // sorted-and-uniqued list of protocols and the type arguments
5329 // canonicalized.
5330 QualType canonical;
5331 bool typeArgsAreCanonical = llvm::all_of(
5332 effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); });
5333 bool protocolsSorted = areSortedAndUniqued(protocols);
5334 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
5335 // Determine the canonical type arguments.
5336 ArrayRef<QualType> canonTypeArgs;
5337 SmallVector<QualType, 4> canonTypeArgsVec;
5338 if (!typeArgsAreCanonical) {
5339 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
5340 for (auto typeArg : effectiveTypeArgs)
5341 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
5342 canonTypeArgs = canonTypeArgsVec;
5343 } else {
5344 canonTypeArgs = effectiveTypeArgs;
5345 }
5346
5347 ArrayRef<ObjCProtocolDecl *> canonProtocols;
5348 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
5349 if (!protocolsSorted) {
5350 canonProtocolsVec.append(protocols.begin(), protocols.end());
5351 SortAndUniqueProtocols(canonProtocolsVec);
5352 canonProtocols = canonProtocolsVec;
5353 } else {
5354 canonProtocols = protocols;
5355 }
5356
5357 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
5358 canonProtocols, isKindOf);
5359
5360 // Regenerate InsertPos.
5361 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
5362 }
5363
5364 unsigned size = sizeof(ObjCObjectTypeImpl);
5365 size += typeArgs.size() * sizeof(QualType);
5366 size += protocols.size() * sizeof(ObjCProtocolDecl *);
5367 void *mem = Allocate(size, alignof(ObjCObjectTypeImpl));
5368 auto *T =
5369 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
5370 isKindOf);
5371
5372 Types.push_back(T);
5373 ObjCObjectTypes.InsertNode(T, InsertPos);
5374 return QualType(T, 0);
5375}
5376
5377/// Apply Objective-C protocol qualifiers to the given type.
5378/// If this is for the canonical type of a type parameter, we can apply
5379/// protocol qualifiers on the ObjCObjectPointerType.
5382 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
5383 bool allowOnPointerType) const {
5384 hasError = false;
5385
5386 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
5387 return getObjCTypeParamType(objT->getDecl(), protocols);
5388 }
5389
5390 // Apply protocol qualifiers to ObjCObjectPointerType.
5391 if (allowOnPointerType) {
5392 if (const auto *objPtr =
5393 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
5394 const ObjCObjectType *objT = objPtr->getObjectType();
5395 // Merge protocol lists and construct ObjCObjectType.
5397 protocolsVec.append(objT->qual_begin(),
5398 objT->qual_end());
5399 protocolsVec.append(protocols.begin(), protocols.end());
5400 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
5402 objT->getBaseType(),
5403 objT->getTypeArgsAsWritten(),
5404 protocols,
5405 objT->isKindOfTypeAsWritten());
5407 }
5408 }
5409
5410 // Apply protocol qualifiers to ObjCObjectType.
5411 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
5412 // FIXME: Check for protocols to which the class type is already
5413 // known to conform.
5414
5415 return getObjCObjectType(objT->getBaseType(),
5416 objT->getTypeArgsAsWritten(),
5417 protocols,
5418 objT->isKindOfTypeAsWritten());
5419 }
5420
5421 // If the canonical type is ObjCObjectType, ...
5422 if (type->isObjCObjectType()) {
5423 // Silently overwrite any existing protocol qualifiers.
5424 // TODO: determine whether that's the right thing to do.
5425
5426 // FIXME: Check for protocols to which the class type is already
5427 // known to conform.
5428 return getObjCObjectType(type, {}, protocols, false);
5429 }
5430
5431 // id<protocol-list>
5432 if (type->isObjCIdType()) {
5433 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
5434 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
5435 objPtr->isKindOfType());
5437 }
5438
5439 // Class<protocol-list>
5440 if (type->isObjCClassType()) {
5441 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
5442 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
5443 objPtr->isKindOfType());
5445 }
5446
5447 hasError = true;
5448 return type;
5449}
5450
5453 ArrayRef<ObjCProtocolDecl *> protocols) const {
5454 // Look in the folding set for an existing type.
5455 llvm::FoldingSetNodeID ID;
5456 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
5457 void *InsertPos = nullptr;
5458 if (ObjCTypeParamType *TypeParam =
5459 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
5460 return QualType(TypeParam, 0);
5461
5462 // We canonicalize to the underlying type.
5463 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
5464 if (!protocols.empty()) {
5465 // Apply the protocol qualifers.
5466 bool hasError;
5468 Canonical, protocols, hasError, true /*allowOnPointerType*/));
5469 assert(!hasError && "Error when apply protocol qualifier to bound type");
5470 }
5471
5472 unsigned size = sizeof(ObjCTypeParamType);
5473 size += protocols.size() * sizeof(ObjCProtocolDecl *);
5474 void *mem = Allocate(size, alignof(ObjCTypeParamType));
5475 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
5476
5477 Types.push_back(newType);
5478 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
5479 return QualType(newType, 0);
5480}
5481
5483 ObjCTypeParamDecl *New) const {
5485 // Update TypeForDecl after updating TypeSourceInfo.
5486 auto NewTypeParamTy = cast<ObjCTypeParamType>(New->getTypeForDecl());
5488 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
5489 QualType UpdatedTy = getObjCTypeParamType(New, protocols);
5490 New->setTypeForDecl(UpdatedTy.getTypePtr());
5491}
5492
5493/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
5494/// protocol list adopt all protocols in QT's qualified-id protocol
5495/// list.
5497 ObjCInterfaceDecl *IC) {
5498 if (!QT->isObjCQualifiedIdType())
5499 return false;
5500
5501 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
5502 // If both the right and left sides have qualifiers.
5503 for (auto *Proto : OPT->quals()) {
5504 if (!IC->ClassImplementsProtocol(Proto, false))
5505 return false;
5506 }
5507 return true;
5508 }
5509 return false;
5510}
5511
5512/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
5513/// QT's qualified-id protocol list adopt all protocols in IDecl's list
5514/// of protocols.
5516 ObjCInterfaceDecl *IDecl) {
5517 if (!QT->isObjCQualifiedIdType())
5518 return false;
5519 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
5520 if (!OPT)
5521 return false;
5522 if (!IDecl->hasDefinition())
5523 return false;
5525 CollectInheritedProtocols(IDecl, InheritedProtocols);
5526 if (InheritedProtocols.empty())
5527 return false;
5528 // Check that if every protocol in list of id<plist> conforms to a protocol
5529 // of IDecl's, then bridge casting is ok.
5530 bool Conforms = false;
5531 for (auto *Proto : OPT->quals()) {
5532 Conforms = false;
5533 for (auto *PI : InheritedProtocols) {
5534 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
5535 Conforms = true;
5536 break;
5537 }
5538 }
5539 if (!Conforms)
5540 break;
5541 }
5542 if (Conforms)
5543 return true;
5544
5545 for (auto *PI : InheritedProtocols) {
5546 // If both the right and left sides have qualifiers.
5547 bool Adopts = false;
5548 for (auto *Proto : OPT->quals()) {
5549 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
5550 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
5551 break;
5552 }
5553 if (!Adopts)
5554 return false;
5555 }
5556 return true;
5557}
5558
5559/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
5560/// the given object type.
5562 llvm::FoldingSetNodeID ID;
5563 ObjCObjectPointerType::Profile(ID, ObjectT);
5564
5565 void *InsertPos = nullptr;
5566 if (ObjCObjectPointerType *QT =
5567 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
5568 return QualType(QT, 0);
5569
5570 // Find the canonical object type.
5571 QualType Canonical;
5572 if (!ObjectT.isCanonical()) {
5573 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
5574
5575 // Regenerate InsertPos.
5576 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
5577 }
5578
5579 // No match.
5580 void *Mem =
5582 auto *QType =
5583 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
5584
5585 Types.push_back(QType);
5586 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
5587 return QualType(QType, 0);
5588}
5589
5590/// getObjCInterfaceType - Return the unique reference to the type for the
5591/// specified ObjC interface decl. The list of protocols is optional.
5593 ObjCInterfaceDecl *PrevDecl) const {
5594 if (Decl->TypeForDecl)
5595 return QualType(Decl->TypeForDecl, 0);
5596
5597 if (PrevDecl) {
5598 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
5599 Decl->TypeForDecl = PrevDecl->TypeForDecl;
5600 return QualType(PrevDecl->TypeForDecl, 0);
5601 }
5602
5603 // Prefer the definition, if there is one.
5604 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
5605 Decl = Def;
5606
5607 void *Mem = Allocate(sizeof(ObjCInterfaceType), alignof(ObjCInterfaceType));
5608 auto *T = new (Mem) ObjCInterfaceType(Decl);
5609 Decl->TypeForDecl = T;
5610 Types.push_back(T);
5611 return QualType(T, 0);
5612}
5613
5614/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
5615/// TypeOfExprType AST's (since expression's are never shared). For example,
5616/// multiple declarations that refer to "typeof(x)" all contain different
5617/// DeclRefExpr's. This doesn't effect the type checker, since it operates
5618/// on canonical type's (which are always unique).
5620 TypeOfExprType *toe;
5621 if (tofExpr->isTypeDependent()) {
5622 llvm::FoldingSetNodeID ID;
5623 DependentTypeOfExprType::Profile(ID, *this, tofExpr,
5624 Kind == TypeOfKind::Unqualified);
5625
5626 void *InsertPos = nullptr;
5628 DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
5629 if (Canon) {
5630 // We already have a "canonical" version of an identical, dependent
5631 // typeof(expr) type. Use that as our canonical type.
5632 toe = new (*this, alignof(TypeOfExprType))
5633 TypeOfExprType(tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
5634 } else {
5635 // Build a new, canonical typeof(expr) type.
5636 Canon = new (*this, alignof(DependentTypeOfExprType))
5637 DependentTypeOfExprType(tofExpr, Kind);
5638 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
5639 toe = Canon;
5640 }
5641 } else {
5642 QualType Canonical = getCanonicalType(tofExpr->getType());
5643 toe = new (*this, alignof(TypeOfExprType))
5644 TypeOfExprType(tofExpr, Kind, Canonical);
5645 }
5646 Types.push_back(toe);
5647 return QualType(toe, 0);
5648}
5649
5650/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
5651/// TypeOfType nodes. The only motivation to unique these nodes would be
5652/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
5653/// an issue. This doesn't affect the type checker, since it operates
5654/// on canonical types (which are always unique).
5656 QualType Canonical = getCanonicalType(tofType);
5657 auto *tot =
5658 new (*this, alignof(TypeOfType)) TypeOfType(tofType, Canonical, Kind);
5659 Types.push_back(tot);
5660 return QualType(tot, 0);
5661}
5662
5663/// getReferenceQualifiedType - Given an expr, will return the type for
5664/// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
5665/// and class member access into account.
5667 // C++11 [dcl.type.simple]p4:
5668 // [...]
5669 QualType T = E->getType();
5670 switch (E->getValueKind()) {
5671 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
5672 // type of e;
5673 case VK_XValue:
5674 return getRValueReferenceType(T);
5675 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
5676 // type of e;
5677 case VK_LValue:
5678 return getLValueReferenceType(T);
5679 // - otherwise, decltype(e) is the type of e.
5680 case VK_PRValue:
5681 return T;
5682 }
5683 llvm_unreachable("Unknown value kind");
5684}
5685
5686/// Unlike many "get<Type>" functions, we don't unique DecltypeType
5687/// nodes. This would never be helpful, since each such type has its own
5688/// expression, and would not give a significant memory saving, since there
5689/// is an Expr tree under each such type.
5691 DecltypeType *dt;
5692
5693 // C++11 [temp.type]p2:
5694 // If an expression e involves a template parameter, decltype(e) denotes a
5695 // unique dependent type. Two such decltype-specifiers refer to the same
5696 // type only if their expressions are equivalent (14.5.6.1).
5697 if (e->isInstantiationDependent()) {
5698 llvm::FoldingSetNodeID ID;
5699 DependentDecltypeType::Profile(ID, *this, e);
5700
5701 void *InsertPos = nullptr;
5703 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
5704 if (!Canon) {
5705 // Build a new, canonical decltype(expr) type.
5706 Canon = new (*this, alignof(DependentDecltypeType))
5708 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
5709 }
5710 dt = new (*this, alignof(DecltypeType))
5711 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
5712 } else {
5713 dt = new (*this, alignof(DecltypeType))
5714 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
5715 }
5716 Types.push_back(dt);
5717 return QualType(dt, 0);
5718}
5719
5721 bool FullySubstituted,
5722 ArrayRef<QualType> Expansions,
5723 int Index) const {
5724 QualType Canonical;
5725 if (FullySubstituted && Index != -1) {
5726 Canonical = getCanonicalType(Expansions[Index]);
5727 } else {
5728 llvm::FoldingSetNodeID ID;
5729 PackIndexingType::Profile(ID, *this, Pattern, IndexExpr);
5730 void *InsertPos = nullptr;
5731 PackIndexingType *Canon =
5732 DependentPackIndexingTypes.FindNodeOrInsertPos(ID, InsertPos);
5733 if (!Canon) {
5734 void *Mem = Allocate(
5735 PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
5737 Canon = new (Mem)
5738 PackIndexingType(*this, QualType(), Pattern, IndexExpr, Expansions);
5739 DependentPackIndexingTypes.InsertNode(Canon, InsertPos);
5740 }
5741 Canonical = QualType(Canon, 0);
5742 }
5743
5744 void *Mem =
5745 Allocate(PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
5747 auto *T = new (Mem)
5748 PackIndexingType(*this, Canonical, Pattern, IndexExpr, Expansions);
5749 Types.push_back(T);
5750 return QualType(T, 0);
5751}
5752
5753/// getUnaryTransformationType - We don't unique these, since the memory
5754/// savings are minimal and these are rare.
5756 QualType UnderlyingType,
5758 const {
5759 UnaryTransformType *ut = nullptr;
5760
5761 if (BaseType->isDependentType()) {
5762 // Look in the folding set for an existing type.
5763 llvm::FoldingSetNodeID ID;
5765
5766 void *InsertPos = nullptr;
5768 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
5769
5770 if (!Canon) {
5771 // Build a new, canonical __underlying_type(type) type.
5772 Canon = new (*this, alignof(DependentUnaryTransformType))
5773 DependentUnaryTransformType(*this, getCanonicalType(BaseType), Kind);
5774 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
5775 }
5776 ut = new (*this, alignof(UnaryTransformType))
5777 UnaryTransformType(BaseType, QualType(), Kind, QualType(Canon, 0));
5778 } else {
5779 QualType CanonType = getCanonicalType(UnderlyingType);
5780 ut = new (*this, alignof(UnaryTransformType))
5781 UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType);
5782 }
5783 Types.push_back(ut);
5784 return QualType(ut, 0);
5785}
5786
5787QualType ASTContext::getAutoTypeInternal(
5788 QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent,
5789 bool IsPack, ConceptDecl *TypeConstraintConcept,
5790 ArrayRef<TemplateArgument> TypeConstraintArgs, bool IsCanon) const {
5791 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto &&
5792 !TypeConstraintConcept && !IsDependent)
5793 return getAutoDeductType();
5794
5795 // Look in the folding set for an existing type.
5796 void *InsertPos = nullptr;
5797 llvm::FoldingSetNodeID ID;
5798 AutoType::Profile(ID, *this, DeducedType, Keyword, IsDependent,
5799 TypeConstraintConcept, TypeConstraintArgs);
5800 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
5801 return QualType(AT, 0);
5802
5803 QualType Canon;
5804 if (!IsCanon) {
5805 if (!DeducedType.isNull()) {
5806 Canon = DeducedType.getCanonicalType();
5807 } else if (TypeConstraintConcept) {
5808 bool AnyNonCanonArgs = false;
5809 ConceptDecl *CanonicalConcept = TypeConstraintConcept->getCanonicalDecl();
5810 auto CanonicalConceptArgs = ::getCanonicalTemplateArguments(
5811 *this, TypeConstraintArgs, AnyNonCanonArgs);
5812 if (CanonicalConcept != TypeConstraintConcept || AnyNonCanonArgs) {
5813 Canon =
5814 getAutoTypeInternal(QualType(), Keyword, IsDependent, IsPack,
5815 CanonicalConcept, CanonicalConceptArgs, true);
5816 // Find the insert position again.
5817 [[maybe_unused]] auto *Nothing =
5818 AutoTypes.FindNodeOrInsertPos(ID, InsertPos);
5819 assert(!Nothing && "canonical type broken");
5820 }
5821 }
5822 }
5823
5824 void *Mem = Allocate(sizeof(AutoType) +
5825 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
5826 alignof(AutoType));
5827 auto *AT = new (Mem) AutoType(
5828 DeducedType, Keyword,
5829 (IsDependent ? TypeDependence::DependentInstantiation
5830 : TypeDependence::None) |
5831 (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None),
5832 Canon, TypeConstraintConcept, TypeConstraintArgs);
5833 Types.push_back(AT);
5834 AutoTypes.InsertNode(AT, InsertPos);
5835 return QualType(AT, 0);
5836}
5837
5838/// getAutoType - Return the uniqued reference to the 'auto' type which has been
5839/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
5840/// canonical deduced-but-dependent 'auto' type.
5843 bool IsDependent, bool IsPack,
5844 ConceptDecl *TypeConstraintConcept,
5845 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
5846 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
5847 assert((!IsDependent || DeducedType.isNull()) &&
5848 "A dependent auto should be undeduced");
5849 return getAutoTypeInternal(DeducedType, Keyword, IsDependent, IsPack,
5850 TypeConstraintConcept, TypeConstraintArgs);
5851}
5852
5854 QualType CanonT = T.getCanonicalType();
5855
5856 // Remove a type-constraint from a top-level auto or decltype(auto).
5857 if (auto *AT = CanonT->getAs<AutoType>()) {
5858 if (!AT->isConstrained())
5859 return T;
5860 return getQualifiedType(getAutoType(QualType(), AT->getKeyword(), false,
5862 T.getQualifiers());
5863 }
5864
5865 // FIXME: We only support constrained auto at the top level in the type of a
5866 // non-type template parameter at the moment. Once we lift that restriction,
5867 // we'll need to recursively build types containing auto here.
5868 assert(!CanonT->getContainedAutoType() ||
5869 !CanonT->getContainedAutoType()->isConstrained());
5870 return T;
5871}
5872
5873/// Return the uniqued reference to the deduced template specialization type
5874/// which has been deduced to the given type, or to the canonical undeduced
5875/// such type, or the canonical deduced-but-dependent such type.
5877 TemplateName Template, QualType DeducedType, bool IsDependent) const {
5878 // Look in the folding set for an existing type.
5879 void *InsertPos = nullptr;
5880 llvm::FoldingSetNodeID ID;
5882 IsDependent);
5884 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
5885 return QualType(DTST, 0);
5886
5887 auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType))
5888 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
5889 llvm::FoldingSetNodeID TempID;
5890 DTST->Profile(TempID);
5891 assert(ID == TempID && "ID does not match");
5892 Types.push_back(DTST);
5893 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
5894 return QualType(DTST, 0);
5895}
5896
5897/// getAtomicType - Return the uniqued reference to the atomic type for
5898/// the given value type.
5900 // Unique pointers, to guarantee there is only one pointer of a particular
5901 // structure.
5902 llvm::FoldingSetNodeID ID;
5903 AtomicType::Profile(ID, T);
5904
5905 void *InsertPos = nullptr;
5906 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
5907 return QualType(AT, 0);
5908
5909 // If the atomic value type isn't canonical, this won't be a canonical type
5910 // either, so fill in the canonical type field.
5911 QualType Canonical;
5912 if (!T.isCanonical()) {
5913 Canonical = getAtomicType(getCanonicalType(T));
5914
5915 // Get the new insert position for the node we care about.
5916 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
5917 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5918 }
5919 auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
5920 Types.push_back(New);
5921 AtomicTypes.InsertNode(New, InsertPos);
5922 return QualType(New, 0);
5923}
5924
5925/// getAutoDeductType - Get type pattern for deducing against 'auto'.
5927 if (AutoDeductTy.isNull())
5928 AutoDeductTy = QualType(new (*this, alignof(AutoType))
5930 TypeDependence::None, QualType(),
5931 /*concept*/ nullptr, /*args*/ {}),
5932 0);
5933 return AutoDeductTy;
5934}
5935
5936/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
5940 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
5941 return AutoRRefDeductTy;
5942}
5943
5944/// getTagDeclType - Return the unique reference to the type for the
5945/// specified TagDecl (struct/union/class/enum) decl.
5947 assert(Decl);
5948 // FIXME: What is the design on getTagDeclType when it requires casting
5949 // away const? mutable?
5950 return getTypeDeclType(const_cast<TagDecl*>(Decl));
5951}
5952
5953/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
5954/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
5955/// needs to agree with the definition in <stddef.h>.
5957 return getFromTargetType(Target->getSizeType());
5958}
5959
5960/// Return the unique signed counterpart of the integer type
5961/// corresponding to size_t.
5963 return getFromTargetType(Target->getSignedSizeType());
5964}
5965
5966/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
5968 return getFromTargetType(Target->getIntMaxType());
5969}
5970
5971/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
5973 return getFromTargetType(Target->getUIntMaxType());
5974}
5975
5976/// getSignedWCharType - Return the type of "signed wchar_t".
5977/// Used when in C++, as a GCC extension.
5979 // FIXME: derive from "Target" ?
5980 return WCharTy;
5981}
5982
5983/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
5984/// Used when in C++, as a GCC extension.
5986 // FIXME: derive from "Target" ?
5987 return UnsignedIntTy;
5988}
5989
5991 return getFromTargetType(Target->getIntPtrType());
5992}
5993
5996}
5997
5998/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
5999/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
6001 return getFromTargetType(Target->getPtrDiffType(LangAS::Default));
6002}
6003
6004/// Return the unique unsigned counterpart of "ptrdiff_t"
6005/// integer type. The standard (C11 7.21.6.1p7) refers to this type
6006/// in the definition of %tu format specifier.
6008 return getFromTargetType(Target->getUnsignedPtrDiffType(LangAS::Default));
6009}
6010
6011/// Return the unique type for "pid_t" defined in
6012/// <sys/types.h>. We need this to compute the correct type for vfork().
6014 return getFromTargetType(Target->getProcessIDType());
6015}
6016
6017//===----------------------------------------------------------------------===//
6018// Type Operators
6019//===----------------------------------------------------------------------===//
6020
6022 // Push qualifiers into arrays, and then discard any remaining
6023 // qualifiers.
6024 T = getCanonicalType(T);
6026 const Type *Ty = T.getTypePtr();
6028 if (isa<ArrayType>(Ty)) {
6030 } else if (isa<FunctionType>(Ty)) {
6031 Result = getPointerType(QualType(Ty, 0));
6032 } else {
6033 Result = QualType(Ty, 0);
6034 }
6035
6037}
6038
6040 Qualifiers &quals) {
6041 SplitQualType splitType = type.getSplitUnqualifiedType();
6042
6043 // FIXME: getSplitUnqualifiedType() actually walks all the way to
6044 // the unqualified desugared type and then drops it on the floor.
6045 // We then have to strip that sugar back off with
6046 // getUnqualifiedDesugaredType(), which is silly.
6047 const auto *AT =
6048 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
6049
6050 // If we don't have an array, just use the results in splitType.
6051 if (!AT) {
6052 quals = splitType.Quals;
6053 return QualType(splitType.Ty, 0);
6054 }
6055
6056 // Otherwise, recurse on the array's element type.
6057 QualType elementType = AT->getElementType();
6058 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
6059
6060 // If that didn't change the element type, AT has no qualifiers, so we
6061 // can just use the results in splitType.
6062 if (elementType == unqualElementType) {
6063 assert(quals.empty()); // from the recursive call
6064 quals = splitType.Quals;
6065 return QualType(splitType.Ty, 0);
6066 }
6067
6068 // Otherwise, add in the qualifiers from the outermost type, then
6069 // build the type back up.
6070 quals.addConsistentQualifiers(splitType.Quals);
6071
6072 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
6073 return getConstantArrayType(unqualElementType, CAT->getSize(),
6074 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
6075 }
6076
6077 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
6078 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
6079 }
6080
6081 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
6082 return getVariableArrayType(unqualElementType,
6083 VAT->getSizeExpr(),
6084 VAT->getSizeModifier(),
6085 VAT->getIndexTypeCVRQualifiers(),
6086 VAT->getBracketsRange());
6087 }
6088
6089 const auto *DSAT = cast<DependentSizedArrayType>(AT);
6090 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
6091 DSAT->getSizeModifier(), 0,
6092 SourceRange());
6093}
6094
6095/// Attempt to unwrap two types that may both be array types with the same bound
6096/// (or both be array types of unknown bound) for the purpose of comparing the
6097/// cv-decomposition of two types per C++ [conv.qual].
6098///
6099/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
6100/// C++20 [conv.qual], if permitted by the current language mode.
6102 bool AllowPiMismatch) {
6103 while (true) {
6104 auto *AT1 = getAsArrayType(T1);
6105 if (!AT1)
6106 return;
6107
6108 auto *AT2 = getAsArrayType(T2);
6109 if (!AT2)
6110 return;
6111
6112 // If we don't have two array types with the same constant bound nor two
6113 // incomplete array types, we've unwrapped everything we can.
6114 // C++20 also permits one type to be a constant array type and the other
6115 // to be an incomplete array type.
6116 // FIXME: Consider also unwrapping array of unknown bound and VLA.
6117 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
6118 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
6119 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
6120 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
6121 isa<IncompleteArrayType>(AT2))))
6122 return;
6123 } else if (isa<IncompleteArrayType>(AT1)) {
6124 if (!(isa<IncompleteArrayType>(AT2) ||
6125 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
6126 isa<ConstantArrayType>(AT2))))
6127 return;
6128 } else {
6129 return;
6130 }
6131
6132 T1 = AT1->getElementType();
6133 T2 = AT2->getElementType();
6134 }
6135}
6136
6137/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
6138///
6139/// If T1 and T2 are both pointer types of the same kind, or both array types
6140/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
6141/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
6142///
6143/// This function will typically be called in a loop that successively
6144/// "unwraps" pointer and pointer-to-member types to compare them at each
6145/// level.
6146///
6147/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
6148/// C++20 [conv.qual], if permitted by the current language mode.
6149///
6150/// \return \c true if a pointer type was unwrapped, \c false if we reached a
6151/// pair of types that can't be unwrapped further.
6153 bool AllowPiMismatch) {
6154 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
6155
6156 const auto *T1PtrType = T1->getAs<PointerType>();
6157 const auto *T2PtrType = T2->getAs<PointerType>();
6158 if (T1PtrType && T2PtrType) {
6159 T1 = T1PtrType->getPointeeType();
6160 T2 = T2PtrType->getPointeeType();
6161 return true;
6162 }
6163
6164 const auto *T1MPType = T1->getAs<MemberPointerType>();
6165 const auto *T2MPType = T2->getAs<MemberPointerType>();
6166 if (T1MPType && T2MPType &&
6167 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
6168 QualType(T2MPType->getClass(), 0))) {
6169 T1 = T1MPType->getPointeeType();
6170 T2 = T2MPType->getPointeeType();
6171 return true;
6172 }
6173
6174 if (getLangOpts().ObjC) {
6175 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
6176 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
6177 if (T1OPType && T2OPType) {
6178 T1 = T1OPType->getPointeeType();
6179 T2 = T2OPType->getPointeeType();
6180 return true;
6181 }
6182 }
6183
6184 // FIXME: Block pointers, too?
6185
6186 return false;
6187}
6188
6190 while (true) {
6191 Qualifiers Quals;
6192 T1 = getUnqualifiedArrayType(T1, Quals);
6193 T2 = getUnqualifiedArrayType(T2, Quals);
6194 if (hasSameType(T1, T2))
6195 return true;
6196 if (!UnwrapSimilarTypes(T1, T2))
6197 return false;
6198 }
6199}
6200
6202 while (true) {
6203 Qualifiers Quals1, Quals2;
6204 T1 = getUnqualifiedArrayType(T1, Quals1);
6205 T2 = getUnqualifiedArrayType(T2, Quals2);
6206
6207 Quals1.removeCVRQualifiers();
6208 Quals2.removeCVRQualifiers();
6209 if (Quals1 != Quals2)
6210 return false;
6211
6212 if (hasSameType(T1, T2))
6213 return true;
6214
6215 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
6216 return false;
6217 }
6218}
6219
6222 SourceLocation NameLoc) const {
6223 switch (Name.getKind()) {
6226 // DNInfo work in progress: CHECKME: what about DNLoc?
6227 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
6228 NameLoc);
6229
6231 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
6232 // DNInfo work in progress: CHECKME: what about DNLoc?
6233 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
6234 }
6235
6237 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
6238 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
6239 }
6240
6242 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
6243 DeclarationName DName;
6244 if (DTN->isIdentifier()) {
6246 return DeclarationNameInfo(DName, NameLoc);
6247 } else {
6249 // DNInfo work in progress: FIXME: source locations?
6250 DeclarationNameLoc DNLoc =
6252 return DeclarationNameInfo(DName, NameLoc, DNLoc);
6253 }
6254 }
6255
6258 = Name.getAsSubstTemplateTemplateParm();
6259 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
6260 NameLoc);
6261 }
6262
6265 = Name.getAsSubstTemplateTemplateParmPack();
6267 NameLoc);
6268 }
6270 return DeclarationNameInfo(Name.getAsUsingShadowDecl()->getDeclName(),
6271 NameLoc);
6272 }
6273
6274 llvm_unreachable("bad template name kind!");
6275}
6276
6279 switch (Name.getKind()) {
6283 TemplateDecl *Template = Name.getAsTemplateDecl();
6284 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
6285 Template = getCanonicalTemplateTemplateParmDecl(TTP);
6286
6287 // The canonical template name is the canonical template declaration.
6288 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
6289 }
6290
6293 llvm_unreachable("cannot canonicalize unresolved template");
6294
6296 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
6297 assert(DTN && "Non-dependent template names must refer to template decls.");
6298 return DTN->CanonicalTemplateName;
6299 }
6300
6303 = Name.getAsSubstTemplateTemplateParm();
6305 }
6306
6309 Name.getAsSubstTemplateTemplateParmPack();
6310 TemplateArgument canonArgPack =
6313 canonArgPack, subst->getAssociatedDecl()->getCanonicalDecl(),
6314 subst->getFinal(), subst->getIndex());
6315 }
6316 }
6317
6318 llvm_unreachable("bad template name!");
6319}
6320
6322 const TemplateName &Y) const {
6325}
6326
6327bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
6328 if (!XCE != !YCE)
6329 return false;
6330
6331 if (!XCE)
6332 return true;
6333
6334 llvm::FoldingSetNodeID XCEID, YCEID;
6335 XCE->Profile(XCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
6336 YCE->Profile(YCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
6337 return XCEID == YCEID;
6338}
6339
6341 const TypeConstraint *YTC) const {
6342 if (!XTC != !YTC)
6343 return false;
6344
6345 if (!XTC)
6346 return true;
6347
6348 auto *NCX = XTC->getNamedConcept();
6349 auto *NCY = YTC->getNamedConcept();
6350 if (!NCX || !NCY || !isSameEntity(NCX, NCY))
6351 return false;
6354 return false;
6356 if (XTC->getConceptReference()
6358 ->NumTemplateArgs !=
6360 return false;
6361
6362 // Compare slowly by profiling.
6363 //
6364 // We couldn't compare the profiling result for the template
6365 // args here. Consider the following example in different modules:
6366 //
6367 // template <__integer_like _Tp, C<_Tp> Sentinel>
6368 // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
6369 // return __t;
6370 // }
6371 //
6372 // When we compare the profiling result for `C<_Tp>` in different
6373 // modules, it will compare the type of `_Tp` in different modules.
6374 // However, the type of `_Tp` in different modules refer to different
6375 // types here naturally. So we couldn't compare the profiling result
6376 // for the template args directly.
6379}
6380
6382 const NamedDecl *Y) const {
6383 if (X->getKind() != Y->getKind())
6384 return false;
6385
6386 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
6387 auto *TY = cast<TemplateTypeParmDecl>(Y);
6388 if (TX->isParameterPack() != TY->isParameterPack())
6389 return false;
6390 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
6391 return false;
6392 return isSameTypeConstraint(TX->getTypeConstraint(),
6393 TY->getTypeConstraint());
6394 }
6395
6396 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
6397 auto *TY = cast<NonTypeTemplateParmDecl>(Y);
6398 return TX->isParameterPack() == TY->isParameterPack() &&
6399 TX->getASTContext().hasSameType(TX->getType(), TY->getType()) &&
6400 isSameConstraintExpr(TX->getPlaceholderTypeConstraint(),
6401 TY->getPlaceholderTypeConstraint());
6402 }
6403
6404 auto *TX = cast<TemplateTemplateParmDecl>(X);
6405 auto *TY = cast<TemplateTemplateParmDecl>(Y);
6406 return TX->isParameterPack() == TY->isParameterPack() &&
6407 isSameTemplateParameterList(TX->getTemplateParameters(),
6408 TY->getTemplateParameters());
6409}
6410
6412 const TemplateParameterList *X, const TemplateParameterList *Y) const {
6413 if (X->size() != Y->size())
6414 return false;
6415
6416 for (unsigned I = 0, N = X->size(); I != N; ++I)
6417 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
6418 return false;
6419
6420 return isSameConstraintExpr(X->getRequiresClause(), Y->getRequiresClause());
6421}
6422
6424 const NamedDecl *Y) const {
6425 // If the type parameter isn't the same already, we don't need to check the
6426 // default argument further.
6427 if (!isSameTemplateParameter(X, Y))
6428 return false;
6429
6430 if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(X)) {
6431 auto *TTPY = cast<TemplateTypeParmDecl>(Y);
6432 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
6433 return false;
6434
6435 return hasSameType(TTPX->getDefaultArgument(), TTPY->getDefaultArgument());
6436 }
6437
6438 if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
6439 auto *NTTPY = cast<NonTypeTemplateParmDecl>(Y);
6440 if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
6441 return false;
6442
6443 Expr *DefaultArgumentX = NTTPX->getDefaultArgument()->IgnoreImpCasts();
6444 Expr *DefaultArgumentY = NTTPY->getDefaultArgument()->IgnoreImpCasts();
6445 llvm::FoldingSetNodeID XID, YID;
6446 DefaultArgumentX->Profile(XID, *this, /*Canonical=*/true);
6447 DefaultArgumentY->Profile(YID, *this, /*Canonical=*/true);
6448 return XID == YID;
6449 }
6450
6451 auto *TTPX = cast<TemplateTemplateParmDecl>(X);
6452 auto *TTPY = cast<TemplateTemplateParmDecl>(Y);
6453
6454 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
6455 return false;
6456
6457 const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
6458 const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
6459 return hasSameTemplateName(TAX.getAsTemplate(), TAY.getAsTemplate());
6460}
6461
6463 if (auto *NS = X->getAsNamespace())
6464 return NS;
6465 if (auto *NAS = X->getAsNamespaceAlias())
6466 return NAS->getNamespace();
6467 return nullptr;
6468}
6469
6471 const NestedNameSpecifier *Y) {
6472 if (auto *NSX = getNamespace(X)) {
6473 auto *NSY = getNamespace(Y);
6474 if (!NSY || NSX->getCanonicalDecl() != NSY->getCanonicalDecl())
6475 return false;
6476 } else if (X->getKind() != Y->getKind())
6477 return false;
6478
6479 // FIXME: For namespaces and types, we're permitted to check that the entity
6480 // is named via the same tokens. We should probably do so.
6481 switch (X->getKind()) {
6483 if (X->getAsIdentifier() != Y->getAsIdentifier())
6484 return false;
6485 break;
6488 // We've already checked that we named the same namespace.
6489 break;
6492 if (X->getAsType()->getCanonicalTypeInternal() !=
6494 return false;
6495 break;
6498 return true;
6499 }
6500
6501 // Recurse into earlier portion of NNS, if any.
6502 auto *PX = X->getPrefix();
6503 auto *PY = Y->getPrefix();
6504 if (PX && PY)
6505 return isSameQualifier(PX, PY);
6506 return !PX && !PY;
6507}
6508
6509/// Determine whether the attributes we can overload on are identical for A and
6510/// B. Will ignore any overloadable attrs represented in the type of A and B.
6512 const FunctionDecl *B) {
6513 // Note that pass_object_size attributes are represented in the function's
6514 // ExtParameterInfo, so we don't need to check them here.
6515
6516 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
6517 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
6518 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
6519
6520 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
6521 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
6522 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
6523
6524 // Return false if the number of enable_if attributes is different.
6525 if (!Cand1A || !Cand2A)
6526 return false;
6527
6528 Cand1ID.clear();
6529 Cand2ID.clear();
6530
6531 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
6532 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
6533
6534 // Return false if any of the enable_if expressions of A and B are
6535 // different.
6536 if (Cand1ID != Cand2ID)
6537 return false;
6538 }
6539 return true;
6540}
6541
6542bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
6543 // Caution: this function is called by the AST reader during deserialization,
6544 // so it cannot rely on AST invariants being met. Non-trivial accessors
6545 // should be avoided, along with any traversal of redeclaration chains.
6546
6547 if (X == Y)
6548 return true;
6549
6550 if (X->getDeclName() != Y->getDeclName())
6551 return false;
6552
6553 // Must be in the same context.
6554 //
6555 // Note that we can't use DeclContext::Equals here, because the DeclContexts
6556 // could be two different declarations of the same function. (We will fix the
6557 // semantic DC to refer to the primary definition after merging.)
6558 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
6559 cast<Decl>(Y->getDeclContext()->getRedeclContext())))
6560 return false;
6561
6562 // Two typedefs refer to the same entity if they have the same underlying
6563 // type.
6564 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
6565 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
6566 return hasSameType(TypedefX->getUnderlyingType(),
6567 TypedefY->getUnderlyingType());
6568
6569 // Must have the same kind.
6570 if (X->getKind() != Y->getKind())
6571 return false;
6572
6573 // Objective-C classes and protocols with the same name always match.
6574 if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
6575 return true;
6576
6577 if (isa<ClassTemplateSpecializationDecl>(X)) {
6578 // No need to handle these here: we merge them when adding them to the
6579 // template.
6580 return false;
6581 }
6582
6583 // Compatible tags match.
6584 if (const auto *TagX = dyn_cast<TagDecl>(X)) {
6585 const auto *TagY = cast<TagDecl>(Y);
6586 return (TagX->getTagKind() == TagY->getTagKind()) ||
6587 ((TagX->getTagKind() == TagTypeKind::Struct ||
6588 TagX->getTagKind() == TagTypeKind::Class ||
6589 TagX->getTagKind() == TagTypeKind::Interface) &&
6590 (TagY->getTagKind() == TagTypeKind::Struct ||
6591 TagY->getTagKind() == TagTypeKind::Class ||
6592 TagY->getTagKind() == TagTypeKind::Interface));
6593 }
6594
6595 // Functions with the same type and linkage match.
6596 // FIXME: This needs to cope with merging of prototyped/non-prototyped
6597 // functions, etc.
6598 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
6599 const auto *FuncY = cast<FunctionDecl>(Y);
6600 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
6601 const auto *CtorY = cast<CXXConstructorDecl>(Y);
6602 if (CtorX->getInheritedConstructor() &&
6603 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
6604 CtorY->getInheritedConstructor().getConstructor()))
6605 return false;
6606 }
6607
6608 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
6609 return false;
6610
6611 // Multiversioned functions with different feature strings are represented
6612 // as separate declarations.
6613 if (FuncX->isMultiVersion()) {
6614 const auto *TAX = FuncX->getAttr<TargetAttr>();
6615 const auto *TAY = FuncY->getAttr<TargetAttr>();
6616 assert(TAX && TAY && "Multiversion Function without target attribute");
6617
6618 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
6619 return false;
6620 }
6621
6622 // Per C++20 [temp.over.link]/4, friends in different classes are sometimes
6623 // not the same entity if they are constrained.
6624 if ((FuncX->isMemberLikeConstrainedFriend() ||
6625 FuncY->isMemberLikeConstrainedFriend()) &&
6626 !FuncX->getLexicalDeclContext()->Equals(
6627 FuncY->getLexicalDeclContext())) {
6628 return false;
6629 }
6630
6631 if (!isSameConstraintExpr(FuncX->getTrailingRequiresClause(),
6632 FuncY->getTrailingRequiresClause()))
6633 return false;
6634
6635 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
6636 // Map to the first declaration that we've already merged into this one.
6637 // The TSI of redeclarations might not match (due to calling conventions
6638 // being inherited onto the type but not the TSI), but the TSI type of
6639 // the first declaration of the function should match across modules.
6640 FD = FD->getCanonicalDecl();
6641 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
6642 : FD->getType();
6643 };
6644 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
6645 if (!hasSameType(XT, YT)) {
6646 // We can get functions with different types on the redecl chain in C++17
6647 // if they have differing exception specifications and at least one of
6648 // the excpetion specs is unresolved.
6649 auto *XFPT = XT->getAs<FunctionProtoType>();
6650 auto *YFPT = YT->getAs<FunctionProtoType>();
6651 if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
6652 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
6655 return true;
6656 return false;
6657 }
6658
6659 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
6660 hasSameOverloadableAttrs(FuncX, FuncY);
6661 }
6662
6663 // Variables with the same type and linkage match.
6664 if (const auto *VarX = dyn_cast<VarDecl>(X)) {
6665 const auto *VarY = cast<VarDecl>(Y);
6666 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
6667 // During deserialization, we might compare variables before we load
6668 // their types. Assume the types will end up being the same.
6669 if (VarX->getType().isNull() || VarY->getType().isNull())
6670 return true;
6671
6672 if (hasSameType(VarX->getType(), VarY->getType()))
6673 return true;
6674
6675 // We can get decls with different types on the redecl chain. Eg.
6676 // template <typename T> struct S { static T Var[]; }; // #1
6677 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
6678 // Only? happens when completing an incomplete array type. In this case
6679 // when comparing #1 and #2 we should go through their element type.
6680 const ArrayType *VarXTy = getAsArrayType(VarX->getType());
6681 const ArrayType *VarYTy = getAsArrayType(VarY->getType());
6682 if (!VarXTy || !VarYTy)
6683 return false;
6684 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
6685 return hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
6686 }
6687 return false;
6688 }
6689
6690 // Namespaces with the same name and inlinedness match.
6691 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
6692 const auto *NamespaceY = cast<NamespaceDecl>(Y);
6693 return NamespaceX->isInline() == NamespaceY->isInline();
6694 }
6695
6696 // Identical template names and kinds match if their template parameter lists
6697 // and patterns match.
6698 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
6699 const auto *TemplateY = cast<TemplateDecl>(Y);
6700
6701 // ConceptDecl wouldn't be the same if their constraint expression differs.
6702 if (const auto *ConceptX = dyn_cast<ConceptDecl>(X)) {
6703 const auto *ConceptY = cast<ConceptDecl>(Y);
6704 if (!isSameConstraintExpr(ConceptX->getConstraintExpr(),
6705 ConceptY->getConstraintExpr()))
6706 return false;
6707 }
6708
6709 return isSameEntity(TemplateX->getTemplatedDecl(),
6710 TemplateY->getTemplatedDecl()) &&
6711 isSameTemplateParameterList(TemplateX->getTemplateParameters(),
6712 TemplateY->getTemplateParameters());
6713 }
6714
6715 // Fields with the same name and the same type match.
6716 if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
6717 const auto *FDY = cast<FieldDecl>(Y);
6718 // FIXME: Also check the bitwidth is odr-equivalent, if any.
6719 return hasSameType(FDX->getType(), FDY->getType());
6720 }
6721
6722 // Indirect fields with the same target field match.
6723 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
6724 const auto *IFDY = cast<IndirectFieldDecl>(Y);
6725 return IFDX->getAnonField()->getCanonicalDecl() ==
6726 IFDY->getAnonField()->getCanonicalDecl();
6727 }
6728
6729 // Enumerators with the same name match.
6730 if (isa<EnumConstantDecl>(X))
6731 // FIXME: Also check the value is odr-equivalent.
6732 return true;
6733
6734 // Using shadow declarations with the same target match.
6735 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
6736 const auto *USY = cast<UsingShadowDecl>(Y);
6737 return USX->getTargetDecl() == USY->getTargetDecl();
6738 }
6739
6740 // Using declarations with the same qualifier match. (We already know that
6741 // the name matches.)
6742 if (const auto *UX = dyn_cast<UsingDecl>(X)) {
6743 const auto *UY = cast<UsingDecl>(Y);
6744 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
6745 UX->hasTypename() == UY->hasTypename() &&
6746 UX->isAccessDeclaration() == UY->isAccessDeclaration();
6747 }
6748 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
6749 const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
6750 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
6751 UX->isAccessDeclaration() == UY->isAccessDeclaration();
6752 }
6753 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
6754 return isSameQualifier(
6755 UX->getQualifier(),
6756 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
6757 }
6758
6759 // Using-pack declarations are only created by instantiation, and match if
6760 // they're instantiated from matching UnresolvedUsing...Decls.
6761 if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
6762 return declaresSameEntity(
6763 UX->getInstantiatedFromUsingDecl(),
6764 cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
6765 }
6766
6767 // Namespace alias definitions with the same target match.
6768 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
6769 const auto *NAY = cast<NamespaceAliasDecl>(Y);
6770 return NAX->getNamespace()->Equals(NAY->getNamespace());
6771 }
6772
6773 return false;
6774}
6775
6778 switch (Arg.getKind()) {
6780 return Arg;
6781
6783 return Arg;
6784
6786 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
6788 Arg.getIsDefaulted());
6789 }
6790
6793 /*isNullPtr*/ true, Arg.getIsDefaulted());
6794
6797 Arg.getIsDefaulted());
6798
6800 return TemplateArgument(
6803
6806
6808 return TemplateArgument(*this,
6810 Arg.getAsStructuralValue());
6811
6814 /*isNullPtr*/ false, Arg.getIsDefaulted());
6815
6817 bool AnyNonCanonArgs = false;
6818 auto CanonArgs = ::getCanonicalTemplateArguments(
6819 *this, Arg.pack_elements(), AnyNonCanonArgs);
6820 if (!AnyNonCanonArgs)
6821 return Arg;
6822 return TemplateArgument::CreatePackCopy(const_cast<ASTContext &>(*this),
6823 CanonArgs);
6824 }
6825 }
6826
6827 // Silence GCC warning
6828 llvm_unreachable("Unhandled template argument kind");
6829}
6830
6833 if (!NNS)
6834 return nullptr;
6835
6836 switch (NNS->getKind()) {
6838 // Canonicalize the prefix but keep the identifier the same.
6839 return NestedNameSpecifier::Create(*this,
6841 NNS->getAsIdentifier());
6842
6844 // A namespace is canonical; build a nested-name-specifier with
6845 // this namespace and no prefix.
6846 return NestedNameSpecifier::Create(*this, nullptr,
6848
6850 // A namespace is canonical; build a nested-name-specifier with
6851 // this namespace and no prefix.
6852 return NestedNameSpecifier::Create(*this, nullptr,
6855
6856 // The difference between TypeSpec and TypeSpecWithTemplate is that the
6857 // latter will have the 'template' keyword when printed.
6860 const Type *T = getCanonicalType(NNS->getAsType());
6861
6862 // If we have some kind of dependent-named type (e.g., "typename T::type"),
6863 // break it apart into its prefix and identifier, then reconsititute those
6864 // as the canonical nested-name-specifier. This is required to canonicalize
6865 // a dependent nested-name-specifier involving typedefs of dependent-name
6866 // types, e.g.,
6867 // typedef typename T::type T1;
6868 // typedef typename T1::type T2;
6869 if (const auto *DNT = T->getAs<DependentNameType>())
6871 *this, DNT->getQualifier(),
6872 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
6873 if (const auto *DTST = T->getAs<DependentTemplateSpecializationType>())
6874 return NestedNameSpecifier::Create(*this, DTST->getQualifier(), true,
6875 const_cast<Type *>(T));
6876
6877 // TODO: Set 'Template' parameter to true for other template types.
6878 return NestedNameSpecifier::Create(*this, nullptr, false,
6879 const_cast<Type *>(T));
6880 }
6881
6884 // The global specifier and __super specifer are canonical and unique.
6885 return NNS;
6886 }
6887
6888 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6889}
6890
6892 // Handle the non-qualified case efficiently.
6893 if (!T.hasLocalQualifiers()) {
6894 // Handle the common positive case fast.
6895 if (const auto *AT = dyn_cast<ArrayType>(T))
6896 return AT;
6897 }
6898
6899 // Handle the common negative case fast.
6900 if (!isa<ArrayType>(T.getCanonicalType()))
6901 return nullptr;
6902
6903 // Apply any qualifiers from the array type to the element type. This
6904 // implements C99 6.7.3p8: "If the specification of an array type includes
6905 // any type qualifiers, the element type is so qualified, not the array type."
6906
6907 // If we get here, we either have type qualifiers on the type, or we have
6908 // sugar such as a typedef in the way. If we have type qualifiers on the type
6909 // we must propagate them down into the element type.
6910
6912 Qualifiers qs = split.Quals;
6913
6914 // If we have a simple case, just return now.
6915 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
6916 if (!ATy || qs.empty())
6917 return ATy;
6918
6919 // Otherwise, we have an array and we have qualifiers on it. Push the
6920 // qualifiers into the array element type and return a new array type.
6921 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
6922
6923 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
6924 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
6925 CAT->getSizeExpr(),
6926 CAT->getSizeModifier(),
6927 CAT->getIndexTypeCVRQualifiers()));
6928 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
6929 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
6930 IAT->getSizeModifier(),
6931 IAT->getIndexTypeCVRQualifiers()));
6932
6933 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
6934 return cast<ArrayType>(
6936 DSAT->getSizeExpr(),
6937 DSAT->getSizeModifier(),
6938 DSAT->getIndexTypeCVRQualifiers(),
6939 DSAT->getBracketsRange()));
6940
6941 const auto *VAT = cast<VariableArrayType>(ATy);
6942 return cast<ArrayType>(getVariableArrayType(NewEltTy,
6943 VAT->getSizeExpr(),
6944 VAT->getSizeModifier(),
6945 VAT->getIndexTypeCVRQualifiers(),
6946 VAT->getBracketsRange()));
6947}
6948
6950 if (T->isArrayType() || T->isFunctionType())
6951 return getDecayedType(T);
6952 return T;
6953}
6954
6958 return T.getUnqualifiedType();
6959}
6960
6962 // C++ [except.throw]p3:
6963 // A throw-expression initializes a temporary object, called the exception
6964 // object, the type of which is determined by removing any top-level
6965 // cv-qualifiers from the static type of the operand of throw and adjusting
6966 // the type from "array of T" or "function returning T" to "pointer to T"
6967 // or "pointer to function returning T", [...]
6969 if (T->isArrayType() || T->isFunctionType())
6970 T = getDecayedType(T);
6971 return T.getUnqualifiedType();
6972}
6973
6974/// getArrayDecayedType - Return the properly qualified result of decaying the
6975/// specified array type to a pointer. This operation is non-trivial when
6976/// handling typedefs etc. The canonical type of "T" must be an array type,
6977/// this returns a pointer to a properly qualified element of the array.
6978///
6979/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
6981 // Get the element type with 'getAsArrayType' so that we don't lose any
6982 // typedefs in the element type of the array. This also handles propagation
6983 // of type qualifiers from the array type into the element type if present
6984 // (C99 6.7.3p8).
6985 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
6986 assert(PrettyArrayType && "Not an array type!");
6987
6988 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
6989
6990 // int x[restrict 4] -> int *restrict
6992 PrettyArrayType->getIndexTypeQualifiers());
6993
6994 // int x[_Nullable] -> int * _Nullable
6995 if (auto Nullability = Ty->getNullability()) {
6996 Result = const_cast<ASTContext *>(this)->getAttributedType(
6998 }
6999 return Result;
7000}
7001
7003 return getBaseElementType(array->getElementType());
7004}
7005
7007 Qualifiers qs;
7008 while (true) {
7009 SplitQualType split = type.getSplitDesugaredType();
7010 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
7011 if (!array) break;
7012
7013 type = array->getElementType();
7015 }
7016
7017 return getQualifiedType(type, qs);
7018}
7019
7020/// getConstantArrayElementCount - Returns number of constant array elements.
7021uint64_t
7023 uint64_t ElementCount = 1;
7024 do {
7025 ElementCount *= CA->getSize().getZExtValue();
7026 CA = dyn_cast_or_null<ConstantArrayType>(
7028 } while (CA);
7029 return ElementCount;
7030}
7031
7033 const ArrayInitLoopExpr *AILE) const {
7034 if (!AILE)
7035 return 0;
7036
7037 uint64_t ElementCount = 1;
7038
7039 do {
7040 ElementCount *= AILE->getArraySize().getZExtValue();
7041 AILE = dyn_cast<ArrayInitLoopExpr>(AILE->getSubExpr());
7042 } while (AILE);
7043
7044 return ElementCount;
7045}
7046
7047/// getFloatingRank - Return a relative rank for floating point types.
7048/// This routine will assert if passed a built-in type that isn't a float.
7050 if (const auto *CT = T->getAs<ComplexType>())
7051 return getFloatingRank(CT->getElementType());
7052
7053 switch (T->castAs<BuiltinType>()->getKind()) {
7054 default: llvm_unreachable("getFloatingRank(): not a floating type");
7055 case BuiltinType::Float16: return Float16Rank;
7056 case BuiltinType::Half: return HalfRank;
7057 case BuiltinType::Float: return FloatRank;
7058 case BuiltinType::Double: return DoubleRank;
7059 case BuiltinType::LongDouble: return LongDoubleRank;
7060 case BuiltinType::Float128: return Float128Rank;
7061 case BuiltinType::BFloat16: return BFloat16Rank;
7062 case BuiltinType::Ibm128: return Ibm128Rank;
7063 }
7064}
7065
7066/// getFloatingTypeOrder - Compare the rank of the two specified floating
7067/// point types, ignoring the domain of the type (i.e. 'double' ==
7068/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
7069/// LHS < RHS, return -1.
7071 FloatingRank LHSR = getFloatingRank(LHS);
7072 FloatingRank RHSR = getFloatingRank(RHS);
7073
7074 if (LHSR == RHSR)
7075 return 0;
7076 if (LHSR > RHSR)
7077 return 1;
7078 return -1;
7079}
7080
7083 return 0;
7084 return getFloatingTypeOrder(LHS, RHS);
7085}
7086
7087/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
7088/// routine will assert if passed a built-in type that isn't an integer or enum,
7089/// or if it is not canonicalized.
7090unsigned ASTContext::getIntegerRank(const Type *T) const {
7091 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
7092
7093 // Results in this 'losing' to any type of the same size, but winning if
7094 // larger.
7095 if (const auto *EIT = dyn_cast<BitIntType>(T))
7096 return 0 + (EIT->getNumBits() << 3);
7097
7098 switch (cast<BuiltinType>(T)->getKind()) {
7099 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
7100 case BuiltinType::Bool:
7101 return 1 + (getIntWidth(BoolTy) << 3);
7102 case BuiltinType::Char_S:
7103 case BuiltinType::Char_U:
7104 case BuiltinType::SChar:
7105 case BuiltinType::UChar:
7106 return 2 + (getIntWidth(CharTy) << 3);
7107 case BuiltinType::Short:
7108 case BuiltinType::UShort:
7109 return 3 + (getIntWidth(ShortTy) << 3);
7110 case BuiltinType::Int:
7111 case BuiltinType::UInt:
7112 return 4 + (getIntWidth(IntTy) << 3);
7113 case BuiltinType::Long:
7114 case BuiltinType::ULong:
7115 return 5 + (getIntWidth(LongTy) << 3);
7116 case BuiltinType::LongLong:
7117 case BuiltinType::ULongLong:
7118 return 6 + (getIntWidth(LongLongTy) << 3);
7119 case BuiltinType::Int128:
7120 case BuiltinType::UInt128:
7121 return 7 + (getIntWidth(Int128Ty) << 3);
7122
7123 // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
7124 // their underlying types" [c++20 conv.rank]
7125 case BuiltinType::Char8:
7126 return getIntegerRank(UnsignedCharTy.getTypePtr());
7127 case BuiltinType::Char16:
7128 return getIntegerRank(
7129 getFromTargetType(Target->getChar16Type()).getTypePtr());
7130 case BuiltinType::Char32:
7131 return getIntegerRank(
7132 getFromTargetType(Target->getChar32Type()).getTypePtr());
7133 case BuiltinType::WChar_S:
7134 case BuiltinType::WChar_U:
7135 return getIntegerRank(
7136 getFromTargetType(Target->getWCharType()).getTypePtr());
7137 }
7138}
7139
7140/// Whether this is a promotable bitfield reference according
7141/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
7142///
7143/// \returns the type this bit-field will promote to, or NULL if no
7144/// promotion occurs.
7146 if (E->isTypeDependent() || E->isValueDependent())
7147 return {};
7148
7149 // C++ [conv.prom]p5:
7150 // If the bit-field has an enumerated type, it is treated as any other
7151 // value of that type for promotion purposes.
7153 return {};
7154
7155 // FIXME: We should not do this unless E->refersToBitField() is true. This
7156 // matters in C where getSourceBitField() will find bit-fields for various
7157 // cases where the source expression is not a bit-field designator.
7158
7159 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
7160 if (!Field)
7161 return {};
7162
7163 QualType FT = Field->getType();
7164
7165 uint64_t BitWidth = Field->getBitWidthValue(*this);
7166 uint64_t IntSize = getTypeSize(IntTy);
7167 // C++ [conv.prom]p5:
7168 // A prvalue for an integral bit-field can be converted to a prvalue of type
7169 // int if int can represent all the values of the bit-field; otherwise, it
7170 // can be converted to unsigned int if unsigned int can represent all the
7171 // values of the bit-field. If the bit-field is larger yet, no integral
7172 // promotion applies to it.
7173 // C11 6.3.1.1/2:
7174 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
7175 // If an int can represent all values of the original type (as restricted by
7176 // the width, for a bit-field), the value is converted to an int; otherwise,
7177 // it is converted to an unsigned int.
7178 //
7179 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
7180 // We perform that promotion here to match GCC and C++.
7181 // FIXME: C does not permit promotion of an enum bit-field whose rank is
7182 // greater than that of 'int'. We perform that promotion to match GCC.
7183 if (BitWidth < IntSize)
7184 return IntTy;
7185
7186 if (BitWidth == IntSize)
7187 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
7188
7189 // Bit-fields wider than int are not subject to promotions, and therefore act
7190 // like the base type. GCC has some weird bugs in this area that we
7191 // deliberately do not follow (GCC follows a pre-standard resolution to
7192 // C's DR315 which treats bit-width as being part of the type, and this leaks
7193 // into their semantics in some cases).
7194 return {};
7195}
7196
7197/// getPromotedIntegerType - Returns the type that Promotable will
7198/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
7199/// integer type.
7201 assert(!Promotable.isNull());
7202 assert(isPromotableIntegerType(Promotable));
7203 if (const auto *ET = Promotable->getAs<EnumType>())
7204 return ET->getDecl()->getPromotionType();
7205
7206 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
7207 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
7208 // (3.9.1) can be converted to a prvalue of the first of the following
7209 // types that can represent all the values of its underlying type:
7210 // int, unsigned int, long int, unsigned long int, long long int, or
7211 // unsigned long long int [...]
7212 // FIXME: Is there some better way to compute this?
7213 if (BT->getKind() == BuiltinType::WChar_S ||
7214 BT->getKind() == BuiltinType::WChar_U ||
7215 BT->getKind() == BuiltinType::Char8 ||
7216 BT->getKind() == BuiltinType::Char16 ||
7217 BT->getKind() == BuiltinType::Char32) {
7218 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
7219 uint64_t FromSize = getTypeSize(BT);
7220 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
7222 for (const auto &PT : PromoteTypes) {
7223 uint64_t ToSize = getTypeSize(PT);
7224 if (FromSize < ToSize ||
7225 (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
7226 return PT;
7227 }
7228 llvm_unreachable("char type should fit into long long");
7229 }
7230 }
7231
7232 // At this point, we should have a signed or unsigned integer type.
7233 if (Promotable->isSignedIntegerType())
7234 return IntTy;
7235 uint64_t PromotableSize = getIntWidth(Promotable);
7236 uint64_t IntSize = getIntWidth(IntTy);
7237 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
7238 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
7239}
7240
7241/// Recurses in pointer/array types until it finds an objc retainable
7242/// type and returns its ownership.
7244 while (!T.isNull()) {
7246 return T.getObjCLifetime();
7247 if (T->isArrayType())
7248 T = getBaseElementType(T);
7249 else if (const auto *PT = T->getAs<PointerType>())
7250 T = PT->getPointeeType();
7251 else if (const auto *RT = T->getAs<ReferenceType>())
7252 T = RT->getPointeeType();
7253 else
7254 break;
7255 }
7256
7257 return Qualifiers::OCL_None;
7258}
7259
7260static const Type *getIntegerTypeForEnum(const EnumType *ET) {
7261 // Incomplete enum types are not treated as integer types.
7262 // FIXME: In C++, enum types are never integer types.
7263 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
7264 return ET->getDecl()->getIntegerType().getTypePtr();
7265 return nullptr;
7266}
7267
7268/// getIntegerTypeOrder - Returns the highest ranked integer type:
7269/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
7270/// LHS < RHS, return -1.
7272 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
7273 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
7274
7275 // Unwrap enums to their underlying type.
7276 if (const auto *ET = dyn_cast<EnumType>(LHSC))
7277 LHSC = getIntegerTypeForEnum(ET);
7278 if (const auto *ET = dyn_cast<EnumType>(RHSC))
7279 RHSC = getIntegerTypeForEnum(ET);
7280
7281 if (LHSC == RHSC) return 0;
7282
7283 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
7284 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
7285
7286 unsigned LHSRank = getIntegerRank(LHSC);
7287 unsigned RHSRank = getIntegerRank(RHSC);
7288
7289 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
7290 if (LHSRank == RHSRank) return 0;
7291 return LHSRank > RHSRank ? 1 : -1;
7292 }
7293
7294 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
7295 if (LHSUnsigned) {
7296 // If the unsigned [LHS] type is larger, return it.
7297 if (LHSRank >= RHSRank)
7298 return 1;
7299
7300 // If the signed type can represent all values of the unsigned type, it
7301 // wins. Because we are dealing with 2's complement and types that are
7302 // powers of two larger than each other, this is always safe.
7303 return -1;
7304 }
7305
7306 // If the unsigned [RHS] type is larger, return it.
7307 if (RHSRank >= LHSRank)
7308 return -1;
7309
7310 // If the signed type can represent all values of the unsigned type, it
7311 // wins. Because we are dealing with 2's complement and types that are
7312 // powers of two larger than each other, this is always safe.
7313 return 1;
7314}
7315
7317 if (CFConstantStringTypeDecl)
7318 return CFConstantStringTypeDecl;
7319
7320 assert(!CFConstantStringTagDecl &&
7321 "tag and typedef should be initialized together");
7322 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
7323 CFConstantStringTagDecl->startDefinition();
7324
7325 struct {
7326 QualType Type;
7327 const char *Name;
7328 } Fields[5];
7329 unsigned Count = 0;
7330
7331 /// Objective-C ABI
7332 ///
7333 /// typedef struct __NSConstantString_tag {
7334 /// const int *isa;
7335 /// int flags;
7336 /// const char *str;
7337 /// long length;
7338 /// } __NSConstantString;
7339 ///
7340 /// Swift ABI (4.1, 4.2)
7341 ///
7342 /// typedef struct __NSConstantString_tag {
7343 /// uintptr_t _cfisa;
7344 /// uintptr_t _swift_rc;
7345 /// _Atomic(uint64_t) _cfinfoa;
7346 /// const char *_ptr;
7347 /// uint32_t _length;
7348 /// } __NSConstantString;
7349 ///
7350 /// Swift ABI (5.0)
7351 ///
7352 /// typedef struct __NSConstantString_tag {
7353 /// uintptr_t _cfisa;
7354 /// uintptr_t _swift_rc;
7355 /// _Atomic(uint64_t) _cfinfoa;
7356 /// const char *_ptr;
7357 /// uintptr_t _length;
7358 /// } __NSConstantString;
7359
7360 const auto CFRuntime = getLangOpts().CFRuntime;
7361 if (static_cast<unsigned>(CFRuntime) <
7362 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
7363 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
7364 Fields[Count++] = { IntTy, "flags" };
7365 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
7366 Fields[Count++] = { LongTy, "length" };
7367 } else {
7368 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
7369 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
7370 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
7371 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
7374 Fields[Count++] = { IntTy, "_ptr" };
7375 else
7376 Fields[Count++] = { getUIntPtrType(), "_ptr" };
7377 }
7378
7379 // Create fields
7380 for (unsigned i = 0; i < Count; ++i) {
7381 FieldDecl *Field =
7382 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
7383 SourceLocation(), &Idents.get(Fields[i].Name),
7384 Fields[i].Type, /*TInfo=*/nullptr,
7385 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
7386 Field->setAccess(AS_public);
7387 CFConstantStringTagDecl->addDecl(Field);
7388 }
7389
7390 CFConstantStringTagDecl->completeDefinition();
7391 // This type is designed to be compatible with NSConstantString, but cannot
7392 // use the same name, since NSConstantString is an interface.
7393 auto tagType = getTagDeclType(CFConstantStringTagDecl);
7394 CFConstantStringTypeDecl =
7395 buildImplicitTypedef(tagType, "__NSConstantString");
7396
7397 return CFConstantStringTypeDecl;
7398}
7399
7401 if (!CFConstantStringTagDecl)
7402 getCFConstantStringDecl(); // Build the tag and the typedef.
7403 return CFConstantStringTagDecl;
7404}
7405
7406// getCFConstantStringType - Return the type used for constant CFStrings.
7409}
7410
7412 if (ObjCSuperType.isNull()) {
7413 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
7414 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl);
7415 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
7416 }
7417 return ObjCSuperType;
7418}
7419
7421 const auto *TD = T->castAs<TypedefType>();
7422 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
7423 const auto *TagType =
7424 CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>();
7425 CFConstantStringTagDecl = TagType->getDecl();
7426}
7427
7429 if (BlockDescriptorType)
7430 return getTagDeclType(BlockDescriptorType);
7431
7432 RecordDecl *RD;
7433 // FIXME: Needs the FlagAppleBlock bit.
7434 RD = buildImplicitRecord("__block_descriptor");
7435 RD->startDefinition();
7436
7437 QualType FieldTypes[] = {
7440 };
7441
7442 static const char *const FieldNames[] = {
7443 "reserved",
7444 "Size"
7445 };
7446
7447 for (size_t i = 0; i < 2; ++i) {
7449 *this, RD, SourceLocation(), SourceLocation(),
7450 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
7451 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
7452 Field->setAccess(AS_public);
7453 RD->addDecl(Field);
7454 }
7455
7456 RD->completeDefinition();
7457
7458 BlockDescriptorType = RD;
7459
7460 return getTagDeclType(BlockDescriptorType);
7461}
7462
7464 if (BlockDescriptorExtendedType)
7465 return getTagDeclType(BlockDescriptorExtendedType);
7466
7467 RecordDecl *RD;
7468 // FIXME: Needs the FlagAppleBlock bit.
7469 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
7470 RD->startDefinition();
7471
7472 QualType FieldTypes[] = {
7477 };
7478
7479 static const char *const FieldNames[] = {
7480 "reserved",
7481 "Size",
7482 "CopyFuncPtr",
7483 "DestroyFuncPtr"
7484 };
7485
7486 for (size_t i = 0; i < 4; ++i) {
7488 *this, RD, SourceLocation(), SourceLocation(),
7489 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
7490 /*BitWidth=*/nullptr,
7491 /*Mutable=*/false, ICIS_NoInit);
7492 Field->setAccess(AS_public);
7493 RD->addDecl(Field);
7494 }
7495
7496 RD->completeDefinition();
7497
7498 BlockDescriptorExtendedType = RD;
7499 return getTagDeclType(BlockDescriptorExtendedType);
7500}
7501
7503 const auto *BT = dyn_cast<BuiltinType>(T);
7504
7505 if (!BT) {
7506 if (isa<PipeType>(T))
7507 return OCLTK_Pipe;
7508
7509 return OCLTK_Default;
7510 }
7511
7512 switch (BT->getKind()) {
7513#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7514 case BuiltinType::Id: \
7515 return OCLTK_Image;
7516#include "clang/Basic/OpenCLImageTypes.def"
7517
7518 case BuiltinType::OCLClkEvent:
7519 return OCLTK_ClkEvent;
7520
7521 case BuiltinType::OCLEvent:
7522 return OCLTK_Event;
7523
7524 case BuiltinType::OCLQueue:
7525 return OCLTK_Queue;
7526
7527 case BuiltinType::OCLReserveID:
7528 return OCLTK_ReserveID;
7529
7530 case BuiltinType::OCLSampler:
7531 return OCLTK_Sampler;
7532
7533 default:
7534 return OCLTK_Default;
7535 }
7536}
7537
7539 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
7540}
7541
7542/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
7543/// requires copy/dispose. Note that this must match the logic
7544/// in buildByrefHelpers.
7546 const VarDecl *D) {
7547 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
7548 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
7549 if (!copyExpr && record->hasTrivialDestructor()) return false;
7550
7551 return true;
7552 }
7553
7554 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
7555 // move or destroy.
7557 return true;
7558
7559 if (!Ty->isObjCRetainableType()) return false;
7560
7561 Qualifiers qs = Ty.getQualifiers();
7562
7563 // If we have lifetime, that dominates.
7564 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
7565 switch (lifetime) {
7566 case Qualifiers::OCL_None: llvm_unreachable("impossible");
7567
7568 // These are just bits as far as the runtime is concerned.
7571 return false;
7572
7573 // These cases should have been taken care of when checking the type's
7574 // non-triviality.
7577 llvm_unreachable("impossible");
7578 }
7579 llvm_unreachable("fell out of lifetime switch!");
7580 }
7581 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
7583}
7584
7586 Qualifiers::ObjCLifetime &LifeTime,
7587 bool &HasByrefExtendedLayout) const {
7588 if (!getLangOpts().ObjC ||
7589 getLangOpts().getGC() != LangOptions::NonGC)
7590 return false;
7591
7592 HasByrefExtendedLayout = false;
7593 if (Ty->isRecordType()) {
7594 HasByrefExtendedLayout = true;
7595 LifeTime = Qualifiers::OCL_None;
7596 } else if ((LifeTime = Ty.getObjCLifetime())) {
7597 // Honor the ARC qualifiers.
7598 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
7599 // The MRR rule.
7601 } else {
7602 LifeTime = Qualifiers::OCL_None;
7603 }
7604 return true;
7605}
7606
7608 assert(Target && "Expected target to be initialized");
7609 const llvm::Triple &T = Target->getTriple();
7610 // Windows is LLP64 rather than LP64
7611 if (T.isOSWindows() && T.isArch64Bit())
7612 return UnsignedLongLongTy;
7613 return UnsignedLongTy;
7614}
7615
7617 assert(Target && "Expected target to be initialized");
7618 const llvm::Triple &T = Target->getTriple();
7619 // Windows is LLP64 rather than LP64
7620 if (T.isOSWindows() && T.isArch64Bit())
7621 return LongLongTy;
7622 return LongTy;
7623}
7624
7626 if (!ObjCInstanceTypeDecl)
7627 ObjCInstanceTypeDecl =
7628 buildImplicitTypedef(getObjCIdType(), "instancetype");
7629 return ObjCInstanceTypeDecl;
7630}
7631
7632// This returns true if a type has been typedefed to BOOL:
7633// typedef <type> BOOL;
7635 if (const auto *TT = dyn_cast<TypedefType>(T))
7636 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
7637 return II->isStr("BOOL");
7638
7639 return false;
7640}
7641
7642/// getObjCEncodingTypeSize returns size of type for objective-c encoding
7643/// purpose.
7645 if (!type->isIncompleteArrayType() && type->isIncompleteType())
7646 return CharUnits::Zero();
7647
7649
7650 // Make all integer and enum types at least as large as an int
7651 if (sz.isPositive() && type->isIntegralOrEnumerationType())
7652 sz = std::max(sz, getTypeSizeInChars(IntTy));
7653 // Treat arrays as pointers, since that's how they're passed in.
7654 else if (type->isArrayType())
7656 return sz;
7657}
7658
7660 return getTargetInfo().getCXXABI().isMicrosoft() &&
7661 VD->isStaticDataMember() &&
7663 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
7664}
7665
7668 if (!VD->isInline())
7670
7671 // In almost all cases, it's a weak definition.
7672 auto *First = VD->getFirstDecl();
7673 if (First->isInlineSpecified() || !First->isStaticDataMember())
7675
7676 // If there's a file-context declaration in this translation unit, it's a
7677 // non-discardable definition.
7678 for (auto *D : VD->redecls())
7679 if (D->getLexicalDeclContext()->isFileContext() &&
7680 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
7682
7683 // If we've not seen one yet, we don't know.
7685}
7686
7687static std::string charUnitsToString(const CharUnits &CU) {
7688 return llvm::itostr(CU.getQuantity());
7689}
7690
7691/// getObjCEncodingForBlock - Return the encoded type for this block
7692/// declaration.
7694 std::string S;
7695
7696 const BlockDecl *Decl = Expr->getBlockDecl();
7697 QualType BlockTy =
7698 Expr->getType()->castAs<BlockPointerType>()->getPointeeType();
7699 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
7700 // Encode result type.
7701 if (getLangOpts().EncodeExtendedBlockSig)
7703 true /*Extended*/);
7704 else
7705 getObjCEncodingForType(BlockReturnTy, S);
7706 // Compute size of all parameters.
7707 // Start with computing size of a pointer in number of bytes.
7708 // FIXME: There might(should) be a better way of doing this computation!
7710 CharUnits ParmOffset = PtrSize;
7711 for (auto *PI : Decl->parameters()) {
7712 QualType PType = PI->getType();
7714 if (sz.isZero())
7715 continue;
7716 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
7717 ParmOffset += sz;
7718 }
7719 // Size of the argument frame
7720 S += charUnitsToString(ParmOffset);
7721 // Block pointer and offset.
7722 S += "@?0";
7723
7724 // Argument types.
7725 ParmOffset = PtrSize;
7726 for (auto *PVDecl : Decl->parameters()) {
7727 QualType PType = PVDecl->getOriginalType();
7728 if (const auto *AT =
7729 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
7730 // Use array's original type only if it has known number of
7731 // elements.
7732 if (!isa<ConstantArrayType>(AT))
7733 PType = PVDecl->getType();
7734 } else if (PType->isFunctionType())
7735 PType = PVDecl->getType();
7736 if (getLangOpts().EncodeExtendedBlockSig)
7738 S, true /*Extended*/);
7739 else
7740 getObjCEncodingForType(PType, S);
7741 S += charUnitsToString(ParmOffset);
7742 ParmOffset += getObjCEncodingTypeSize(PType);
7743 }
7744
7745 return S;
7746}
7747
7748std::string
7750 std::string S;
7751 // Encode result type.
7752 getObjCEncodingForType(Decl->getReturnType(), S);
7753 CharUnits ParmOffset;
7754 // Compute size of all parameters.
7755 for (auto *PI : Decl->parameters()) {
7756 QualType PType = PI->getType();
7758 if (sz.isZero())
7759 continue;
7760
7761 assert(sz.isPositive() &&
7762 "getObjCEncodingForFunctionDecl - Incomplete param type");
7763 ParmOffset += sz;
7764 }
7765 S += charUnitsToString(ParmOffset);
7766 ParmOffset = CharUnits::Zero();
7767
7768 // Argument types.
7769 for (auto *PVDecl : Decl->parameters()) {
7770 QualType PType = PVDecl->getOriginalType();
7771 if (const auto *AT =
7772 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
7773 // Use array's original type only if it has known number of
7774 // elements.
7775 if (!isa<ConstantArrayType>(AT))
7776 PType = PVDecl->getType();
7777 } else if (PType->isFunctionType())
7778 PType = PVDecl->getType();
7779 getObjCEncodingForType(PType, S);
7780 S += charUnitsToString(ParmOffset);
7781 ParmOffset += getObjCEncodingTypeSize(PType);
7782 }
7783
7784 return S;
7785}
7786
7787/// getObjCEncodingForMethodParameter - Return the encoded type for a single
7788/// method parameter or return type. If Extended, include class names and
7789/// block object types.
7791 QualType T, std::string& S,
7792 bool Extended) const {
7793 // Encode type qualifier, 'in', 'inout', etc. for the parameter.
7795 // Encode parameter type.
7796 ObjCEncOptions Options = ObjCEncOptions()
7797 .setExpandPointedToStructures()
7798 .setExpandStructures()
7799 .setIsOutermostType();
7800 if (Extended)
7801 Options.setEncodeBlockParameters().setEncodeClassNames();
7802 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
7803}
7804
7805/// getObjCEncodingForMethodDecl - Return the encoded type for this method
7806/// declaration.
7808 bool Extended) const {
7809 // FIXME: This is not very efficient.
7810 // Encode return type.
7811 std::string S;
7812 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
7813 Decl->getReturnType(), S, Extended);
7814 // Compute size of all parameters.
7815 // Start with computing size of a pointer in number of bytes.
7816 // FIXME: There might(should) be a better way of doing this computation!
7818 // The first two arguments (self and _cmd) are pointers; account for
7819 // their size.
7820 CharUnits ParmOffset = 2 * PtrSize;
7821 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
7822 E = Decl->sel_param_end(); PI != E; ++PI) {
7823 QualType PType = (*PI)->getType();
7825 if (sz.isZero())
7826 continue;
7827
7828 assert(sz.isPositive() &&
7829 "getObjCEncodingForMethodDecl - Incomplete param type");
7830 ParmOffset += sz;
7831 }
7832 S += charUnitsToString(ParmOffset);
7833 S += "@0:";
7834 S += charUnitsToString(PtrSize);
7835
7836 // Argument types.
7837 ParmOffset = 2 * PtrSize;
7838 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
7839 E = Decl->sel_param_end(); PI != E; ++PI) {
7840 const ParmVarDecl *PVDecl = *PI;
7841 QualType PType = PVDecl->getOriginalType();
7842 if (const auto *AT =
7843 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
7844 // Use array's original type only if it has known number of
7845 // elements.
7846 if (!isa<ConstantArrayType>(AT))
7847 PType = PVDecl->getType();
7848 } else if (PType->isFunctionType())
7849 PType = PVDecl->getType();
7851 PType, S, Extended);
7852 S += charUnitsToString(ParmOffset);
7853 ParmOffset += getObjCEncodingTypeSize(PType);
7854 }
7855
7856 return S;
7857}
7858
7861 const ObjCPropertyDecl *PD,
7862 const Decl *Container) const {
7863 if (!Container)
7864 return nullptr;
7865 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
7866 for (auto *PID : CID->property_impls())
7867 if (PID->getPropertyDecl() == PD)
7868 return PID;
7869 } else {
7870 const auto *OID = cast<ObjCImplementationDecl>(Container);
7871 for (auto *PID : OID->property_impls())
7872 if (PID->getPropertyDecl() == PD)
7873 return PID;
7874 }
7875 return nullptr;
7876}
7877
7878/// getObjCEncodingForPropertyDecl - Return the encoded type for this
7879/// property declaration. If non-NULL, Container must be either an
7880/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
7881/// NULL when getting encodings for protocol properties.
7882/// Property attributes are stored as a comma-delimited C string. The simple
7883/// attributes readonly and bycopy are encoded as single characters. The
7884/// parametrized attributes, getter=name, setter=name, and ivar=name, are
7885/// encoded as single characters, followed by an identifier. Property types
7886/// are also encoded as a parametrized attribute. The characters used to encode
7887/// these attributes are defined by the following enumeration:
7888/// @code
7889/// enum PropertyAttributes {
7890/// kPropertyReadOnly = 'R', // property is read-only.
7891/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
7892/// kPropertyByref = '&', // property is a reference to the value last assigned
7893/// kPropertyDynamic = 'D', // property is dynamic
7894/// kPropertyGetter = 'G', // followed by getter selector name
7895/// kPropertySetter = 'S', // followed by setter selector name
7896/// kPropertyInstanceVariable = 'V' // followed by instance variable name
7897/// kPropertyType = 'T' // followed by old-style type encoding.
7898/// kPropertyWeak = 'W' // 'weak' property
7899/// kPropertyStrong = 'P' // property GC'able
7900/// kPropertyNonAtomic = 'N' // property non-atomic
7901/// kPropertyOptional = '?' // property optional
7902/// };
7903/// @endcode
7904std::string
7906 const Decl *Container) const {
7907 // Collect information from the property implementation decl(s).
7908 bool Dynamic = false;
7909 ObjCPropertyImplDecl *SynthesizePID = nullptr;
7910
7911 if (ObjCPropertyImplDecl *PropertyImpDecl =
7913 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7914 Dynamic = true;
7915 else
7916 SynthesizePID = PropertyImpDecl;
7917 }
7918
7919 // FIXME: This is not very efficient.
7920 std::string S = "T";
7921
7922 // Encode result type.
7923 // GCC has some special rules regarding encoding of properties which
7924 // closely resembles encoding of ivars.
7926
7927 if (PD->isOptional())
7928 S += ",?";
7929
7930 if (PD->isReadOnly()) {
7931 S += ",R";
7933 S += ",C";
7935 S += ",&";
7937 S += ",W";
7938 } else {
7939 switch (PD->getSetterKind()) {
7940 case ObjCPropertyDecl::Assign: break;
7941 case ObjCPropertyDecl::Copy: S += ",C"; break;
7942 case ObjCPropertyDecl::Retain: S += ",&"; break;
7943 case ObjCPropertyDecl::Weak: S += ",W"; break;
7944 }
7945 }
7946
7947 // It really isn't clear at all what this means, since properties
7948 // are "dynamic by default".
7949 if (Dynamic)
7950 S += ",D";
7951
7953 S += ",N";
7954
7956 S += ",G";
7957 S += PD->getGetterName().getAsString();
7958 }
7959
7961 S += ",S";
7962 S += PD->getSetterName().getAsString();
7963 }
7964
7965 if (SynthesizePID) {
7966 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
7967 S += ",V";
7968 S += OID->getNameAsString();
7969 }
7970
7971 // FIXME: OBJCGC: weak & strong
7972 return S;
7973}
7974
7975/// getLegacyIntegralTypeEncoding -
7976/// Another legacy compatibility encoding: 32-bit longs are encoded as
7977/// 'l' or 'L' , but not always. For typedefs, we need to use
7978/// 'i' or 'I' instead if encoding a struct field, or a pointer!
7980 if (PointeeTy->getAs<TypedefType>()) {
7981 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
7982 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
7983 PointeeTy = UnsignedIntTy;
7984 else
7985 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
7986 PointeeTy = IntTy;
7987 }
7988 }
7989}
7990
7992 const FieldDecl *Field,
7993 QualType *NotEncodedT) const {
7994 // We follow the behavior of gcc, expanding structures which are
7995 // directly pointed to, and expanding embedded structures. Note that
7996 // these rules are sufficient to prevent recursive encoding of the
7997 // same type.
7998 getObjCEncodingForTypeImpl(T, S,
7999 ObjCEncOptions()
8000 .setExpandPointedToStructures()
8001 .setExpandStructures()
8002 .setIsOutermostType(),
8003 Field, NotEncodedT);
8004}
8005
8007 std::string& S) const {
8008 // Encode result type.
8009 // GCC has some special rules regarding encoding of properties which
8010 // closely resembles encoding of ivars.
8011 getObjCEncodingForTypeImpl(T, S,
8012 ObjCEncOptions()
8013 .setExpandPointedToStructures()
8014 .setExpandStructures()
8015 .setIsOutermostType()
8016 .setEncodingProperty(),
8017 /*Field=*/nullptr);
8018}
8019
8021 const BuiltinType *BT) {
8022 BuiltinType::Kind kind = BT->getKind();
8023 switch (kind) {
8024 case BuiltinType::Void: return 'v';
8025 case BuiltinType::Bool: return 'B';
8026 case BuiltinType::Char8:
8027 case BuiltinType::Char_U:
8028 case BuiltinType::UChar: return 'C';
8029 case BuiltinType::Char16:
8030 case BuiltinType::UShort: return 'S';
8031 case BuiltinType::Char32:
8032 case BuiltinType::UInt: return 'I';
8033 case BuiltinType::ULong:
8034 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
8035 case BuiltinType::UInt128: return 'T';
8036 case BuiltinType::ULongLong: return 'Q';
8037 case BuiltinType::Char_S:
8038 case BuiltinType::SChar: return 'c';
8039 case BuiltinType::Short: return 's';
8040 case BuiltinType::WChar_S:
8041 case BuiltinType::WChar_U:
8042 case BuiltinType::Int: return 'i';
8043 case BuiltinType::Long:
8044 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
8045 case BuiltinType::LongLong: return 'q';
8046 case BuiltinType::Int128: return 't';
8047 case BuiltinType::Float: return 'f';
8048 case BuiltinType::Double: return 'd';
8049 case BuiltinType::LongDouble: return 'D';
8050 case BuiltinType::NullPtr: return '*'; // like char*
8051
8052 case BuiltinType::BFloat16:
8053 case BuiltinType::Float16:
8054 case BuiltinType::Float128:
8055 case BuiltinType::Ibm128:
8056 case BuiltinType::Half:
8057 case BuiltinType::ShortAccum:
8058 case BuiltinType::Accum:
8059 case BuiltinType::LongAccum:
8060 case BuiltinType::UShortAccum:
8061 case BuiltinType::UAccum:
8062 case BuiltinType::ULongAccum:
8063 case BuiltinType::ShortFract:
8064 case BuiltinType::Fract:
8065 case BuiltinType::LongFract:
8066 case BuiltinType::UShortFract:
8067 case BuiltinType::UFract:
8068 case BuiltinType::ULongFract:
8069 case BuiltinType::SatShortAccum:
8070 case BuiltinType::SatAccum:
8071 case BuiltinType::SatLongAccum:
8072 case BuiltinType::SatUShortAccum:
8073 case BuiltinType::SatUAccum:
8074 case BuiltinType::SatULongAccum:
8075 case BuiltinType::SatShortFract:
8076 case BuiltinType::SatFract:
8077 case BuiltinType::SatLongFract:
8078 case BuiltinType::SatUShortFract:
8079 case BuiltinType::SatUFract:
8080 case BuiltinType::SatULongFract:
8081 // FIXME: potentially need @encodes for these!
8082 return ' ';
8083
8084#define SVE_TYPE(Name, Id, SingletonId) \
8085 case BuiltinType::Id:
8086#include "clang/Basic/AArch64SVEACLETypes.def"
8087#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
8088#include "clang/Basic/RISCVVTypes.def"
8089#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
8090#include "clang/Basic/WebAssemblyReferenceTypes.def"
8091 {
8092 DiagnosticsEngine &Diags = C->getDiagnostics();
8093 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
8094 "cannot yet @encode type %0");
8095 Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
8096 return ' ';
8097 }
8098
8099 case BuiltinType::ObjCId:
8100 case BuiltinType::ObjCClass:
8101 case BuiltinType::ObjCSel:
8102 llvm_unreachable("@encoding ObjC primitive type");
8103
8104 // OpenCL and placeholder types don't need @encodings.
8105#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8106 case BuiltinType::Id:
8107#include "clang/Basic/OpenCLImageTypes.def"
8108#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
8109 case BuiltinType::Id:
8110#include "clang/Basic/OpenCLExtensionTypes.def"
8111 case BuiltinType::OCLEvent:
8112 case BuiltinType::OCLClkEvent:
8113 case BuiltinType::OCLQueue:
8114 case BuiltinType::OCLReserveID:
8115 case BuiltinType::OCLSampler:
8116 case BuiltinType::Dependent:
8117#define PPC_VECTOR_TYPE(Name, Id, Size) \
8118 case BuiltinType::Id:
8119#include "clang/Basic/PPCTypes.def"
8120#define BUILTIN_TYPE(KIND, ID)
8121#define PLACEHOLDER_TYPE(KIND, ID) \
8122 case BuiltinType::KIND:
8123#include "clang/AST/BuiltinTypes.def"
8124 llvm_unreachable("invalid builtin type for @encode");
8125 }
8126 llvm_unreachable("invalid BuiltinType::Kind value");
8127}
8128
8129static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
8130 EnumDecl *Enum = ET->getDecl();
8131
8132 // The encoding of an non-fixed enum type is always 'i', regardless of size.
8133 if (!Enum->isFixed())
8134 return 'i';
8135
8136 // The encoding of a fixed enum type matches its fixed underlying type.
8137 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
8139}
8140
8141static void EncodeBitField(const ASTContext *Ctx, std::string& S,
8142 QualType T, const FieldDecl *FD) {
8143 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
8144 S += 'b';
8145 // The NeXT runtime encodes bit fields as b followed by the number of bits.
8146 // The GNU runtime requires more information; bitfields are encoded as b,
8147 // then the offset (in bits) of the first element, then the type of the
8148 // bitfield, then the size in bits. For example, in this structure:
8149 //
8150 // struct
8151 // {
8152 // int integer;
8153 // int flags:2;
8154 // };
8155 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
8156 // runtime, but b32i2 for the GNU runtime. The reason for this extra
8157 // information is not especially sensible, but we're stuck with it for
8158 // compatibility with GCC, although providing it breaks anything that
8159 // actually uses runtime introspection and wants to work on both runtimes...
8160 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
8161 uint64_t Offset;
8162
8163 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
8164 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
8165 IVD);
8166 } else {
8167 const RecordDecl *RD = FD->getParent();
8168 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
8169 Offset = RL.getFieldOffset(FD->getFieldIndex());
8170 }
8171
8172 S += llvm::utostr(Offset);
8173
8174 if (const auto *ET = T->getAs<EnumType>())
8175 S += ObjCEncodingForEnumType(Ctx, ET);
8176 else {
8177 const auto *BT = T->castAs<BuiltinType>();
8178 S += getObjCEncodingForPrimitiveType(Ctx, BT);
8179 }
8180 }
8181 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
8182}
8183
8184// Helper function for determining whether the encoded type string would include
8185// a template specialization type.
8187 bool VisitBasesAndFields) {
8188 T = T->getBaseElementTypeUnsafe();
8189
8190 if (auto *PT = T->getAs<PointerType>())
8192 PT->getPointeeType().getTypePtr(), false);
8193
8194 auto *CXXRD = T->getAsCXXRecordDecl();
8195
8196 if (!CXXRD)
8197 return false;
8198
8199 if (isa<ClassTemplateSpecializationDecl>(CXXRD))
8200 return true;
8201
8202 if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
8203 return false;
8204
8205 for (const auto &B : CXXRD->bases())
8206 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
8207 true))
8208 return true;
8209
8210 for (auto *FD : CXXRD->fields())
8211 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
8212 true))
8213 return true;
8214
8215 return false;
8216}
8217
8218// FIXME: Use SmallString for accumulating string.
8219void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
8220 const ObjCEncOptions Options,
8221 const FieldDecl *FD,
8222 QualType *NotEncodedT) const {
8224 switch (CT->getTypeClass()) {
8225 case Type::Builtin:
8226 case Type::Enum:
8227 if (FD && FD->isBitField())
8228 return EncodeBitField(this, S, T, FD);
8229 if (const auto *BT = dyn_cast<BuiltinType>(CT))
8230 S += getObjCEncodingForPrimitiveType(this, BT);
8231 else
8232 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
8233 return;
8234
8235 case Type::Complex:
8236 S += 'j';
8237 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
8238 ObjCEncOptions(),
8239 /*Field=*/nullptr);
8240 return;
8241
8242 case Type::Atomic:
8243 S += 'A';
8244 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
8245 ObjCEncOptions(),
8246 /*Field=*/nullptr);
8247 return;
8248
8249 // encoding for pointer or reference types.
8250 case Type::Pointer:
8251 case Type::LValueReference:
8252 case Type::RValueReference: {
8253 QualType PointeeTy;
8254 if (isa<PointerType>(CT)) {
8255 const auto *PT = T->castAs<PointerType>();
8256 if (PT->isObjCSelType()) {
8257 S += ':';
8258 return;
8259 }
8260 PointeeTy = PT->getPointeeType();
8261 } else {
8262 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
8263 }
8264
8265 bool isReadOnly = false;
8266 // For historical/compatibility reasons, the read-only qualifier of the
8267 // pointee gets emitted _before_ the '^'. The read-only qualifier of
8268 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
8269 // Also, do not emit the 'r' for anything but the outermost type!
8270 if (T->getAs<TypedefType>()) {
8271 if (Options.IsOutermostType() && T.isConstQualified()) {
8272 isReadOnly = true;
8273 S += 'r';
8274 }
8275 } else if (Options.IsOutermostType()) {
8276 QualType P = PointeeTy;
8277 while (auto PT = P->getAs<PointerType>())
8278 P = PT->getPointeeType();
8279 if (P.isConstQualified()) {
8280 isReadOnly = true;
8281 S += 'r';
8282 }
8283 }
8284 if (isReadOnly) {
8285 // Another legacy compatibility encoding. Some ObjC qualifier and type
8286 // combinations need to be rearranged.
8287 // Rewrite "in const" from "nr" to "rn"
8288 if (StringRef(S).ends_with("nr"))
8289 S.replace(S.end()-2, S.end(), "rn");
8290 }
8291
8292 if (PointeeTy->isCharType()) {
8293 // char pointer types should be encoded as '*' unless it is a
8294 // type that has been typedef'd to 'BOOL'.
8295 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
8296 S += '*';
8297 return;
8298 }
8299 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
8300 // GCC binary compat: Need to convert "struct objc_class *" to "#".
8301 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
8302 S += '#';
8303 return;
8304 }
8305 // GCC binary compat: Need to convert "struct objc_object *" to "@".
8306 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
8307 S += '@';
8308 return;
8309 }
8310 // If the encoded string for the class includes template names, just emit
8311 // "^v" for pointers to the class.
8312 if (getLangOpts().CPlusPlus &&
8313 (!getLangOpts().EncodeCXXClassTemplateSpec &&
8315 RTy, Options.ExpandPointedToStructures()))) {
8316 S += "^v";
8317 return;
8318 }
8319 // fall through...
8320 }
8321 S += '^';
8323
8324 ObjCEncOptions NewOptions;
8325 if (Options.ExpandPointedToStructures())
8326 NewOptions.setExpandStructures();
8327 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
8328 /*Field=*/nullptr, NotEncodedT);
8329 return;
8330 }
8331
8332 case Type::ConstantArray:
8333 case Type::IncompleteArray:
8334 case Type::VariableArray: {
8335 const auto *AT = cast<ArrayType>(CT);
8336
8337 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
8338 // Incomplete arrays are encoded as a pointer to the array element.
8339 S += '^';
8340
8341 getObjCEncodingForTypeImpl(
8342 AT->getElementType(), S,
8343 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
8344 } else {
8345 S += '[';
8346
8347 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
8348 S += llvm::utostr(CAT->getSize().getZExtValue());
8349 else {
8350 //Variable length arrays are encoded as a regular array with 0 elements.
8351 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
8352 "Unknown array type!");
8353 S += '0';
8354 }
8355
8356 getObjCEncodingForTypeImpl(
8357 AT->getElementType(), S,
8358 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
8359 NotEncodedT);
8360 S += ']';
8361 }
8362 return;
8363 }
8364
8365 case Type::FunctionNoProto:
8366 case Type::FunctionProto:
8367 S += '?';
8368 return;
8369
8370 case Type::Record: {
8371 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
8372 S += RDecl->isUnion() ? '(' : '{';
8373 // Anonymous structures print as '?'
8374 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
8375 S += II->getName();
8376 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
8377 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
8378 llvm::raw_string_ostream OS(S);
8379 printTemplateArgumentList(OS, TemplateArgs.asArray(),
8381 }
8382 } else {
8383 S += '?';
8384 }
8385 if (Options.ExpandStructures()) {
8386 S += '=';
8387 if (!RDecl->isUnion()) {
8388 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
8389 } else {
8390 for (const auto *Field : RDecl->fields()) {
8391 if (FD) {
8392 S += '"';
8393 S += Field->getNameAsString();
8394 S += '"';
8395 }
8396
8397 // Special case bit-fields.
8398 if (Field->isBitField()) {
8399 getObjCEncodingForTypeImpl(Field->getType(), S,
8400 ObjCEncOptions().setExpandStructures(),
8401 Field);
8402 } else {
8403 QualType qt = Field->getType();
8405 getObjCEncodingForTypeImpl(
8406 qt, S,
8407 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
8408 NotEncodedT);
8409 }
8410 }
8411 }
8412 }
8413 S += RDecl->isUnion() ? ')' : '}';
8414 return;
8415 }
8416
8417 case Type::BlockPointer: {
8418 const auto *BT = T->castAs<BlockPointerType>();
8419 S += "@?"; // Unlike a pointer-to-function, which is "^?".
8420 if (Options.EncodeBlockParameters()) {
8421 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
8422
8423 S += '<';
8424 // Block return type
8425 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
8426 Options.forComponentType(), FD, NotEncodedT);
8427 // Block self
8428 S += "@?";
8429 // Block parameters
8430 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
8431 for (const auto &I : FPT->param_types())
8432 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
8433 NotEncodedT);
8434 }
8435 S += '>';
8436 }
8437 return;
8438 }
8439
8440 case Type::ObjCObject: {
8441 // hack to match legacy encoding of *id and *Class
8443 if (Ty->isObjCIdType()) {
8444 S += "{objc_object=}";
8445 return;
8446 }
8447 else if (Ty->isObjCClassType()) {
8448 S += "{objc_class=}";
8449 return;
8450 }
8451 // TODO: Double check to make sure this intentionally falls through.
8452 [[fallthrough]];
8453 }
8454
8455 case Type::ObjCInterface: {
8456 // Ignore protocol qualifiers when mangling at this level.
8457 // @encode(class_name)
8458 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
8459 S += '{';
8460 S += OI->getObjCRuntimeNameAsString();
8461 if (Options.ExpandStructures()) {
8462 S += '=';
8464 DeepCollectObjCIvars(OI, true, Ivars);
8465 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
8466 const FieldDecl *Field = Ivars[i];
8467 if (Field->isBitField())
8468 getObjCEncodingForTypeImpl(Field->getType(), S,
8469 ObjCEncOptions().setExpandStructures(),
8470 Field);
8471 else
8472 getObjCEncodingForTypeImpl(Field->getType(), S,
8473 ObjCEncOptions().setExpandStructures(), FD,
8474 NotEncodedT);
8475 }
8476 }
8477 S += '}';
8478 return;
8479 }
8480
8481 case Type::ObjCObjectPointer: {
8482 const auto *OPT = T->castAs<ObjCObjectPointerType>();
8483 if (OPT->isObjCIdType()) {
8484 S += '@';
8485 return;
8486 }
8487
8488 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
8489 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
8490 // Since this is a binary compatibility issue, need to consult with
8491 // runtime folks. Fortunately, this is a *very* obscure construct.
8492 S += '#';
8493 return;
8494 }
8495
8496 if (OPT->isObjCQualifiedIdType()) {
8497 getObjCEncodingForTypeImpl(
8498 getObjCIdType(), S,
8499 Options.keepingOnly(ObjCEncOptions()
8500 .setExpandPointedToStructures()
8501 .setExpandStructures()),
8502 FD);
8503 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
8504 // Note that we do extended encoding of protocol qualifier list
8505 // Only when doing ivar or property encoding.
8506 S += '"';
8507 for (const auto *I : OPT->quals()) {
8508 S += '<';
8509 S += I->getObjCRuntimeNameAsString();
8510 S += '>';
8511 }
8512 S += '"';
8513 }
8514 return;
8515 }
8516
8517 S += '@';
8518 if (OPT->getInterfaceDecl() &&
8519 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
8520 S += '"';
8521 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
8522 for (const auto *I : OPT->quals()) {
8523 S += '<';
8524 S += I->getObjCRuntimeNameAsString();
8525 S += '>';
8526 }
8527 S += '"';
8528 }
8529 return;
8530 }
8531
8532 // gcc just blithely ignores member pointers.
8533 // FIXME: we should do better than that. 'M' is available.
8534 case Type::MemberPointer:
8535 // This matches gcc's encoding, even though technically it is insufficient.
8536 //FIXME. We should do a better job than gcc.
8537 case Type::Vector:
8538 case Type::ExtVector:
8539 // Until we have a coherent encoding of these three types, issue warning.
8540 if (NotEncodedT)
8541 *NotEncodedT = T;
8542 return;
8543
8544 case Type::ConstantMatrix:
8545 if (NotEncodedT)
8546 *NotEncodedT = T;
8547 return;
8548
8549 case Type::BitInt:
8550 if (NotEncodedT)
8551 *NotEncodedT = T;
8552 return;
8553
8554 // We could see an undeduced auto type here during error recovery.
8555 // Just ignore it.
8556 case Type::Auto:
8557 case Type::DeducedTemplateSpecialization:
8558 return;
8559
8560 case Type::Pipe:
8561#define ABSTRACT_TYPE(KIND, BASE)
8562#define TYPE(KIND, BASE)
8563#define DEPENDENT_TYPE(KIND, BASE) \
8564 case Type::KIND:
8565#define NON_CANONICAL_TYPE(KIND, BASE) \
8566 case Type::KIND:
8567#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
8568 case Type::KIND:
8569#include "clang/AST/TypeNodes.inc"
8570 llvm_unreachable("@encode for dependent type!");
8571 }
8572 llvm_unreachable("bad type kind!");
8573}
8574
8575void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
8576 std::string &S,
8577 const FieldDecl *FD,
8578 bool includeVBases,
8579 QualType *NotEncodedT) const {
8580 assert(RDecl && "Expected non-null RecordDecl");
8581 assert(!RDecl->isUnion() && "Should not be called for unions");
8582 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
8583 return;
8584
8585 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
8586 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
8587 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
8588
8589 if (CXXRec) {
8590 for (const auto &BI : CXXRec->bases()) {
8591 if (!BI.isVirtual()) {
8592 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
8593 if (base->isEmpty())
8594 continue;
8595 uint64_t offs = toBits(layout.getBaseClassOffset(base));
8596 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
8597 std::make_pair(offs, base));
8598 }
8599 }
8600 }
8601
8602 for (FieldDecl *Field : RDecl->fields()) {
8603 if (!Field->isZeroLengthBitField(*this) && Field->isZeroSize(*this))
8604 continue;
8605 uint64_t offs = layout.getFieldOffset(Field->getFieldIndex());
8606 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
8607 std::make_pair(offs, Field));
8608 }
8609
8610 if (CXXRec && includeVBases) {
8611 for (const auto &BI : CXXRec->vbases()) {
8612 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
8613 if (base->isEmpty())
8614 continue;
8615 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
8616 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
8617 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
8618 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
8619 std::make_pair(offs, base));
8620 }
8621 }
8622
8623 CharUnits size;
8624 if (CXXRec) {
8625 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
8626 } else {
8627 size = layout.getSize();
8628 }
8629
8630#ifndef NDEBUG
8631 uint64_t CurOffs = 0;
8632#endif
8633 std::multimap<uint64_t, NamedDecl *>::iterator
8634 CurLayObj = FieldOrBaseOffsets.begin();
8635
8636 if (CXXRec && CXXRec->isDynamicClass() &&
8637 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
8638 if (FD) {
8639 S += "\"_vptr$";
8640 std::string recname = CXXRec->getNameAsString();
8641 if (recname.empty()) recname = "?";
8642 S += recname;
8643 S += '"';
8644 }
8645 S += "^^?";
8646#ifndef NDEBUG
8647 CurOffs += getTypeSize(VoidPtrTy);
8648#endif
8649 }
8650
8651 if (!RDecl->hasFlexibleArrayMember()) {
8652 // Mark the end of the structure.
8653 uint64_t offs = toBits(size);
8654 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
8655 std::make_pair(offs, nullptr));
8656 }
8657
8658 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
8659#ifndef NDEBUG
8660 assert(CurOffs <= CurLayObj->first);
8661 if (CurOffs < CurLayObj->first) {
8662 uint64_t padding = CurLayObj->first - CurOffs;
8663 // FIXME: There doesn't seem to be a way to indicate in the encoding that
8664 // packing/alignment of members is different that normal, in which case
8665 // the encoding will be out-of-sync with the real layout.
8666 // If the runtime switches to just consider the size of types without
8667 // taking into account alignment, we could make padding explicit in the
8668 // encoding (e.g. using arrays of chars). The encoding strings would be
8669 // longer then though.
8670 CurOffs += padding;
8671 }
8672#endif
8673
8674 NamedDecl *dcl = CurLayObj->second;
8675 if (!dcl)
8676 break; // reached end of structure.
8677
8678 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
8679 // We expand the bases without their virtual bases since those are going
8680 // in the initial structure. Note that this differs from gcc which
8681 // expands virtual bases each time one is encountered in the hierarchy,
8682 // making the encoding type bigger than it really is.
8683 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
8684 NotEncodedT);
8685 assert(!base->isEmpty());
8686#ifndef NDEBUG
8687 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
8688#endif
8689 } else {
8690 const auto *field = cast<FieldDecl>(dcl);
8691 if (FD) {
8692 S += '"';
8693 S += field->getNameAsString();
8694 S += '"';
8695 }
8696
8697 if (field->isBitField()) {
8698 EncodeBitField(this, S, field->getType(), field);
8699#ifndef NDEBUG
8700 CurOffs += field->getBitWidthValue(*this);
8701#endif
8702 } else {
8703 QualType qt = field->getType();
8705 getObjCEncodingForTypeImpl(
8706 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
8707 FD, NotEncodedT);
8708#ifndef NDEBUG
8709 CurOffs += getTypeSize(field->getType());
8710#endif
8711 }
8712 }
8713 }
8714}
8715
8717 std::string& S) const {
8718 if (QT & Decl::OBJC_TQ_In)
8719 S += 'n';
8720 if (QT & Decl::OBJC_TQ_Inout)
8721 S += 'N';
8722 if (QT & Decl::OBJC_TQ_Out)
8723 S += 'o';
8724 if (QT & Decl::OBJC_TQ_Bycopy)
8725 S += 'O';
8726 if (QT & Decl::OBJC_TQ_Byref)
8727 S += 'R';
8728 if (QT & Decl::OBJC_TQ_Oneway)
8729 S += 'V';
8730}
8731
8733 if (!ObjCIdDecl) {
8736 ObjCIdDecl = buildImplicitTypedef(T, "id");
8737 }
8738 return ObjCIdDecl;
8739}
8740
8742 if (!ObjCSelDecl) {
8744 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
8745 }
8746 return ObjCSelDecl;
8747}
8748
8750 if (!ObjCClassDecl) {
8753 ObjCClassDecl = buildImplicitTypedef(T, "Class");
8754 }
8755 return ObjCClassDecl;
8756}
8757
8759 if (!ObjCProtocolClassDecl) {
8760 ObjCProtocolClassDecl
8763 &Idents.get("Protocol"),
8764 /*typeParamList=*/nullptr,
8765 /*PrevDecl=*/nullptr,
8766 SourceLocation(), true);
8767 }
8768
8769 return ObjCProtocolClassDecl;
8770}
8771
8772//===----------------------------------------------------------------------===//
8773// __builtin_va_list Construction Functions
8774//===----------------------------------------------------------------------===//
8775
8777 StringRef Name) {
8778 // typedef char* __builtin[_ms]_va_list;
8779 QualType T = Context->getPointerType(Context->CharTy);
8780 return Context->buildImplicitTypedef(T, Name);
8781}
8782
8784 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
8785}
8786
8788 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
8789}
8790
8792 // typedef void* __builtin_va_list;
8793 QualType T = Context->getPointerType(Context->VoidTy);
8794 return Context->buildImplicitTypedef(T, "__builtin_va_list");
8795}
8796
8797static TypedefDecl *
8799 // struct __va_list
8800 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
8801 if (Context->getLangOpts().CPlusPlus) {
8802 // namespace std { struct __va_list {
8803 auto *NS = NamespaceDecl::Create(
8804 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(),
8805 /*Inline=*/false, SourceLocation(), SourceLocation(),
8806 &Context->Idents.get("std"),
8807 /*PrevDecl=*/nullptr, /*Nested=*/false);
8808 NS->setImplicit();
8809 VaListTagDecl->setDeclContext(NS);
8810 }
8811
8812 VaListTagDecl->startDefinition();
8813
8814 const size_t NumFields = 5;
8815 QualType FieldTypes[NumFields];
8816 const char *FieldNames[NumFields];
8817
8818 // void *__stack;
8819 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
8820 FieldNames[0] = "__stack";
8821
8822 // void *__gr_top;
8823 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
8824 FieldNames[1] = "__gr_top";
8825
8826 // void *__vr_top;
8827 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8828 FieldNames[2] = "__vr_top";
8829
8830 // int __gr_offs;
8831 FieldTypes[3] = Context->IntTy;
8832 FieldNames[3] = "__gr_offs";
8833
8834 // int __vr_offs;
8835 FieldTypes[4] = Context->IntTy;
8836 FieldNames[4] = "__vr_offs";
8837
8838 // Create fields
8839 for (unsigned i = 0; i < NumFields; ++i) {
8840 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8841 VaListTagDecl,
8844 &Context->Idents.get(FieldNames[i]),
8845 FieldTypes[i], /*TInfo=*/nullptr,
8846 /*BitWidth=*/nullptr,
8847 /*Mutable=*/false,
8848 ICIS_NoInit);
8849 Field->setAccess(AS_public);
8850 VaListTagDecl->addDecl(Field);
8851 }
8852 VaListTagDecl->completeDefinition();
8853 Context->VaListTagDecl = VaListTagDecl;
8854 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8855
8856 // } __builtin_va_list;
8857 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
8858}
8859
8861 // typedef struct __va_list_tag {
8862 RecordDecl *VaListTagDecl;
8863
8864 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8865 VaListTagDecl->startDefinition();
8866
8867 const size_t NumFields = 5;
8868 QualType FieldTypes[NumFields];
8869 const char *FieldNames[NumFields];
8870
8871 // unsigned char gpr;
8872 FieldTypes[0] = Context->UnsignedCharTy;
8873 FieldNames[0] = "gpr";
8874
8875 // unsigned char fpr;
8876 FieldTypes[1] = Context->UnsignedCharTy;
8877 FieldNames[1] = "fpr";
8878
8879 // unsigned short reserved;
8880 FieldTypes[2] = Context->UnsignedShortTy;
8881 FieldNames[2] = "reserved";
8882
8883 // void* overflow_arg_area;
8884 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
8885 FieldNames[3] = "overflow_arg_area";
8886
8887 // void* reg_save_area;
8888 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
8889 FieldNames[4] = "reg_save_area";
8890
8891 // Create fields
8892 for (unsigned i = 0; i < NumFields; ++i) {
8893 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
8896 &Context->Idents.get(FieldNames[i]),
8897 FieldTypes[i], /*TInfo=*/nullptr,
8898 /*BitWidth=*/nullptr,
8899 /*Mutable=*/false,
8900 ICIS_NoInit);
8901 Field->setAccess(AS_public);
8902 VaListTagDecl->addDecl(Field);
8903 }
8904 VaListTagDecl->completeDefinition();
8905 Context->VaListTagDecl = VaListTagDecl;
8906 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8907
8908 // } __va_list_tag;
8909 TypedefDecl *VaListTagTypedefDecl =
8910 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
8911
8912 QualType VaListTagTypedefType =
8913 Context->getTypedefType(VaListTagTypedefDecl);
8914
8915 // typedef __va_list_tag __builtin_va_list[1];
8916 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8917 QualType VaListTagArrayType = Context->getConstantArrayType(
8918 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
8919 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8920}
8921
8922static TypedefDecl *
8924 // struct __va_list_tag {
8925 RecordDecl *VaListTagDecl;
8926 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8927 VaListTagDecl->startDefinition();
8928
8929 const size_t NumFields = 4;
8930 QualType FieldTypes[NumFields];
8931 const char *FieldNames[NumFields];
8932
8933 // unsigned gp_offset;
8934 FieldTypes[0] = Context->UnsignedIntTy;
8935 FieldNames[0] = "gp_offset";
8936
8937 // unsigned fp_offset;
8938 FieldTypes[1] = Context->UnsignedIntTy;
8939 FieldNames[1] = "fp_offset";
8940
8941 // void* overflow_arg_area;
8942 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8943 FieldNames[2] = "overflow_arg_area";
8944
8945 // void* reg_save_area;
8946 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
8947 FieldNames[3] = "reg_save_area";
8948
8949 // Create fields
8950 for (unsigned i = 0; i < NumFields; ++i) {
8951 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8952 VaListTagDecl,
8955 &Context->Idents.get(FieldNames[i]),
8956 FieldTypes[i], /*TInfo=*/nullptr,
8957 /*BitWidth=*/nullptr,
8958 /*Mutable=*/false,
8959 ICIS_NoInit);
8960 Field->setAccess(AS_public);
8961 VaListTagDecl->addDecl(Field);
8962 }
8963 VaListTagDecl->completeDefinition();
8964 Context->VaListTagDecl = VaListTagDecl;
8965 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8966
8967 // };
8968
8969 // typedef struct __va_list_tag __builtin_va_list[1];
8970 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8971 QualType VaListTagArrayType = Context->getConstantArrayType(
8972 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
8973 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8974}
8975
8977 // typedef int __builtin_va_list[4];
8978 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
8979 QualType IntArrayType = Context->getConstantArrayType(
8980 Context->IntTy, Size, nullptr, ArraySizeModifier::Normal, 0);
8981 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
8982}
8983
8984static TypedefDecl *
8986 // struct __va_list
8987 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
8988 if (Context->getLangOpts().CPlusPlus) {
8989 // namespace std { struct __va_list {
8990 NamespaceDecl *NS;
8991 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
8992 Context->getTranslationUnitDecl(),
8993 /*Inline=*/false, SourceLocation(),
8994 SourceLocation(), &Context->Idents.get("std"),
8995 /*PrevDecl=*/nullptr, /*Nested=*/false);
8996 NS->setImplicit();
8997 VaListDecl->setDeclContext(NS);
8998 }
8999
9000 VaListDecl->startDefinition();
9001
9002 // void * __ap;
9003 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9004 VaListDecl,
9007 &Context->Idents.get("__ap"),
9008 Context->getPointerType(Context->VoidTy),
9009 /*TInfo=*/nullptr,
9010 /*BitWidth=*/nullptr,
9011 /*Mutable=*/false,
9012 ICIS_NoInit);
9013 Field->setAccess(AS_public);
9014 VaListDecl->addDecl(Field);
9015
9016 // };
9017 VaListDecl->completeDefinition();
9018 Context->VaListTagDecl = VaListDecl;
9019
9020 // typedef struct __va_list __builtin_va_list;
9021 QualType T = Context->getRecordType(VaListDecl);
9022 return Context->buildImplicitTypedef(T, "__builtin_va_list");
9023}
9024
9025static TypedefDecl *
9027 // struct __va_list_tag {
9028 RecordDecl *VaListTagDecl;
9029 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9030 VaListTagDecl->startDefinition();
9031
9032 const size_t NumFields = 4;
9033 QualType FieldTypes[NumFields];
9034 const char *FieldNames[NumFields];
9035
9036 // long __gpr;
9037 FieldTypes[0] = Context->LongTy;
9038 FieldNames[0] = "__gpr";
9039
9040 // long __fpr;
9041 FieldTypes[1] = Context->LongTy;
9042 FieldNames[1] = "__fpr";
9043
9044 // void *__overflow_arg_area;
9045 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9046 FieldNames[2] = "__overflow_arg_area";
9047
9048 // void *__reg_save_area;
9049 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
9050 FieldNames[3] = "__reg_save_area";
9051
9052 // Create fields
9053 for (unsigned i = 0; i < NumFields; ++i) {
9054 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9055 VaListTagDecl,
9058 &Context->Idents.get(FieldNames[i]),
9059 FieldTypes[i], /*TInfo=*/nullptr,
9060 /*BitWidth=*/nullptr,
9061 /*Mutable=*/false,
9062 ICIS_NoInit);
9063 Field->setAccess(AS_public);
9064 VaListTagDecl->addDecl(Field);
9065 }
9066 VaListTagDecl->completeDefinition();
9067 Context->VaListTagDecl = VaListTagDecl;
9068 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9069
9070 // };
9071
9072 // typedef __va_list_tag __builtin_va_list[1];
9073 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
9074 QualType VaListTagArrayType = Context->getConstantArrayType(
9075 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
9076
9077 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
9078}
9079
9081 // typedef struct __va_list_tag {
9082 RecordDecl *VaListTagDecl;
9083 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9084 VaListTagDecl->startDefinition();
9085
9086 const size_t NumFields = 3;
9087 QualType FieldTypes[NumFields];
9088 const char *FieldNames[NumFields];
9089
9090 // void *CurrentSavedRegisterArea;
9091 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
9092 FieldNames[0] = "__current_saved_reg_area_pointer";
9093
9094 // void *SavedRegAreaEnd;
9095 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
9096 FieldNames[1] = "__saved_reg_area_end_pointer";
9097
9098 // void *OverflowArea;
9099 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9100 FieldNames[2] = "__overflow_area_pointer";
9101
9102 // Create fields
9103 for (unsigned i = 0; i < NumFields; ++i) {
9105 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
9106 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
9107 /*TInfo=*/nullptr,
9108 /*BitWidth=*/nullptr,
9109 /*Mutable=*/false, ICIS_NoInit);
9110 Field->setAccess(AS_public);
9111 VaListTagDecl->addDecl(Field);
9112 }
9113 VaListTagDecl->completeDefinition();
9114 Context->VaListTagDecl = VaListTagDecl;
9115 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9116
9117 // } __va_list_tag;
9118 TypedefDecl *VaListTagTypedefDecl =
9119 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
9120
9121 QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl);
9122
9123 // typedef __va_list_tag __builtin_va_list[1];
9124 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
9125 QualType VaListTagArrayType = Context->getConstantArrayType(
9126 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
9127
9128 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
9129}
9130
9133 switch (Kind) {
9135 return CreateCharPtrBuiltinVaListDecl(Context);
9137 return CreateVoidPtrBuiltinVaListDecl(Context);
9139 return CreateAArch64ABIBuiltinVaListDecl(Context);
9141 return CreatePowerABIBuiltinVaListDecl(Context);
9143 return CreateX86_64ABIBuiltinVaListDecl(Context);
9145 return CreatePNaClABIBuiltinVaListDecl(Context);
9147 return CreateAAPCSABIBuiltinVaListDecl(Context);
9149 return CreateSystemZBuiltinVaListDecl(Context);
9151 return CreateHexagonBuiltinVaListDecl(Context);
9152 }
9153
9154 llvm_unreachable("Unhandled __builtin_va_list type kind");
9155}
9156
9158 if (!BuiltinVaListDecl) {
9159 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
9160 assert(BuiltinVaListDecl->isImplicit());
9161 }
9162
9163 return BuiltinVaListDecl;
9164}
9165
9167 // Force the creation of VaListTagDecl by building the __builtin_va_list
9168 // declaration.
9169 if (!VaListTagDecl)
9170 (void)getBuiltinVaListDecl();
9171
9172 return VaListTagDecl;
9173}
9174
9176 if (!BuiltinMSVaListDecl)
9177 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
9178
9179 return BuiltinMSVaListDecl;
9180}
9181
9183 // Allow redecl custom type checking builtin for HLSL.
9184 if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
9186 return true;
9188}
9189
9191 assert(ObjCConstantStringType.isNull() &&
9192 "'NSConstantString' type already set!");
9193
9194 ObjCConstantStringType = getObjCInterfaceType(Decl);
9195}
9196
9197/// Retrieve the template name that corresponds to a non-empty
9198/// lookup.
9201 UnresolvedSetIterator End) const {
9202 unsigned size = End - Begin;
9203 assert(size > 1 && "set is not overloaded!");
9204
9205 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
9206 size * sizeof(FunctionTemplateDecl*));
9207 auto *OT = new (memory) OverloadedTemplateStorage(size);
9208
9209 NamedDecl **Storage = OT->getStorage();
9210 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
9211 NamedDecl *D = *I;
9212 assert(isa<FunctionTemplateDecl>(D) ||
9213 isa<UnresolvedUsingValueDecl>(D) ||
9214 (isa<UsingShadowDecl>(D) &&
9215 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
9216 *Storage++ = D;
9217 }
9218
9219 return TemplateName(OT);
9220}
9221
9222/// Retrieve a template name representing an unqualified-id that has been
9223/// assumed to name a template for ADL purposes.
9225 auto *OT = new (*this) AssumedTemplateStorage(Name);
9226 return TemplateName(OT);
9227}
9228
9229/// Retrieve the template name that represents a qualified
9230/// template name such as \c std::vector.
9232 bool TemplateKeyword,
9233 TemplateName Template) const {
9234 assert(NNS && "Missing nested-name-specifier in qualified template name");
9235
9236 // FIXME: Canonicalization?
9237 llvm::FoldingSetNodeID ID;
9238 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
9239
9240 void *InsertPos = nullptr;
9242 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9243 if (!QTN) {
9244 QTN = new (*this, alignof(QualifiedTemplateName))
9245 QualifiedTemplateName(NNS, TemplateKeyword, Template);
9246 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
9247 }
9248
9249 return TemplateName(QTN);
9250}
9251
9252/// Retrieve the template name that represents a dependent
9253/// template name such as \c MetaFun::template apply.
9256 const IdentifierInfo *Name) const {
9257 assert((!NNS || NNS->isDependent()) &&
9258 "Nested name specifier must be dependent");
9259
9260 llvm::FoldingSetNodeID ID;
9261 DependentTemplateName::Profile(ID, NNS, Name);
9262
9263 void *InsertPos = nullptr;
9265 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9266
9267 if (QTN)
9268 return TemplateName(QTN);
9269
9271 if (CanonNNS == NNS) {
9272 QTN = new (*this, alignof(DependentTemplateName))
9273 DependentTemplateName(NNS, Name);
9274 } else {
9275 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
9276 QTN = new (*this, alignof(DependentTemplateName))
9277 DependentTemplateName(NNS, Name, Canon);
9278 DependentTemplateName *CheckQTN =
9279 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9280 assert(!CheckQTN && "Dependent type name canonicalization broken");
9281 (void)CheckQTN;
9282 }
9283
9284 DependentTemplateNames.InsertNode(QTN, InsertPos);
9285 return TemplateName(QTN);
9286}
9287
9288/// Retrieve the template name that represents a dependent
9289/// template name such as \c MetaFun::template operator+.
9292 OverloadedOperatorKind Operator) const {
9293 assert((!NNS || NNS->isDependent()) &&
9294 "Nested name specifier must be dependent");
9295
9296 llvm::FoldingSetNodeID ID;
9297 DependentTemplateName::Profile(ID, NNS, Operator);
9298
9299 void *InsertPos = nullptr;
9301 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9302
9303 if (QTN)
9304 return TemplateName(QTN);
9305
9307 if (CanonNNS == NNS) {
9308 QTN = new (*this, alignof(DependentTemplateName))
9309 DependentTemplateName(NNS, Operator);
9310 } else {
9311 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
9312 QTN = new (*this, alignof(DependentTemplateName))
9313 DependentTemplateName(NNS, Operator, Canon);
9314
9315 DependentTemplateName *CheckQTN
9316 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9317 assert(!CheckQTN && "Dependent template name canonicalization broken");
9318 (void)CheckQTN;
9319 }
9320
9321 DependentTemplateNames.InsertNode(QTN, InsertPos);
9322 return TemplateName(QTN);
9323}
9324
9326 TemplateName Replacement, Decl *AssociatedDecl, unsigned Index,
9327 std::optional<unsigned> PackIndex) const {
9328 llvm::FoldingSetNodeID ID;
9329 SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
9330 Index, PackIndex);
9331
9332 void *insertPos = nullptr;
9334 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
9335
9336 if (!subst) {
9337 subst = new (*this) SubstTemplateTemplateParmStorage(
9338 Replacement, AssociatedDecl, Index, PackIndex);
9339 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
9340 }
9341
9342 return TemplateName(subst);
9343}
9344
9347 Decl *AssociatedDecl,
9348 unsigned Index, bool Final) const {
9349 auto &Self = const_cast<ASTContext &>(*this);
9350 llvm::FoldingSetNodeID ID;
9352 AssociatedDecl, Index, Final);
9353
9354 void *InsertPos = nullptr;
9356 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
9357
9358 if (!Subst) {
9359 Subst = new (*this) SubstTemplateTemplateParmPackStorage(
9360 ArgPack.pack_elements(), AssociatedDecl, Index, Final);
9361 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
9362 }
9363
9364 return TemplateName(Subst);
9365}
9366
9367/// getFromTargetType - Given one of the integer types provided by
9368/// TargetInfo, produce the corresponding type. The unsigned @p Type
9369/// is actually a value of type @c TargetInfo::IntType.
9370CanQualType ASTContext::getFromTargetType(unsigned Type) const {
9371 switch (Type) {
9372 case TargetInfo::NoInt: return {};
9375 case TargetInfo::SignedShort: return ShortTy;
9377 case TargetInfo::SignedInt: return IntTy;
9379 case TargetInfo::SignedLong: return LongTy;
9383 }
9384
9385 llvm_unreachable("Unhandled TargetInfo::IntType value");
9386}
9387
9388//===----------------------------------------------------------------------===//
9389// Type Predicates.
9390//===----------------------------------------------------------------------===//
9391
9392/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
9393/// garbage collection attribute.
9394///
9396 if (getLangOpts().getGC() == LangOptions::NonGC)
9397 return Qualifiers::GCNone;
9398
9399 assert(getLangOpts().ObjC);
9400 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
9401
9402 // Default behaviour under objective-C's gc is for ObjC pointers
9403 // (or pointers to them) be treated as though they were declared
9404 // as __strong.
9405 if (GCAttrs == Qualifiers::GCNone) {
9407 return Qualifiers::Strong;
9408 else if (Ty->isPointerType())
9410 } else {
9411 // It's not valid to set GC attributes on anything that isn't a
9412 // pointer.
9413#ifndef NDEBUG
9415 while (const auto *AT = dyn_cast<ArrayType>(CT))
9416 CT = AT->getElementType();
9417 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
9418#endif
9419 }
9420 return GCAttrs;
9421}
9422
9423//===----------------------------------------------------------------------===//
9424// Type Compatibility Testing
9425//===----------------------------------------------------------------------===//
9426
9427/// areCompatVectorTypes - Return true if the two specified vector types are
9428/// compatible.
9429static bool areCompatVectorTypes(const VectorType *LHS,
9430 const VectorType *RHS) {
9431 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
9432 return LHS->getElementType() == RHS->getElementType() &&
9433 LHS->getNumElements() == RHS->getNumElements();
9434}
9435
9436/// areCompatMatrixTypes - Return true if the two specified matrix types are
9437/// compatible.
9439 const ConstantMatrixType *RHS) {
9440 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
9441 return LHS->getElementType() == RHS->getElementType() &&
9442 LHS->getNumRows() == RHS->getNumRows() &&
9443 LHS->getNumColumns() == RHS->getNumColumns();
9444}
9445
9447 QualType SecondVec) {
9448 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
9449 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
9450
9451 if (hasSameUnqualifiedType(FirstVec, SecondVec))
9452 return true;
9453
9454 // Treat Neon vector types and most AltiVec vector types as if they are the
9455 // equivalent GCC vector types.
9456 const auto *First = FirstVec->castAs<VectorType>();
9457 const auto *Second = SecondVec->castAs<VectorType>();
9458 if (First->getNumElements() == Second->getNumElements() &&
9459 hasSameType(First->getElementType(), Second->getElementType()) &&
9460 First->getVectorKind() != VectorKind::AltiVecPixel &&
9461 First->getVectorKind() != VectorKind::AltiVecBool &&
9464 First->getVectorKind() != VectorKind::SveFixedLengthData &&
9465 First->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
9468 First->getVectorKind() != VectorKind::RVVFixedLengthData &&
9470 First->getVectorKind() != VectorKind::RVVFixedLengthMask &&
9472 return true;
9473
9474 return false;
9475}
9476
9477/// getSVETypeSize - Return SVE vector or predicate register size.
9478static uint64_t getSVETypeSize(ASTContext &Context, const BuiltinType *Ty) {
9479 assert(Ty->isSveVLSBuiltinType() && "Invalid SVE Type");
9480 if (Ty->getKind() == BuiltinType::SveBool ||
9481 Ty->getKind() == BuiltinType::SveCount)
9482 return (Context.getLangOpts().VScaleMin * 128) / Context.getCharWidth();
9483 return Context.getLangOpts().VScaleMin * 128;
9484}
9485
9487 QualType SecondType) {
9488 assert(
9489 ((FirstType->isSVESizelessBuiltinType() && SecondType->isVectorType()) ||
9490 (FirstType->isVectorType() && SecondType->isSVESizelessBuiltinType())) &&
9491 "Expected SVE builtin type and vector type!");
9492
9493 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
9494 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
9495 if (const auto *VT = SecondType->getAs<VectorType>()) {
9496 // Predicates have the same representation as uint8 so we also have to
9497 // check the kind to make these types incompatible.
9498 if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
9499 return BT->getKind() == BuiltinType::SveBool;
9500 else if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
9501 return VT->getElementType().getCanonicalType() ==
9502 FirstType->getSveEltType(*this);
9503 else if (VT->getVectorKind() == VectorKind::Generic)
9504 return getTypeSize(SecondType) == getSVETypeSize(*this, BT) &&
9505 hasSameType(VT->getElementType(),
9506 getBuiltinVectorTypeInfo(BT).ElementType);
9507 }
9508 }
9509 return false;
9510 };
9511
9512 return IsValidCast(FirstType, SecondType) ||
9513 IsValidCast(SecondType, FirstType);
9514}
9515
9517 QualType SecondType) {
9518 assert(
9519 ((FirstType->isSVESizelessBuiltinType() && SecondType->isVectorType()) ||
9520 (FirstType->isVectorType() && SecondType->isSVESizelessBuiltinType())) &&
9521 "Expected SVE builtin type and vector type!");
9522
9523 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
9524 const auto *BT = FirstType->getAs<BuiltinType>();
9525 if (!BT)
9526 return false;
9527
9528 const auto *VecTy = SecondType->getAs<VectorType>();
9529 if (VecTy && (VecTy->getVectorKind() == VectorKind::SveFixedLengthData ||
9530 VecTy->getVectorKind() == VectorKind::Generic)) {
9532 getLangOpts().getLaxVectorConversions();
9533
9534 // Can not convert between sve predicates and sve vectors because of
9535 // different size.
9536 if (BT->getKind() == BuiltinType::SveBool &&
9537 VecTy->getVectorKind() == VectorKind::SveFixedLengthData)
9538 return false;
9539
9540 // If __ARM_FEATURE_SVE_BITS != N do not allow GNU vector lax conversion.
9541 // "Whenever __ARM_FEATURE_SVE_BITS==N, GNUT implicitly
9542 // converts to VLAT and VLAT implicitly converts to GNUT."
9543 // ACLE Spec Version 00bet6, 3.7.3.2. Behavior common to vectors and
9544 // predicates.
9545 if (VecTy->getVectorKind() == VectorKind::Generic &&
9546 getTypeSize(SecondType) != getSVETypeSize(*this, BT))
9547 return false;
9548
9549 // If -flax-vector-conversions=all is specified, the types are
9550 // certainly compatible.
9552 return true;
9553
9554 // If -flax-vector-conversions=integer is specified, the types are
9555 // compatible if the elements are integer types.
9557 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
9558 FirstType->getSveEltType(*this)->isIntegerType();
9559 }
9560
9561 return false;
9562 };
9563
9564 return IsLaxCompatible(FirstType, SecondType) ||
9565 IsLaxCompatible(SecondType, FirstType);
9566}
9567
9568/// getRVVTypeSize - Return RVV vector register size.
9569static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) {
9570 assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type");
9571 auto VScale = Context.getTargetInfo().getVScaleRange(Context.getLangOpts());
9572 if (!VScale)
9573 return 0;
9574
9576
9577 unsigned EltSize = Context.getTypeSize(Info.ElementType);
9578 if (Info.ElementType == Context.BoolTy)
9579 EltSize = 1;
9580
9581 unsigned MinElts = Info.EC.getKnownMinValue();
9582 return VScale->first * MinElts * EltSize;
9583}
9584
9586 QualType SecondType) {
9587 assert(
9588 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
9589 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
9590 "Expected RVV builtin type and vector type!");
9591
9592 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
9593 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
9594 if (const auto *VT = SecondType->getAs<VectorType>()) {
9595 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask) {
9597 return FirstType->isRVVVLSBuiltinType() &&
9598 Info.ElementType == BoolTy &&
9599 getTypeSize(SecondType) == getRVVTypeSize(*this, BT);
9600 }
9601 if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
9602 VT->getVectorKind() == VectorKind::Generic)
9603 return FirstType->isRVVVLSBuiltinType() &&
9604 getTypeSize(SecondType) == getRVVTypeSize(*this, BT) &&
9605 hasSameType(VT->getElementType(),
9606 getBuiltinVectorTypeInfo(BT).ElementType);
9607 }
9608 }
9609 return false;
9610 };
9611
9612 return IsValidCast(FirstType, SecondType) ||
9613 IsValidCast(SecondType, FirstType);
9614}
9615
9617 QualType SecondType) {
9618 assert(
9619 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
9620 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
9621 "Expected RVV builtin type and vector type!");
9622
9623 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
9624 const auto *BT = FirstType->getAs<BuiltinType>();
9625 if (!BT)
9626 return false;
9627
9628 if (!BT->isRVVVLSBuiltinType())
9629 return false;
9630
9631 const auto *VecTy = SecondType->getAs<VectorType>();
9632 if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) {
9634 getLangOpts().getLaxVectorConversions();
9635
9636 // If __riscv_v_fixed_vlen != N do not allow vector lax conversion.
9637 if (getTypeSize(SecondType) != getRVVTypeSize(*this, BT))
9638 return false;
9639
9640 // If -flax-vector-conversions=all is specified, the types are
9641 // certainly compatible.
9643 return true;
9644
9645 // If -flax-vector-conversions=integer is specified, the types are
9646 // compatible if the elements are integer types.
9648 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
9649 FirstType->getRVVEltType(*this)->isIntegerType();
9650 }
9651
9652 return false;
9653 };
9654
9655 return IsLaxCompatible(FirstType, SecondType) ||
9656 IsLaxCompatible(SecondType, FirstType);
9657}
9658
9660 while (true) {
9661 // __strong id
9662 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
9663 if (Attr->getAttrKind() == attr::ObjCOwnership)
9664 return true;
9665
9666 Ty = Attr->getModifiedType();
9667
9668 // X *__strong (...)
9669 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
9670 Ty = Paren->getInnerType();
9671
9672 // We do not want to look through typedefs, typeof(expr),
9673 // typeof(type), or any other way that the type is somehow
9674 // abstracted.
9675 } else {
9676 return false;
9677 }
9678 }
9679}
9680
9681//===----------------------------------------------------------------------===//
9682// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
9683//===----------------------------------------------------------------------===//
9684
9685/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
9686/// inheritance hierarchy of 'rProto'.
9687bool
9689 ObjCProtocolDecl *rProto) const {
9690 if (declaresSameEntity(lProto, rProto))
9691 return true;
9692 for (auto *PI : rProto->protocols())
9693 if (ProtocolCompatibleWithProtocol(lProto, PI))
9694 return true;
9695 return false;
9696}
9697
9698/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
9699/// Class<pr1, ...>.
9701 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
9702 for (auto *lhsProto : lhs->quals()) {
9703 bool match = false;
9704 for (auto *rhsProto : rhs->quals()) {
9705 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
9706 match = true;
9707 break;
9708 }
9709 }
9710 if (!match)
9711 return false;
9712 }
9713 return true;
9714}
9715
9716/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
9717/// ObjCQualifiedIDType.
9719 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
9720 bool compare) {
9721 // Allow id<P..> and an 'id' in all cases.
9722 if (lhs->isObjCIdType() || rhs->isObjCIdType())
9723 return true;
9724
9725 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
9726 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
9728 return false;
9729
9730 if (lhs->isObjCQualifiedIdType()) {
9731 if (rhs->qual_empty()) {
9732 // If the RHS is a unqualified interface pointer "NSString*",
9733 // make sure we check the class hierarchy.
9734 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
9735 for (auto *I : lhs->quals()) {
9736 // when comparing an id<P> on lhs with a static type on rhs,
9737 // see if static class implements all of id's protocols, directly or
9738 // through its super class and categories.
9739 if (!rhsID->ClassImplementsProtocol(I, true))
9740 return false;
9741 }
9742 }
9743 // If there are no qualifiers and no interface, we have an 'id'.
9744 return true;
9745 }
9746 // Both the right and left sides have qualifiers.
9747 for (auto *lhsProto : lhs->quals()) {
9748 bool match = false;
9749
9750 // when comparing an id<P> on lhs with a static type on rhs,
9751 // see if static class implements all of id's protocols, directly or
9752 // through its super class and categories.
9753 for (auto *rhsProto : rhs->quals()) {
9754 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
9755 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
9756 match = true;
9757 break;
9758 }
9759 }
9760 // If the RHS is a qualified interface pointer "NSString<P>*",
9761 // make sure we check the class hierarchy.
9762 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
9763 for (auto *I : lhs->quals()) {
9764 // when comparing an id<P> on lhs with a static type on rhs,
9765 // see if static class implements all of id's protocols, directly or
9766 // through its super class and categories.
9767 if (rhsID->ClassImplementsProtocol(I, true)) {
9768 match = true;
9769 break;
9770 }
9771 }
9772 }
9773 if (!match)
9774 return false;
9775 }
9776
9777 return true;
9778 }
9779
9780 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
9781
9782 if (lhs->getInterfaceType()) {
9783 // If both the right and left sides have qualifiers.
9784 for (auto *lhsProto : lhs->quals()) {
9785 bool match = false;
9786
9787 // when comparing an id<P> on rhs with a static type on lhs,
9788 // see if static class implements all of id's protocols, directly or
9789 // through its super class and categories.
9790 // First, lhs protocols in the qualifier list must be found, direct
9791 // or indirect in rhs's qualifier list or it is a mismatch.
9792 for (auto *rhsProto : rhs->quals()) {
9793 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
9794 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
9795 match = true;
9796 break;
9797 }
9798 }
9799 if (!match)
9800 return false;
9801 }
9802
9803 // Static class's protocols, or its super class or category protocols
9804 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
9805 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
9806 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
9807 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
9808 // This is rather dubious but matches gcc's behavior. If lhs has
9809 // no type qualifier and its class has no static protocol(s)
9810 // assume that it is mismatch.
9811 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
9812 return false;
9813 for (auto *lhsProto : LHSInheritedProtocols) {
9814 bool match = false;
9815 for (auto *rhsProto : rhs->quals()) {
9816 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
9817 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
9818 match = true;
9819 break;
9820 }
9821 }
9822 if (!match)
9823 return false;
9824 }
9825 }
9826 return true;
9827 }
9828 return false;
9829}
9830
9831/// canAssignObjCInterfaces - Return true if the two interface types are
9832/// compatible for assignment from RHS to LHS. This handles validation of any
9833/// protocol qualifiers on the LHS or RHS.
9835 const ObjCObjectPointerType *RHSOPT) {
9836 const ObjCObjectType* LHS = LHSOPT->getObjectType();
9837 const ObjCObjectType* RHS = RHSOPT->getObjectType();
9838
9839 // If either type represents the built-in 'id' type, return true.
9840 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
9841 return true;
9842
9843 // Function object that propagates a successful result or handles
9844 // __kindof types.
9845 auto finish = [&](bool succeeded) -> bool {
9846 if (succeeded)
9847 return true;
9848
9849 if (!RHS->isKindOfType())
9850 return false;
9851
9852 // Strip off __kindof and protocol qualifiers, then check whether
9853 // we can assign the other way.
9855 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
9856 };
9857
9858 // Casts from or to id<P> are allowed when the other side has compatible
9859 // protocols.
9860 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
9861 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
9862 }
9863
9864 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
9865 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
9866 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
9867 }
9868
9869 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
9870 if (LHS->isObjCClass() && RHS->isObjCClass()) {
9871 return true;
9872 }
9873
9874 // If we have 2 user-defined types, fall into that path.
9875 if (LHS->getInterface() && RHS->getInterface()) {
9876 return finish(canAssignObjCInterfaces(LHS, RHS));
9877 }
9878
9879 return false;
9880}
9881
9882/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
9883/// for providing type-safety for objective-c pointers used to pass/return
9884/// arguments in block literals. When passed as arguments, passing 'A*' where
9885/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
9886/// not OK. For the return type, the opposite is not OK.
9888 const ObjCObjectPointerType *LHSOPT,
9889 const ObjCObjectPointerType *RHSOPT,
9890 bool BlockReturnType) {
9891
9892 // Function object that propagates a successful result or handles
9893 // __kindof types.
9894 auto finish = [&](bool succeeded) -> bool {
9895 if (succeeded)
9896 return true;
9897
9898 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
9899 if (!Expected->isKindOfType())
9900 return false;
9901
9902 // Strip off __kindof and protocol qualifiers, then check whether
9903 // we can assign the other way.
9905 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
9906 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
9907 BlockReturnType);
9908 };
9909
9910 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
9911 return true;
9912
9913 if (LHSOPT->isObjCBuiltinType()) {
9914 return finish(RHSOPT->isObjCBuiltinType() ||
9915 RHSOPT->isObjCQualifiedIdType());
9916 }
9917
9918 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
9919 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
9920 // Use for block parameters previous type checking for compatibility.
9921 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
9922 // Or corrected type checking as in non-compat mode.
9923 (!BlockReturnType &&
9924 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
9925 else
9927 (BlockReturnType ? LHSOPT : RHSOPT),
9928 (BlockReturnType ? RHSOPT : LHSOPT), false));
9929 }
9930
9931 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
9932 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
9933 if (LHS && RHS) { // We have 2 user-defined types.
9934 if (LHS != RHS) {
9935 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
9936 return finish(BlockReturnType);
9937 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
9938 return finish(!BlockReturnType);
9939 }
9940 else
9941 return true;
9942 }
9943 return false;
9944}
9945
9946/// Comparison routine for Objective-C protocols to be used with
9947/// llvm::array_pod_sort.
9949 ObjCProtocolDecl * const *rhs) {
9950 return (*lhs)->getName().compare((*rhs)->getName());
9951}
9952
9953/// getIntersectionOfProtocols - This routine finds the intersection of set
9954/// of protocols inherited from two distinct objective-c pointer objects with
9955/// the given common base.
9956/// It is used to build composite qualifier list of the composite type of
9957/// the conditional expression involving two objective-c pointer objects.
9958static
9960 const ObjCInterfaceDecl *CommonBase,
9961 const ObjCObjectPointerType *LHSOPT,
9962 const ObjCObjectPointerType *RHSOPT,
9963 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
9964
9965 const ObjCObjectType* LHS = LHSOPT->getObjectType();
9966 const ObjCObjectType* RHS = RHSOPT->getObjectType();
9967 assert(LHS->getInterface() && "LHS must have an interface base");
9968 assert(RHS->getInterface() && "RHS must have an interface base");
9969
9970 // Add all of the protocols for the LHS.
9972
9973 // Start with the protocol qualifiers.
9974 for (auto *proto : LHS->quals()) {
9975 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
9976 }
9977
9978 // Also add the protocols associated with the LHS interface.
9979 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
9980
9981 // Add all of the protocols for the RHS.
9983
9984 // Start with the protocol qualifiers.
9985 for (auto *proto : RHS->quals()) {
9986 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
9987 }
9988
9989 // Also add the protocols associated with the RHS interface.
9990 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
9991
9992 // Compute the intersection of the collected protocol sets.
9993 for (auto *proto : LHSProtocolSet) {
9994 if (RHSProtocolSet.count(proto))
9995 IntersectionSet.push_back(proto);
9996 }
9997
9998 // Compute the set of protocols that is implied by either the common type or
9999 // the protocols within the intersection.
10001 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
10002
10003 // Remove any implied protocols from the list of inherited protocols.
10004 if (!ImpliedProtocols.empty()) {
10005 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool {
10006 return ImpliedProtocols.contains(proto);
10007 });
10008 }
10009
10010 // Sort the remaining protocols by name.
10011 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
10013}
10014
10015/// Determine whether the first type is a subtype of the second.
10017 QualType rhs) {
10018 // Common case: two object pointers.
10019 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
10020 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
10021 if (lhsOPT && rhsOPT)
10022 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
10023
10024 // Two block pointers.
10025 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
10026 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
10027 if (lhsBlock && rhsBlock)
10028 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
10029
10030 // If either is an unqualified 'id' and the other is a block, it's
10031 // acceptable.
10032 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
10033 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
10034 return true;
10035
10036 return false;
10037}
10038
10039// Check that the given Objective-C type argument lists are equivalent.
10041 const ObjCInterfaceDecl *iface,
10042 ArrayRef<QualType> lhsArgs,
10043 ArrayRef<QualType> rhsArgs,
10044 bool stripKindOf) {
10045 if (lhsArgs.size() != rhsArgs.size())
10046 return false;
10047
10048 ObjCTypeParamList *typeParams = iface->getTypeParamList();
10049 if (!typeParams)
10050 return false;
10051
10052 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
10053 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
10054 continue;
10055
10056 switch (typeParams->begin()[i]->getVariance()) {
10058 if (!stripKindOf ||
10059 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
10060 rhsArgs[i].stripObjCKindOfType(ctx))) {
10061 return false;
10062 }
10063 break;
10064
10066 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
10067 return false;
10068 break;
10069
10071 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
10072 return false;
10073 break;
10074 }
10075 }
10076
10077 return true;
10078}
10079
10081 const ObjCObjectPointerType *Lptr,
10082 const ObjCObjectPointerType *Rptr) {
10083 const ObjCObjectType *LHS = Lptr->getObjectType();
10084 const ObjCObjectType *RHS = Rptr->getObjectType();
10085 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
10086 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
10087
10088 if (!LDecl || !RDecl)
10089 return {};
10090
10091 // When either LHS or RHS is a kindof type, we should return a kindof type.
10092 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
10093 // kindof(A).
10094 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
10095
10096 // Follow the left-hand side up the class hierarchy until we either hit a
10097 // root or find the RHS. Record the ancestors in case we don't find it.
10098 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
10099 LHSAncestors;
10100 while (true) {
10101 // Record this ancestor. We'll need this if the common type isn't in the
10102 // path from the LHS to the root.
10103 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
10104
10105 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
10106 // Get the type arguments.
10107 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
10108 bool anyChanges = false;
10109 if (LHS->isSpecialized() && RHS->isSpecialized()) {
10110 // Both have type arguments, compare them.
10111 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
10112 LHS->getTypeArgs(), RHS->getTypeArgs(),
10113 /*stripKindOf=*/true))
10114 return {};
10115 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
10116 // If only one has type arguments, the result will not have type
10117 // arguments.
10118 LHSTypeArgs = {};
10119 anyChanges = true;
10120 }
10121
10122 // Compute the intersection of protocols.
10124 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
10125 Protocols);
10126 if (!Protocols.empty())
10127 anyChanges = true;
10128
10129 // If anything in the LHS will have changed, build a new result type.
10130 // If we need to return a kindof type but LHS is not a kindof type, we
10131 // build a new result type.
10132 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
10134 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
10135 anyKindOf || LHS->isKindOfType());
10137 }
10138
10139 return getObjCObjectPointerType(QualType(LHS, 0));
10140 }
10141
10142 // Find the superclass.
10143 QualType LHSSuperType = LHS->getSuperClassType();
10144 if (LHSSuperType.isNull())
10145 break;
10146
10147 LHS = LHSSuperType->castAs<ObjCObjectType>();
10148 }
10149
10150 // We didn't find anything by following the LHS to its root; now check
10151 // the RHS against the cached set of ancestors.
10152 while (true) {
10153 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
10154 if (KnownLHS != LHSAncestors.end()) {
10155 LHS = KnownLHS->second;
10156
10157 // Get the type arguments.
10158 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
10159 bool anyChanges = false;
10160 if (LHS->isSpecialized() && RHS->isSpecialized()) {
10161 // Both have type arguments, compare them.
10162 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
10163 LHS->getTypeArgs(), RHS->getTypeArgs(),
10164 /*stripKindOf=*/true))
10165 return {};
10166 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
10167 // If only one has type arguments, the result will not have type
10168 // arguments.
10169 RHSTypeArgs = {};
10170 anyChanges = true;
10171 }
10172
10173 // Compute the intersection of protocols.
10175 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
10176 Protocols);
10177 if (!Protocols.empty())
10178 anyChanges = true;
10179
10180 // If we need to return a kindof type but RHS is not a kindof type, we
10181 // build a new result type.
10182 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
10184 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
10185 anyKindOf || RHS->isKindOfType());
10187 }
10188
10189 return getObjCObjectPointerType(QualType(RHS, 0));
10190 }
10191
10192 // Find the superclass of the RHS.
10193 QualType RHSSuperType = RHS->getSuperClassType();
10194 if (RHSSuperType.isNull())
10195 break;
10196
10197 RHS = RHSSuperType->castAs<ObjCObjectType>();
10198 }
10199
10200 return {};
10201}
10202
10204 const ObjCObjectType *RHS) {
10205 assert(LHS->getInterface() && "LHS is not an interface type");
10206 assert(RHS->getInterface() && "RHS is not an interface type");
10207
10208 // Verify that the base decls are compatible: the RHS must be a subclass of
10209 // the LHS.
10210 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
10211 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
10212 if (!IsSuperClass)
10213 return false;
10214
10215 // If the LHS has protocol qualifiers, determine whether all of them are
10216 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
10217 // LHS).
10218 if (LHS->getNumProtocols() > 0) {
10219 // OK if conversion of LHS to SuperClass results in narrowing of types
10220 // ; i.e., SuperClass may implement at least one of the protocols
10221 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
10222 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
10223 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
10224 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
10225 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
10226 // qualifiers.
10227 for (auto *RHSPI : RHS->quals())
10228 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
10229 // If there is no protocols associated with RHS, it is not a match.
10230 if (SuperClassInheritedProtocols.empty())
10231 return false;
10232
10233 for (const auto *LHSProto : LHS->quals()) {
10234 bool SuperImplementsProtocol = false;
10235 for (auto *SuperClassProto : SuperClassInheritedProtocols)
10236 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
10237 SuperImplementsProtocol = true;
10238 break;
10239 }
10240 if (!SuperImplementsProtocol)
10241 return false;
10242 }
10243 }
10244
10245 // If the LHS is specialized, we may need to check type arguments.
10246 if (LHS->isSpecialized()) {
10247 // Follow the superclass chain until we've matched the LHS class in the
10248 // hierarchy. This substitutes type arguments through.
10249 const ObjCObjectType *RHSSuper = RHS;
10250 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
10251 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
10252
10253 // If the RHS is specializd, compare type arguments.
10254 if (RHSSuper->isSpecialized() &&
10255 !sameObjCTypeArgs(*this, LHS->getInterface(),
10256 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
10257 /*stripKindOf=*/true)) {
10258 return false;
10259 }
10260 }
10261
10262 return true;
10263}
10264
10266 // get the "pointed to" types
10267 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
10268 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
10269
10270 if (!LHSOPT || !RHSOPT)
10271 return false;
10272
10273 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
10274 canAssignObjCInterfaces(RHSOPT, LHSOPT);
10275}
10276
10279 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
10280 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
10281}
10282
10283/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
10284/// both shall have the identically qualified version of a compatible type.
10285/// C99 6.2.7p1: Two types have compatible types if their types are the
10286/// same. See 6.7.[2,3,5] for additional rules.
10288 bool CompareUnqualified) {
10289 if (getLangOpts().CPlusPlus)
10290 return hasSameType(LHS, RHS);
10291
10292 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
10293}
10294
10296 return typesAreCompatible(LHS, RHS);
10297}
10298
10300 return !mergeTypes(LHS, RHS, true).isNull();
10301}
10302
10303/// mergeTransparentUnionType - if T is a transparent union type and a member
10304/// of T is compatible with SubType, return the merged type, else return
10305/// QualType()
10307 bool OfBlockPointer,
10308 bool Unqualified) {
10309 if (const RecordType *UT = T->getAsUnionType()) {
10310 RecordDecl *UD = UT->getDecl();
10311 if (UD->hasAttr<TransparentUnionAttr>()) {
10312 for (const auto *I : UD->fields()) {
10313 QualType ET = I->getType().getUnqualifiedType();
10314 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
10315 if (!MT.isNull())
10316 return MT;
10317 }
10318 }
10319 }
10320
10321 return {};
10322}
10323
10324/// mergeFunctionParameterTypes - merge two types which appear as function
10325/// parameter types
10327 bool OfBlockPointer,
10328 bool Unqualified) {
10329 // GNU extension: two types are compatible if they appear as a function
10330 // argument, one of the types is a transparent union type and the other
10331 // type is compatible with a union member
10332 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
10333 Unqualified);
10334 if (!lmerge.isNull())
10335 return lmerge;
10336
10337 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
10338 Unqualified);
10339 if (!rmerge.isNull())
10340 return rmerge;
10341
10342 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
10343}
10344
10346 bool OfBlockPointer, bool Unqualified,
10347 bool AllowCXX,
10348 bool IsConditionalOperator) {
10349 const auto *lbase = lhs->castAs<FunctionType>();
10350 const auto *rbase = rhs->castAs<FunctionType>();
10351 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
10352 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
10353 bool allLTypes = true;
10354 bool allRTypes = true;
10355
10356 // Check return type
10357 QualType retType;
10358 if (OfBlockPointer) {
10359 QualType RHS = rbase->getReturnType();
10360 QualType LHS = lbase->getReturnType();
10361 bool UnqualifiedResult = Unqualified;
10362 if (!UnqualifiedResult)
10363 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
10364 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
10365 }
10366 else
10367 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
10368 Unqualified);
10369 if (retType.isNull())
10370 return {};
10371
10372 if (Unqualified)
10373 retType = retType.getUnqualifiedType();
10374
10375 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
10376 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
10377 if (Unqualified) {
10378 LRetType = LRetType.getUnqualifiedType();
10379 RRetType = RRetType.getUnqualifiedType();
10380 }
10381
10382 if (getCanonicalType(retType) != LRetType)
10383 allLTypes = false;
10384 if (getCanonicalType(retType) != RRetType)
10385 allRTypes = false;
10386
10387 // FIXME: double check this
10388 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
10389 // rbase->getRegParmAttr() != 0 &&
10390 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
10391 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
10392 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
10393
10394 // Compatible functions must have compatible calling conventions
10395 if (lbaseInfo.getCC() != rbaseInfo.getCC())
10396 return {};
10397
10398 // Regparm is part of the calling convention.
10399 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
10400 return {};
10401 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
10402 return {};
10403
10404 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
10405 return {};
10406 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
10407 return {};
10408 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
10409 return {};
10410
10411 // When merging declarations, it's common for supplemental information like
10412 // attributes to only be present in one of the declarations, and we generally
10413 // want type merging to preserve the union of information. So a merged
10414 // function type should be noreturn if it was noreturn in *either* operand
10415 // type.
10416 //
10417 // But for the conditional operator, this is backwards. The result of the
10418 // operator could be either operand, and its type should conservatively
10419 // reflect that. So a function type in a composite type is noreturn only
10420 // if it's noreturn in *both* operand types.
10421 //
10422 // Arguably, noreturn is a kind of subtype, and the conditional operator
10423 // ought to produce the most specific common supertype of its operand types.
10424 // That would differ from this rule in contravariant positions. However,
10425 // neither C nor C++ generally uses this kind of subtype reasoning. Also,
10426 // as a practical matter, it would only affect C code that does abstraction of
10427 // higher-order functions (taking noreturn callbacks!), which is uncommon to
10428 // say the least. So we use the simpler rule.
10429 bool NoReturn = IsConditionalOperator
10430 ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
10431 : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
10432 if (lbaseInfo.getNoReturn() != NoReturn)
10433 allLTypes = false;
10434 if (rbaseInfo.getNoReturn() != NoReturn)
10435 allRTypes = false;
10436
10437 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
10438
10439 if (lproto && rproto) { // two C99 style function prototypes
10440 assert((AllowCXX ||
10441 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
10442 "C++ shouldn't be here");
10443 // Compatible functions must have the same number of parameters
10444 if (lproto->getNumParams() != rproto->getNumParams())
10445 return {};
10446
10447 // Variadic and non-variadic functions aren't compatible
10448 if (lproto->isVariadic() != rproto->isVariadic())
10449 return {};
10450
10451 if (lproto->getMethodQuals() != rproto->getMethodQuals())
10452 return {};
10453
10455 bool canUseLeft, canUseRight;
10456 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
10457 newParamInfos))
10458 return {};
10459
10460 if (!canUseLeft)
10461 allLTypes = false;
10462 if (!canUseRight)
10463 allRTypes = false;
10464
10465 // Check parameter type compatibility
10467 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
10468 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
10469 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
10471 lParamType, rParamType, OfBlockPointer, Unqualified);
10472 if (paramType.isNull())
10473 return {};
10474
10475 if (Unqualified)
10476 paramType = paramType.getUnqualifiedType();
10477
10478 types.push_back(paramType);
10479 if (Unqualified) {
10480 lParamType = lParamType.getUnqualifiedType();
10481 rParamType = rParamType.getUnqualifiedType();
10482 }
10483
10484 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
10485 allLTypes = false;
10486 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
10487 allRTypes = false;
10488 }
10489
10490 if (allLTypes) return lhs;
10491 if (allRTypes) return rhs;
10492
10493 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
10494 EPI.ExtInfo = einfo;
10495 EPI.ExtParameterInfos =
10496 newParamInfos.empty() ? nullptr : newParamInfos.data();
10497 return getFunctionType(retType, types, EPI);
10498 }
10499
10500 if (lproto) allRTypes = false;
10501 if (rproto) allLTypes = false;
10502
10503 const FunctionProtoType *proto = lproto ? lproto : rproto;
10504 if (proto) {
10505 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
10506 if (proto->isVariadic())
10507 return {};
10508 // Check that the types are compatible with the types that
10509 // would result from default argument promotions (C99 6.7.5.3p15).
10510 // The only types actually affected are promotable integer
10511 // types and floats, which would be passed as a different
10512 // type depending on whether the prototype is visible.
10513 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
10514 QualType paramTy = proto->getParamType(i);
10515
10516 // Look at the converted type of enum types, since that is the type used
10517 // to pass enum values.
10518 if (const auto *Enum = paramTy->getAs<EnumType>()) {
10519 paramTy = Enum->getDecl()->getIntegerType();
10520 if (paramTy.isNull())
10521 return {};
10522 }
10523
10524 if (isPromotableIntegerType(paramTy) ||
10525 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
10526 return {};
10527 }
10528
10529 if (allLTypes) return lhs;
10530 if (allRTypes) return rhs;
10531
10533 EPI.ExtInfo = einfo;
10534 return getFunctionType(retType, proto->getParamTypes(), EPI);
10535 }
10536
10537 if (allLTypes) return lhs;
10538 if (allRTypes) return rhs;
10539 return getFunctionNoProtoType(retType, einfo);
10540}
10541
10542/// Given that we have an enum type and a non-enum type, try to merge them.
10544 QualType other, bool isBlockReturnType) {
10545 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
10546 // a signed integer type, or an unsigned integer type.
10547 // Compatibility is based on the underlying type, not the promotion
10548 // type.
10549 QualType underlyingType = ET->getDecl()->getIntegerType();
10550 if (underlyingType.isNull())
10551 return {};
10552 if (Context.hasSameType(underlyingType, other))
10553 return other;
10554
10555 // In block return types, we're more permissive and accept any
10556 // integral type of the same size.
10557 if (isBlockReturnType && other->isIntegerType() &&
10558 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
10559 return other;
10560
10561 return {};
10562}
10563
10564QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
10565 bool Unqualified, bool BlockReturnType,
10566 bool IsConditionalOperator) {
10567 // For C++ we will not reach this code with reference types (see below),
10568 // for OpenMP variant call overloading we might.
10569 //
10570 // C++ [expr]: If an expression initially has the type "reference to T", the
10571 // type is adjusted to "T" prior to any further analysis, the expression
10572 // designates the object or function denoted by the reference, and the
10573 // expression is an lvalue unless the reference is an rvalue reference and
10574 // the expression is a function call (possibly inside parentheses).
10575 auto *LHSRefTy = LHS->getAs<ReferenceType>();
10576 auto *RHSRefTy = RHS->getAs<ReferenceType>();
10577 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
10578 LHS->getTypeClass() == RHS->getTypeClass())
10579 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(),
10580 OfBlockPointer, Unqualified, BlockReturnType);
10581 if (LHSRefTy || RHSRefTy)
10582 return {};
10583
10584 if (Unqualified) {
10585 LHS = LHS.getUnqualifiedType();
10586 RHS = RHS.getUnqualifiedType();
10587 }
10588
10589 QualType LHSCan = getCanonicalType(LHS),
10590 RHSCan = getCanonicalType(RHS);
10591
10592 // If two types are identical, they are compatible.
10593 if (LHSCan == RHSCan)
10594 return LHS;
10595
10596 // If the qualifiers are different, the types aren't compatible... mostly.
10597 Qualifiers LQuals = LHSCan.getLocalQualifiers();
10598 Qualifiers RQuals = RHSCan.getLocalQualifiers();
10599 if (LQuals != RQuals) {
10600 // If any of these qualifiers are different, we have a type
10601 // mismatch.
10602 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
10603 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
10604 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
10605 LQuals.hasUnaligned() != RQuals.hasUnaligned())
10606 return {};
10607
10608 // Exactly one GC qualifier difference is allowed: __strong is
10609 // okay if the other type has no GC qualifier but is an Objective
10610 // C object pointer (i.e. implicitly strong by default). We fix
10611 // this by pretending that the unqualified type was actually
10612 // qualified __strong.
10613 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
10614 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
10615 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
10616
10617 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
10618 return {};
10619
10620 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
10622 }
10623 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
10625 }
10626 return {};
10627 }
10628
10629 // Okay, qualifiers are equal.
10630
10631 Type::TypeClass LHSClass = LHSCan->getTypeClass();
10632 Type::TypeClass RHSClass = RHSCan->getTypeClass();
10633
10634 // We want to consider the two function types to be the same for these
10635 // comparisons, just force one to the other.
10636 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
10637 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
10638
10639 // Same as above for arrays
10640 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
10641 LHSClass = Type::ConstantArray;
10642 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
10643 RHSClass = Type::ConstantArray;
10644
10645 // ObjCInterfaces are just specialized ObjCObjects.
10646 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
10647 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
10648
10649 // Canonicalize ExtVector -> Vector.
10650 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
10651 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
10652
10653 // If the canonical type classes don't match.
10654 if (LHSClass != RHSClass) {
10655 // Note that we only have special rules for turning block enum
10656 // returns into block int returns, not vice-versa.
10657 if (const auto *ETy = LHS->getAs<EnumType>()) {
10658 return mergeEnumWithInteger(*this, ETy, RHS, false);
10659 }
10660 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
10661 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
10662 }
10663 // allow block pointer type to match an 'id' type.
10664 if (OfBlockPointer && !BlockReturnType) {
10665 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
10666 return LHS;
10667 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
10668 return RHS;
10669 }
10670 // Allow __auto_type to match anything; it merges to the type with more
10671 // information.
10672 if (const auto *AT = LHS->getAs<AutoType>()) {
10673 if (!AT->isDeduced() && AT->isGNUAutoType())
10674 return RHS;
10675 }
10676 if (const auto *AT = RHS->getAs<AutoType>()) {
10677 if (!AT->isDeduced() && AT->isGNUAutoType())
10678 return LHS;
10679 }
10680 return {};
10681 }
10682
10683 // The canonical type classes match.
10684 switch (LHSClass) {
10685#define TYPE(Class, Base)
10686#define ABSTRACT_TYPE(Class, Base)
10687#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
10688#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
10689#define DEPENDENT_TYPE(Class, Base) case Type::Class:
10690#include "clang/AST/TypeNodes.inc"
10691 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
10692
10693 case Type::Auto:
10694 case Type::DeducedTemplateSpecialization:
10695 case Type::LValueReference:
10696 case Type::RValueReference:
10697 case Type::MemberPointer:
10698 llvm_unreachable("C++ should never be in mergeTypes");
10699
10700 case Type::ObjCInterface:
10701 case Type::IncompleteArray:
10702 case Type::VariableArray:
10703 case Type::FunctionProto:
10704 case Type::ExtVector:
10705 llvm_unreachable("Types are eliminated above");
10706
10707 case Type::Pointer:
10708 {
10709 // Merge two pointer types, while trying to preserve typedef info
10710 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
10711 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
10712 if (Unqualified) {
10713 LHSPointee = LHSPointee.getUnqualifiedType();
10714 RHSPointee = RHSPointee.getUnqualifiedType();
10715 }
10716 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
10717 Unqualified);
10718 if (ResultType.isNull())
10719 return {};
10720 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
10721 return LHS;
10722 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
10723 return RHS;
10724 return getPointerType(ResultType);
10725 }
10726 case Type::BlockPointer:
10727 {
10728 // Merge two block pointer types, while trying to preserve typedef info
10729 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
10730 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
10731 if (Unqualified) {
10732 LHSPointee = LHSPointee.getUnqualifiedType();
10733 RHSPointee = RHSPointee.getUnqualifiedType();
10734 }
10735 if (getLangOpts().OpenCL) {
10736 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
10737 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
10738 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
10739 // 6.12.5) thus the following check is asymmetric.
10740 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
10741 return {};
10742 LHSPteeQual.removeAddressSpace();
10743 RHSPteeQual.removeAddressSpace();
10744 LHSPointee =
10745 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
10746 RHSPointee =
10747 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
10748 }
10749 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
10750 Unqualified);
10751 if (ResultType.isNull())
10752 return {};
10753 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
10754 return LHS;
10755 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
10756 return RHS;
10757 return getBlockPointerType(ResultType);
10758 }
10759 case Type::Atomic:
10760 {
10761 // Merge two pointer types, while trying to preserve typedef info
10762 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
10763 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
10764 if (Unqualified) {
10765 LHSValue = LHSValue.getUnqualifiedType();
10766 RHSValue = RHSValue.getUnqualifiedType();
10767 }
10768 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
10769 Unqualified);
10770 if (ResultType.isNull())
10771 return {};
10772 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
10773 return LHS;
10774 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
10775 return RHS;
10776 return getAtomicType(ResultType);
10777 }
10778 case Type::ConstantArray:
10779 {
10780 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
10781 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
10782 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
10783 return {};
10784
10785 QualType LHSElem = getAsArrayType(LHS)->getElementType();
10786 QualType RHSElem = getAsArrayType(RHS)->getElementType();
10787 if (Unqualified) {
10788 LHSElem = LHSElem.getUnqualifiedType();
10789 RHSElem = RHSElem.getUnqualifiedType();
10790 }
10791
10792 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
10793 if (ResultType.isNull())
10794 return {};
10795
10796 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
10797 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
10798
10799 // If either side is a variable array, and both are complete, check whether
10800 // the current dimension is definite.
10801 if (LVAT || RVAT) {
10802 auto SizeFetch = [this](const VariableArrayType* VAT,
10803 const ConstantArrayType* CAT)
10804 -> std::pair<bool,llvm::APInt> {
10805 if (VAT) {
10806 std::optional<llvm::APSInt> TheInt;
10807 Expr *E = VAT->getSizeExpr();
10808 if (E && (TheInt = E->getIntegerConstantExpr(*this)))
10809 return std::make_pair(true, *TheInt);
10810 return std::make_pair(false, llvm::APSInt());
10811 }
10812 if (CAT)
10813 return std::make_pair(true, CAT->getSize());
10814 return std::make_pair(false, llvm::APInt());
10815 };
10816
10817 bool HaveLSize, HaveRSize;
10818 llvm::APInt LSize, RSize;
10819 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
10820 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
10821 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
10822 return {}; // Definite, but unequal, array dimension
10823 }
10824
10825 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
10826 return LHS;
10827 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
10828 return RHS;
10829 if (LCAT)
10830 return getConstantArrayType(ResultType, LCAT->getSize(),
10831 LCAT->getSizeExpr(), ArraySizeModifier(), 0);
10832 if (RCAT)
10833 return getConstantArrayType(ResultType, RCAT->getSize(),
10834 RCAT->getSizeExpr(), ArraySizeModifier(), 0);
10835 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
10836 return LHS;
10837 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
10838 return RHS;
10839 if (LVAT) {
10840 // FIXME: This isn't correct! But tricky to implement because
10841 // the array's size has to be the size of LHS, but the type
10842 // has to be different.
10843 return LHS;
10844 }
10845 if (RVAT) {
10846 // FIXME: This isn't correct! But tricky to implement because
10847 // the array's size has to be the size of RHS, but the type
10848 // has to be different.
10849 return RHS;
10850 }
10851 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
10852 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
10853 return getIncompleteArrayType(ResultType, ArraySizeModifier(), 0);
10854 }
10855 case Type::FunctionNoProto:
10856 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified,
10857 /*AllowCXX=*/false, IsConditionalOperator);
10858 case Type::Record:
10859 case Type::Enum:
10860 return {};
10861 case Type::Builtin:
10862 // Only exactly equal builtin types are compatible, which is tested above.
10863 return {};
10864 case Type::Complex:
10865 // Distinct complex types are incompatible.
10866 return {};
10867 case Type::Vector:
10868 // FIXME: The merged type should be an ExtVector!
10869 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
10870 RHSCan->castAs<VectorType>()))
10871 return LHS;
10872 return {};
10873 case Type::ConstantMatrix:
10875 RHSCan->castAs<ConstantMatrixType>()))
10876 return LHS;
10877 return {};
10878 case Type::ObjCObject: {
10879 // Check if the types are assignment compatible.
10880 // FIXME: This should be type compatibility, e.g. whether
10881 // "LHS x; RHS x;" at global scope is legal.
10883 RHS->castAs<ObjCObjectType>()))
10884 return LHS;
10885 return {};
10886 }
10887 case Type::ObjCObjectPointer:
10888 if (OfBlockPointer) {
10891 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
10892 return LHS;
10893 return {};
10894 }
10897 return LHS;
10898 return {};
10899 case Type::Pipe:
10900 assert(LHS != RHS &&
10901 "Equivalent pipe types should have already been handled!");
10902 return {};
10903 case Type::BitInt: {
10904 // Merge two bit-precise int types, while trying to preserve typedef info.
10905 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
10906 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
10907 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
10908 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
10909
10910 // Like unsigned/int, shouldn't have a type if they don't match.
10911 if (LHSUnsigned != RHSUnsigned)
10912 return {};
10913
10914 if (LHSBits != RHSBits)
10915 return {};
10916 return LHS;
10917 }
10918 }
10919
10920 llvm_unreachable("Invalid Type::Class!");
10921}
10922
10924 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
10925 bool &CanUseFirst, bool &CanUseSecond,
10927 assert(NewParamInfos.empty() && "param info list not empty");
10928 CanUseFirst = CanUseSecond = true;
10929 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
10930 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
10931
10932 // Fast path: if the first type doesn't have ext parameter infos,
10933 // we match if and only if the second type also doesn't have them.
10934 if (!FirstHasInfo && !SecondHasInfo)
10935 return true;
10936
10937 bool NeedParamInfo = false;
10938 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
10939 : SecondFnType->getExtParameterInfos().size();
10940
10941 for (size_t I = 0; I < E; ++I) {
10942 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
10943 if (FirstHasInfo)
10944 FirstParam = FirstFnType->getExtParameterInfo(I);
10945 if (SecondHasInfo)
10946 SecondParam = SecondFnType->getExtParameterInfo(I);
10947
10948 // Cannot merge unless everything except the noescape flag matches.
10949 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
10950 return false;
10951
10952 bool FirstNoEscape = FirstParam.isNoEscape();
10953 bool SecondNoEscape = SecondParam.isNoEscape();
10954 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
10955 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
10956 if (NewParamInfos.back().getOpaqueValue())
10957 NeedParamInfo = true;
10958 if (FirstNoEscape != IsNoEscape)
10959 CanUseFirst = false;
10960 if (SecondNoEscape != IsNoEscape)
10961 CanUseSecond = false;
10962 }
10963
10964 if (!NeedParamInfo)
10965 NewParamInfos.clear();
10966
10967 return true;
10968}
10969
10971 ObjCLayouts[CD] = nullptr;
10972}
10973
10974/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
10975/// 'RHS' attributes and returns the merged version; including for function
10976/// return types.
10978 QualType LHSCan = getCanonicalType(LHS),
10979 RHSCan = getCanonicalType(RHS);
10980 // If two types are identical, they are compatible.
10981 if (LHSCan == RHSCan)
10982 return LHS;
10983 if (RHSCan->isFunctionType()) {
10984 if (!LHSCan->isFunctionType())
10985 return {};
10986 QualType OldReturnType =
10987 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
10988 QualType NewReturnType =
10989 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
10990 QualType ResReturnType =
10991 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
10992 if (ResReturnType.isNull())
10993 return {};
10994 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
10995 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
10996 // In either case, use OldReturnType to build the new function type.
10997 const auto *F = LHS->castAs<FunctionType>();
10998 if (const auto *FPT = cast<FunctionProtoType>(F)) {
10999 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11000 EPI.ExtInfo = getFunctionExtInfo(LHS);
11001 QualType ResultType =
11002 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
11003 return ResultType;
11004 }
11005 }
11006 return {};
11007 }
11008
11009 // If the qualifiers are different, the types can still be merged.
11010 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11011 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11012 if (LQuals != RQuals) {
11013 // If any of these qualifiers are different, we have a type mismatch.
11014 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11015 LQuals.getAddressSpace() != RQuals.getAddressSpace())
11016 return {};
11017
11018 // Exactly one GC qualifier difference is allowed: __strong is
11019 // okay if the other type has no GC qualifier but is an Objective
11020 // C object pointer (i.e. implicitly strong by default). We fix
11021 // this by pretending that the unqualified type was actually
11022 // qualified __strong.
11023 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11024 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11025 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11026
11027 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
11028 return {};
11029
11030 if (GC_L == Qualifiers::Strong)
11031 return LHS;
11032 if (GC_R == Qualifiers::Strong)
11033 return RHS;
11034 return {};
11035 }
11036
11037 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
11038 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
11039 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
11040 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
11041 if (ResQT == LHSBaseQT)
11042 return LHS;
11043 if (ResQT == RHSBaseQT)
11044 return RHS;
11045 }
11046 return {};
11047}
11048
11049//===----------------------------------------------------------------------===//
11050// Integer Predicates
11051//===----------------------------------------------------------------------===//
11052
11054 if (const auto *ET = T->getAs<EnumType>())
11055 T = ET->getDecl()->getIntegerType();
11056 if (T->isBooleanType())
11057 return 1;
11058 if (const auto *EIT = T->getAs<BitIntType>())
11059 return EIT->getNumBits();
11060 // For builtin types, just use the standard type sizing method
11061 return (unsigned)getTypeSize(T);
11062}
11063
11065 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
11066 T->isFixedPointType()) &&
11067 "Unexpected type");
11068
11069 // Turn <4 x signed int> -> <4 x unsigned int>
11070 if (const auto *VTy = T->getAs<VectorType>())
11071 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
11072 VTy->getNumElements(), VTy->getVectorKind());
11073
11074 // For _BitInt, return an unsigned _BitInt with same width.
11075 if (const auto *EITy = T->getAs<BitIntType>())
11076 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits());
11077
11078 // For enums, get the underlying integer type of the enum, and let the general
11079 // integer type signchanging code handle it.
11080 if (const auto *ETy = T->getAs<EnumType>())
11081 T = ETy->getDecl()->getIntegerType();
11082
11083 switch (T->castAs<BuiltinType>()->getKind()) {
11084 case BuiltinType::Char_U:
11085 // Plain `char` is mapped to `unsigned char` even if it's already unsigned
11086 case BuiltinType::Char_S:
11087 case BuiltinType::SChar:
11088 case BuiltinType::Char8:
11089 return UnsignedCharTy;
11090 case BuiltinType::Short:
11091 return UnsignedShortTy;
11092 case BuiltinType::Int:
11093 return UnsignedIntTy;
11094 case BuiltinType::Long:
11095 return UnsignedLongTy;
11096 case BuiltinType::LongLong:
11097 return UnsignedLongLongTy;
11098 case BuiltinType::Int128:
11099 return UnsignedInt128Ty;
11100 // wchar_t is special. It is either signed or not, but when it's signed,
11101 // there's no matching "unsigned wchar_t". Therefore we return the unsigned
11102 // version of its underlying type instead.
11103 case BuiltinType::WChar_S:
11104 return getUnsignedWCharType();
11105
11106 case BuiltinType::ShortAccum:
11107 return UnsignedShortAccumTy;
11108 case BuiltinType::Accum:
11109 return UnsignedAccumTy;
11110 case BuiltinType::LongAccum:
11111 return UnsignedLongAccumTy;
11112 case BuiltinType::SatShortAccum:
11114 case BuiltinType::SatAccum:
11115 return SatUnsignedAccumTy;
11116 case BuiltinType::SatLongAccum:
11118 case BuiltinType::ShortFract:
11119 return UnsignedShortFractTy;
11120 case BuiltinType::Fract:
11121 return UnsignedFractTy;
11122 case BuiltinType::LongFract:
11123 return UnsignedLongFractTy;
11124 case BuiltinType::SatShortFract:
11126 case BuiltinType::SatFract:
11127 return SatUnsignedFractTy;
11128 case BuiltinType::SatLongFract:
11130 default:
11131 assert((T->hasUnsignedIntegerRepresentation() ||
11133 "Unexpected signed integer or fixed point type");
11134 return T;
11135 }
11136}
11137
11139 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
11140 T->isFixedPointType()) &&
11141 "Unexpected type");
11142
11143 // Turn <4 x unsigned int> -> <4 x signed int>
11144 if (const auto *VTy = T->getAs<VectorType>())
11145 return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
11146 VTy->getNumElements(), VTy->getVectorKind());
11147
11148 // For _BitInt, return a signed _BitInt with same width.
11149 if (const auto *EITy = T->getAs<BitIntType>())
11150 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits());
11151
11152 // For enums, get the underlying integer type of the enum, and let the general
11153 // integer type signchanging code handle it.
11154 if (const auto *ETy = T->getAs<EnumType>())
11155 T = ETy->getDecl()->getIntegerType();
11156
11157 switch (T->castAs<BuiltinType>()->getKind()) {
11158 case BuiltinType::Char_S:
11159 // Plain `char` is mapped to `signed char` even if it's already signed
11160 case BuiltinType::Char_U:
11161 case BuiltinType::UChar:
11162 case BuiltinType::Char8:
11163 return SignedCharTy;
11164 case BuiltinType::UShort:
11165 return ShortTy;
11166 case BuiltinType::UInt:
11167 return IntTy;
11168 case BuiltinType::ULong:
11169 return LongTy;
11170 case BuiltinType::ULongLong:
11171 return LongLongTy;
11172 case BuiltinType::UInt128:
11173 return Int128Ty;
11174 // wchar_t is special. It is either unsigned or not, but when it's unsigned,
11175 // there's no matching "signed wchar_t". Therefore we return the signed
11176 // version of its underlying type instead.
11177 case BuiltinType::WChar_U:
11178 return getSignedWCharType();
11179
11180 case BuiltinType::UShortAccum:
11181 return ShortAccumTy;
11182 case BuiltinType::UAccum:
11183 return AccumTy;
11184 case BuiltinType::ULongAccum:
11185 return LongAccumTy;
11186 case BuiltinType::SatUShortAccum:
11187 return SatShortAccumTy;
11188 case BuiltinType::SatUAccum:
11189 return SatAccumTy;
11190 case BuiltinType::SatULongAccum:
11191 return SatLongAccumTy;
11192 case BuiltinType::UShortFract:
11193 return ShortFractTy;
11194 case BuiltinType::UFract:
11195 return FractTy;
11196 case BuiltinType::ULongFract:
11197 return LongFractTy;
11198 case BuiltinType::SatUShortFract:
11199 return SatShortFractTy;
11200 case BuiltinType::SatUFract:
11201 return SatFractTy;
11202 case BuiltinType::SatULongFract:
11203 return SatLongFractTy;
11204 default:
11205 assert(
11207 "Unexpected signed integer or fixed point type");
11208 return T;
11209 }
11210}
11211
11213
11215 QualType ReturnType) {}
11216
11217//===----------------------------------------------------------------------===//
11218// Builtin Type Computation
11219//===----------------------------------------------------------------------===//
11220
11221/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
11222/// pointer over the consumed characters. This returns the resultant type. If
11223/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
11224/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
11225/// a vector of "i*".
11226///
11227/// RequiresICE is filled in on return to indicate whether the value is required
11228/// to be an Integer Constant Expression.
11229static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
11231 bool &RequiresICE,
11232 bool AllowTypeModifiers) {
11233 // Modifiers.
11234 int HowLong = 0;
11235 bool Signed = false, Unsigned = false;
11236 RequiresICE = false;
11237
11238 // Read the prefixed modifiers first.
11239 bool Done = false;
11240 #ifndef NDEBUG
11241 bool IsSpecial = false;
11242 #endif
11243 while (!Done) {
11244 switch (*Str++) {
11245 default: Done = true; --Str; break;
11246 case 'I':
11247 RequiresICE = true;
11248 break;
11249 case 'S':
11250 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
11251 assert(!Signed && "Can't use 'S' modifier multiple times!");
11252 Signed = true;
11253 break;
11254 case 'U':
11255 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
11256 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
11257 Unsigned = true;
11258 break;
11259 case 'L':
11260 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
11261 assert(HowLong <= 2 && "Can't have LLLL modifier");
11262 ++HowLong;
11263 break;
11264 case 'N':
11265 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
11266 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
11267 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
11268 #ifndef NDEBUG
11269 IsSpecial = true;
11270 #endif
11271 if (Context.getTargetInfo().getLongWidth() == 32)
11272 ++HowLong;
11273 break;
11274 case 'W':
11275 // This modifier represents int64 type.
11276 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
11277 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
11278 #ifndef NDEBUG
11279 IsSpecial = true;
11280 #endif
11281 switch (Context.getTargetInfo().getInt64Type()) {
11282 default:
11283 llvm_unreachable("Unexpected integer type");
11285 HowLong = 1;
11286 break;
11288 HowLong = 2;
11289 break;
11290 }
11291 break;
11292 case 'Z':
11293 // This modifier represents int32 type.
11294 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
11295 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
11296 #ifndef NDEBUG
11297 IsSpecial = true;
11298 #endif
11299 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
11300 default:
11301 llvm_unreachable("Unexpected integer type");
11303 HowLong = 0;
11304 break;
11306 HowLong = 1;
11307 break;
11309 HowLong = 2;
11310 break;
11311 }
11312 break;
11313 case 'O':
11314 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
11315 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
11316 #ifndef NDEBUG
11317 IsSpecial = true;
11318 #endif
11319 if (Context.getLangOpts().OpenCL)
11320 HowLong = 1;
11321 else
11322 HowLong = 2;
11323 break;
11324 }
11325 }
11326
11327 QualType Type;
11328
11329 // Read the base type.
11330 switch (*Str++) {
11331 default: llvm_unreachable("Unknown builtin type letter!");
11332 case 'x':
11333 assert(HowLong == 0 && !Signed && !Unsigned &&
11334 "Bad modifiers used with 'x'!");
11335 Type = Context.Float16Ty;
11336 break;
11337 case 'y':
11338 assert(HowLong == 0 && !Signed && !Unsigned &&
11339 "Bad modifiers used with 'y'!");
11340 Type = Context.BFloat16Ty;
11341 break;
11342 case 'v':
11343 assert(HowLong == 0 && !Signed && !Unsigned &&
11344 "Bad modifiers used with 'v'!");
11345 Type = Context.VoidTy;
11346 break;
11347 case 'h':
11348 assert(HowLong == 0 && !Signed && !Unsigned &&
11349 "Bad modifiers used with 'h'!");
11350 Type = Context.HalfTy;
11351 break;
11352 case 'f':
11353 assert(HowLong == 0 && !Signed && !Unsigned &&
11354 "Bad modifiers used with 'f'!");
11355 Type = Context.FloatTy;
11356 break;
11357 case 'd':
11358 assert(HowLong < 3 && !Signed && !Unsigned &&
11359 "Bad modifiers used with 'd'!");
11360 if (HowLong == 1)
11361 Type = Context.LongDoubleTy;
11362 else if (HowLong == 2)
11363 Type = Context.Float128Ty;
11364 else
11365 Type = Context.DoubleTy;
11366 break;
11367 case 's':
11368 assert(HowLong == 0 && "Bad modifiers used with 's'!");
11369 if (Unsigned)
11370 Type = Context.UnsignedShortTy;
11371 else
11372 Type = Context.ShortTy;
11373 break;
11374 case 'i':
11375 if (HowLong == 3)
11376 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
11377 else if (HowLong == 2)
11378 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
11379 else if (HowLong == 1)
11380 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
11381 else
11382 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
11383 break;
11384 case 'c':
11385 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
11386 if (Signed)
11387 Type = Context.SignedCharTy;
11388 else if (Unsigned)
11389 Type = Context.UnsignedCharTy;
11390 else
11391 Type = Context.CharTy;
11392 break;
11393 case 'b': // boolean
11394 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
11395 Type = Context.BoolTy;
11396 break;
11397 case 'z': // size_t.
11398 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
11399 Type = Context.getSizeType();
11400 break;
11401 case 'w': // wchar_t.
11402 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
11403 Type = Context.getWideCharType();
11404 break;
11405 case 'F':
11406 Type = Context.getCFConstantStringType();
11407 break;
11408 case 'G':
11409 Type = Context.getObjCIdType();
11410 break;
11411 case 'H':
11412 Type = Context.getObjCSelType();
11413 break;
11414 case 'M':
11415 Type = Context.getObjCSuperType();
11416 break;
11417 case 'a':
11418 Type = Context.getBuiltinVaListType();
11419 assert(!Type.isNull() && "builtin va list type not initialized!");
11420 break;
11421 case 'A':
11422 // This is a "reference" to a va_list; however, what exactly
11423 // this means depends on how va_list is defined. There are two
11424 // different kinds of va_list: ones passed by value, and ones
11425 // passed by reference. An example of a by-value va_list is
11426 // x86, where va_list is a char*. An example of by-ref va_list
11427 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
11428 // we want this argument to be a char*&; for x86-64, we want
11429 // it to be a __va_list_tag*.
11430 Type = Context.getBuiltinVaListType();
11431 assert(!Type.isNull() && "builtin va list type not initialized!");
11432 if (Type->isArrayType())
11433 Type = Context.getArrayDecayedType(Type);
11434 else
11435 Type = Context.getLValueReferenceType(Type);
11436 break;
11437 case 'q': {
11438 char *End;
11439 unsigned NumElements = strtoul(Str, &End, 10);
11440 assert(End != Str && "Missing vector size");
11441 Str = End;
11442
11443 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
11444 RequiresICE, false);
11445 assert(!RequiresICE && "Can't require vector ICE");
11446
11447 Type = Context.getScalableVectorType(ElementType, NumElements);
11448 break;
11449 }
11450 case 'Q': {
11451 switch (*Str++) {
11452 case 'a': {
11453 Type = Context.SveCountTy;
11454 break;
11455 }
11456 default:
11457 llvm_unreachable("Unexpected target builtin type");
11458 }
11459 break;
11460 }
11461 case 'V': {
11462 char *End;
11463 unsigned NumElements = strtoul(Str, &End, 10);
11464 assert(End != Str && "Missing vector size");
11465 Str = End;
11466
11467 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
11468 RequiresICE, false);
11469 assert(!RequiresICE && "Can't require vector ICE");
11470
11471 // TODO: No way to make AltiVec vectors in builtins yet.
11472 Type = Context.getVectorType(ElementType, NumElements, VectorKind::Generic);
11473 break;
11474 }
11475 case 'E': {
11476 char *End;
11477
11478 unsigned NumElements = strtoul(Str, &End, 10);
11479 assert(End != Str && "Missing vector size");
11480
11481 Str = End;
11482
11483 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
11484 false);
11485 Type = Context.getExtVectorType(ElementType, NumElements);
11486 break;
11487 }
11488 case 'X': {
11489 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
11490 false);
11491 assert(!RequiresICE && "Can't require complex ICE");
11492 Type = Context.getComplexType(ElementType);
11493 break;
11494 }
11495 case 'Y':
11496 Type = Context.getPointerDiffType();
11497 break;
11498 case 'P':
11499 Type = Context.getFILEType();
11500 if (Type.isNull()) {
11502 return {};
11503 }
11504 break;
11505 case 'J':
11506 if (Signed)
11507 Type = Context.getsigjmp_bufType();
11508 else
11509 Type = Context.getjmp_bufType();
11510
11511 if (Type.isNull()) {
11513 return {};
11514 }
11515 break;
11516 case 'K':
11517 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
11518 Type = Context.getucontext_tType();
11519
11520 if (Type.isNull()) {
11522 return {};
11523 }
11524 break;
11525 case 'p':
11526 Type = Context.getProcessIDType();
11527 break;
11528 }
11529
11530 // If there are modifiers and if we're allowed to parse them, go for it.
11531 Done = !AllowTypeModifiers;
11532 while (!Done) {
11533 switch (char c = *Str++) {
11534 default: Done = true; --Str; break;
11535 case '*':
11536 case '&': {
11537 // Both pointers and references can have their pointee types
11538 // qualified with an address space.
11539 char *End;
11540 unsigned AddrSpace = strtoul(Str, &End, 10);
11541 if (End != Str) {
11542 // Note AddrSpace == 0 is not the same as an unspecified address space.
11543 Type = Context.getAddrSpaceQualType(
11544 Type,
11545 Context.getLangASForBuiltinAddressSpace(AddrSpace));
11546 Str = End;
11547 }
11548 if (c == '*')
11549 Type = Context.getPointerType(Type);
11550 else
11551 Type = Context.getLValueReferenceType(Type);
11552 break;
11553 }
11554 // FIXME: There's no way to have a built-in with an rvalue ref arg.
11555 case 'C':
11556 Type = Type.withConst();
11557 break;
11558 case 'D':
11559 Type = Context.getVolatileType(Type);
11560 break;
11561 case 'R':
11562 Type = Type.withRestrict();
11563 break;
11564 }
11565 }
11566
11567 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
11568 "Integer constant 'I' type must be an integer");
11569
11570 return Type;
11571}
11572
11573// On some targets such as PowerPC, some of the builtins are defined with custom
11574// type descriptors for target-dependent types. These descriptors are decoded in
11575// other functions, but it may be useful to be able to fall back to default
11576// descriptor decoding to define builtins mixing target-dependent and target-
11577// independent types. This function allows decoding one type descriptor with
11578// default decoding.
11579QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
11580 GetBuiltinTypeError &Error, bool &RequireICE,
11581 bool AllowTypeModifiers) const {
11582 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
11583}
11584
11585/// GetBuiltinType - Return the type for the specified builtin.
11587 GetBuiltinTypeError &Error,
11588 unsigned *IntegerConstantArgs) const {
11589 const char *TypeStr = BuiltinInfo.getTypeString(Id);
11590 if (TypeStr[0] == '\0') {
11591 Error = GE_Missing_type;
11592 return {};
11593 }
11594
11595 SmallVector<QualType, 8> ArgTypes;
11596
11597 bool RequiresICE = false;
11598 Error = GE_None;
11599 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
11600 RequiresICE, true);
11601 if (Error != GE_None)
11602 return {};
11603
11604 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
11605
11606 while (TypeStr[0] && TypeStr[0] != '.') {
11607 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
11608 if (Error != GE_None)
11609 return {};
11610
11611 // If this argument is required to be an IntegerConstantExpression and the
11612 // caller cares, fill in the bitmask we return.
11613 if (RequiresICE && IntegerConstantArgs)
11614 *IntegerConstantArgs |= 1 << ArgTypes.size();
11615
11616 // Do array -> pointer decay. The builtin should use the decayed type.
11617 if (Ty->isArrayType())
11618 Ty = getArrayDecayedType(Ty);
11619
11620 ArgTypes.push_back(Ty);
11621 }
11622
11623 if (Id == Builtin::BI__GetExceptionInfo)
11624 return {};
11625
11626 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
11627 "'.' should only occur at end of builtin type list!");
11628
11629 bool Variadic = (TypeStr[0] == '.');
11630
11632 Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
11633 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
11634
11635
11636 // We really shouldn't be making a no-proto type here.
11637 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
11638 return getFunctionNoProtoType(ResType, EI);
11639
11641 EPI.ExtInfo = EI;
11642 EPI.Variadic = Variadic;
11644 EPI.ExceptionSpec.Type =
11646
11647 return getFunctionType(ResType, ArgTypes, EPI);
11648}
11649
11651 const FunctionDecl *FD) {
11652 if (!FD->isExternallyVisible())
11653 return GVA_Internal;
11654
11655 // Non-user-provided functions get emitted as weak definitions with every
11656 // use, no matter whether they've been explicitly instantiated etc.
11657 if (!FD->isUserProvided())
11658 return GVA_DiscardableODR;
11659
11661 switch (FD->getTemplateSpecializationKind()) {
11662 case TSK_Undeclared:
11665 break;
11666
11668 return GVA_StrongODR;
11669
11670 // C++11 [temp.explicit]p10:
11671 // [ Note: The intent is that an inline function that is the subject of
11672 // an explicit instantiation declaration will still be implicitly
11673 // instantiated when used so that the body can be considered for
11674 // inlining, but that no out-of-line copy of the inline function would be
11675 // generated in the translation unit. -- end note ]
11678
11681 break;
11682 }
11683
11684 if (!FD->isInlined())
11685 return External;
11686
11687 if ((!Context.getLangOpts().CPlusPlus &&
11688 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
11689 !FD->hasAttr<DLLExportAttr>()) ||
11690 FD->hasAttr<GNUInlineAttr>()) {
11691 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
11692
11693 // GNU or C99 inline semantics. Determine whether this symbol should be
11694 // externally visible.
11696 return External;
11697
11698 // C99 inline semantics, where the symbol is not externally visible.
11700 }
11701
11702 // Functions specified with extern and inline in -fms-compatibility mode
11703 // forcibly get emitted. While the body of the function cannot be later
11704 // replaced, the function definition cannot be discarded.
11705 if (FD->isMSExternInline())
11706 return GVA_StrongODR;
11707
11708 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
11709 isa<CXXConstructorDecl>(FD) &&
11710 cast<CXXConstructorDecl>(FD)->isInheritingConstructor())
11711 // Our approach to inheriting constructors is fundamentally different from
11712 // that used by the MS ABI, so keep our inheriting constructor thunks
11713 // internal rather than trying to pick an unambiguous mangling for them.
11714 return GVA_Internal;
11715
11716 return GVA_DiscardableODR;
11717}
11718
11720 const Decl *D, GVALinkage L) {
11721 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
11722 // dllexport/dllimport on inline functions.
11723 if (D->hasAttr<DLLImportAttr>()) {
11724 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
11726 } else if (D->hasAttr<DLLExportAttr>()) {
11727 if (L == GVA_DiscardableODR)
11728 return GVA_StrongODR;
11729 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
11730 // Device-side functions with __global__ attribute must always be
11731 // visible externally so they can be launched from host.
11732 if (D->hasAttr<CUDAGlobalAttr>() &&
11733 (L == GVA_DiscardableODR || L == GVA_Internal))
11734 return GVA_StrongODR;
11735 // Single source offloading languages like CUDA/HIP need to be able to
11736 // access static device variables from host code of the same compilation
11737 // unit. This is done by externalizing the static variable with a shared
11738 // name between the host and device compilation which is the same for the
11739 // same compilation unit whereas different among different compilation
11740 // units.
11741 if (Context.shouldExternalize(D))
11742 return GVA_StrongExternal;
11743 }
11744 return L;
11745}
11746
11747/// Adjust the GVALinkage for a declaration based on what an external AST source
11748/// knows about whether there can be other definitions of this declaration.
11749static GVALinkage
11751 GVALinkage L) {
11752 ExternalASTSource *Source = Ctx.getExternalSource();
11753 if (!Source)
11754 return L;
11755
11756 switch (Source->hasExternalDefinitions(D)) {
11758 // Other translation units rely on us to provide the definition.
11759 if (L == GVA_DiscardableODR)
11760 return GVA_StrongODR;
11761 break;
11762
11765
11767 break;
11768 }
11769 return L;
11770}
11771
11775 basicGVALinkageForFunction(*this, FD)));
11776}
11777
11779 const VarDecl *VD) {
11780 // As an extension for interactive REPLs, make sure constant variables are
11781 // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
11782 // marking them as internal.
11783 if (Context.getLangOpts().CPlusPlus &&
11784 Context.getLangOpts().IncrementalExtensions &&
11785 VD->getType().isConstQualified() &&
11786 !VD->getType().isVolatileQualified() && !VD->isInline() &&
11787 !isa<VarTemplateSpecializationDecl>(VD) && !VD->getDescribedVarTemplate())
11788 return GVA_DiscardableODR;
11789
11790 if (!VD->isExternallyVisible())
11791 return GVA_Internal;
11792
11793 if (VD->isStaticLocal()) {
11794 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
11795 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
11796 LexicalContext = LexicalContext->getLexicalParent();
11797
11798 // ObjC Blocks can create local variables that don't have a FunctionDecl
11799 // LexicalContext.
11800 if (!LexicalContext)
11801 return GVA_DiscardableODR;
11802
11803 // Otherwise, let the static local variable inherit its linkage from the
11804 // nearest enclosing function.
11805 auto StaticLocalLinkage =
11806 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
11807
11808 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
11809 // be emitted in any object with references to the symbol for the object it
11810 // contains, whether inline or out-of-line."
11811 // Similar behavior is observed with MSVC. An alternative ABI could use
11812 // StrongODR/AvailableExternally to match the function, but none are
11813 // known/supported currently.
11814 if (StaticLocalLinkage == GVA_StrongODR ||
11815 StaticLocalLinkage == GVA_AvailableExternally)
11816 return GVA_DiscardableODR;
11817 return StaticLocalLinkage;
11818 }
11819
11820 // MSVC treats in-class initialized static data members as definitions.
11821 // By giving them non-strong linkage, out-of-line definitions won't
11822 // cause link errors.
11824 return GVA_DiscardableODR;
11825
11826 // Most non-template variables have strong linkage; inline variables are
11827 // linkonce_odr or (occasionally, for compatibility) weak_odr.
11828 GVALinkage StrongLinkage;
11829 switch (Context.getInlineVariableDefinitionKind(VD)) {
11831 StrongLinkage = GVA_StrongExternal;
11832 break;
11835 StrongLinkage = GVA_DiscardableODR;
11836 break;
11838 StrongLinkage = GVA_StrongODR;
11839 break;
11840 }
11841
11842 switch (VD->getTemplateSpecializationKind()) {
11843 case TSK_Undeclared:
11844 return StrongLinkage;
11845
11847 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
11848 VD->isStaticDataMember()
11850 : StrongLinkage;
11851
11853 return GVA_StrongODR;
11854
11857
11859 return GVA_DiscardableODR;
11860 }
11861
11862 llvm_unreachable("Invalid Linkage!");
11863}
11864
11868 basicGVALinkageForVariable(*this, VD)));
11869}
11870
11872 if (const auto *VD = dyn_cast<VarDecl>(D)) {
11873 if (!VD->isFileVarDecl())
11874 return false;
11875 // Global named register variables (GNU extension) are never emitted.
11876 if (VD->getStorageClass() == SC_Register)
11877 return false;
11878 if (VD->getDescribedVarTemplate() ||
11879 isa<VarTemplatePartialSpecializationDecl>(VD))
11880 return false;
11881 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
11882 // We never need to emit an uninstantiated function template.
11883 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11884 return false;
11885 } else if (isa<PragmaCommentDecl>(D))
11886 return true;
11887 else if (isa<PragmaDetectMismatchDecl>(D))
11888 return true;
11889 else if (isa<OMPRequiresDecl>(D))
11890 return true;
11891 else if (isa<OMPThreadPrivateDecl>(D))
11892 return !D->getDeclContext()->isDependentContext();
11893 else if (isa<OMPAllocateDecl>(D))
11894 return !D->getDeclContext()->isDependentContext();
11895 else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D))
11896 return !D->getDeclContext()->isDependentContext();
11897 else if (isa<ImportDecl>(D))
11898 return true;
11899 else
11900 return false;
11901
11902 // If this is a member of a class template, we do not need to emit it.
11904 return false;
11905
11906 // Weak references don't produce any output by themselves.
11907 if (D->hasAttr<WeakRefAttr>())
11908 return false;
11909
11910 // Aliases and used decls are required.
11911 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
11912 return true;
11913
11914 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
11915 // Forward declarations aren't required.
11916 if (!FD->doesThisDeclarationHaveABody())
11917 return FD->doesDeclarationForceExternallyVisibleDefinition();
11918
11919 // Constructors and destructors are required.
11920 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
11921 return true;
11922
11923 // The key function for a class is required. This rule only comes
11924 // into play when inline functions can be key functions, though.
11925 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
11926 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
11927 const CXXRecordDecl *RD = MD->getParent();
11928 if (MD->isOutOfLine() && RD->isDynamicClass()) {
11929 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
11930 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
11931 return true;
11932 }
11933 }
11934 }
11935
11937
11938 // static, static inline, always_inline, and extern inline functions can
11939 // always be deferred. Normal inline functions can be deferred in C99/C++.
11940 // Implicit template instantiations can also be deferred in C++.
11942 }
11943
11944 const auto *VD = cast<VarDecl>(D);
11945 assert(VD->isFileVarDecl() && "Expected file scoped var");
11946
11947 // If the decl is marked as `declare target to`, it should be emitted for the
11948 // host and for the device.
11949 if (LangOpts.OpenMP &&
11950 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
11951 return true;
11952
11953 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
11955 return false;
11956
11957 // Variables in other module units shouldn't be forced to be emitted.
11958 if (VD->isInAnotherModuleUnit())
11959 return false;
11960
11961 // Variables that can be needed in other TUs are required.
11964 return true;
11965
11966 // We never need to emit a variable that is available in another TU.
11968 return false;
11969
11970 // Variables that have destruction with side-effects are required.
11971 if (VD->needsDestruction(*this))
11972 return true;
11973
11974 // Variables that have initialization with side-effects are required.
11975 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
11976 // We can get a value-dependent initializer during error recovery.
11977 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
11978 return true;
11979
11980 // Likewise, variables with tuple-like bindings are required if their
11981 // bindings have side-effects.
11982 if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
11983 for (const auto *BD : DD->bindings())
11984 if (const auto *BindingVD = BD->getHoldingVar())
11985 if (DeclMustBeEmitted(BindingVD))
11986 return true;
11987
11988 return false;
11989}
11990
11992 const FunctionDecl *FD,
11993 llvm::function_ref<void(FunctionDecl *)> Pred) const {
11994 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
11995 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
11996 FD = FD->getMostRecentDecl();
11997 // FIXME: The order of traversal here matters and depends on the order of
11998 // lookup results, which happens to be (mostly) oldest-to-newest, but we
11999 // shouldn't rely on that.
12000 for (auto *CurDecl :
12002 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
12003 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
12004 !SeenDecls.contains(CurFD)) {
12005 SeenDecls.insert(CurFD);
12006 Pred(CurFD);
12007 }
12008 }
12009}
12010
12012 bool IsCXXMethod,
12013 bool IsBuiltin) const {
12014 // Pass through to the C++ ABI object
12015 if (IsCXXMethod)
12016 return ABI->getDefaultMethodCallConv(IsVariadic);
12017
12018 // Builtins ignore user-specified default calling convention and remain the
12019 // Target's default calling convention.
12020 if (!IsBuiltin) {
12021 switch (LangOpts.getDefaultCallingConv()) {
12023 break;
12025 return CC_C;
12027 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
12028 return CC_X86FastCall;
12029 break;
12031 if (!IsVariadic)
12032 return CC_X86StdCall;
12033 break;
12035 // __vectorcall cannot be applied to variadic functions.
12036 if (!IsVariadic)
12037 return CC_X86VectorCall;
12038 break;
12040 // __regcall cannot be applied to variadic functions.
12041 if (!IsVariadic)
12042 return CC_X86RegCall;
12043 break;
12045 if (!IsVariadic)
12046 return CC_M68kRTD;
12047 break;
12048 }
12049 }
12050 return Target->getDefaultCallingConv();
12051}
12052
12054 // Pass through to the C++ ABI object
12055 return ABI->isNearlyEmpty(RD);
12056}
12057
12059 if (!VTContext.get()) {
12060 auto ABI = Target->getCXXABI();
12061 if (ABI.isMicrosoft())
12062 VTContext.reset(new MicrosoftVTableContext(*this));
12063 else {
12064 auto ComponentLayout = getLangOpts().RelativeCXXABIVTables
12067 VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout));
12068 }
12069 }
12070 return VTContext.get();
12071}
12072
12074 if (!T)
12075 T = Target;
12076 switch (T->getCXXABI().getKind()) {
12077 case TargetCXXABI::AppleARM64:
12078 case TargetCXXABI::Fuchsia:
12079 case TargetCXXABI::GenericAArch64:
12080 case TargetCXXABI::GenericItanium:
12081 case TargetCXXABI::GenericARM:
12082 case TargetCXXABI::GenericMIPS:
12083 case TargetCXXABI::iOS:
12084 case TargetCXXABI::WebAssembly:
12085 case TargetCXXABI::WatchOS:
12086 case TargetCXXABI::XL:
12088 case TargetCXXABI::Microsoft:
12090 }
12091 llvm_unreachable("Unsupported ABI");
12092}
12093
12095 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
12096 "Device mangle context does not support Microsoft mangling.");
12097 switch (T.getCXXABI().getKind()) {
12098 case TargetCXXABI::AppleARM64:
12099 case TargetCXXABI::Fuchsia:
12100 case TargetCXXABI::GenericAArch64:
12101 case TargetCXXABI::GenericItanium:
12102 case TargetCXXABI::GenericARM:
12103 case TargetCXXABI::GenericMIPS:
12104 case TargetCXXABI::iOS:
12105 case TargetCXXABI::WebAssembly:
12106 case TargetCXXABI::WatchOS:
12107 case TargetCXXABI::XL:
12109 *this, getDiagnostics(),
12110 [](ASTContext &, const NamedDecl *ND) -> std::optional<unsigned> {
12111 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
12112 return RD->getDeviceLambdaManglingNumber();
12113 return std::nullopt;
12114 },
12115 /*IsAux=*/true);
12116 case TargetCXXABI::Microsoft:
12118 /*IsAux=*/true);
12119 }
12120 llvm_unreachable("Unsupported ABI");
12121}
12122
12123CXXABI::~CXXABI() = default;
12124
12126 return ASTRecordLayouts.getMemorySize() +
12127 llvm::capacity_in_bytes(ObjCLayouts) +
12128 llvm::capacity_in_bytes(KeyFunctions) +
12129 llvm::capacity_in_bytes(ObjCImpls) +
12130 llvm::capacity_in_bytes(BlockVarCopyInits) +
12131 llvm::capacity_in_bytes(DeclAttrs) +
12132 llvm::capacity_in_bytes(TemplateOrInstantiation) +
12133 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
12134 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
12135 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
12136 llvm::capacity_in_bytes(OverriddenMethods) +
12137 llvm::capacity_in_bytes(Types) +
12138 llvm::capacity_in_bytes(VariableArrayTypes);
12139}
12140
12141/// getIntTypeForBitwidth -
12142/// sets integer QualTy according to specified details:
12143/// bitwidth, signed/unsigned.
12144/// Returns empty type if there is no appropriate target types.
12146 unsigned Signed) const {
12148 CanQualType QualTy = getFromTargetType(Ty);
12149 if (!QualTy && DestWidth == 128)
12150 return Signed ? Int128Ty : UnsignedInt128Ty;
12151 return QualTy;
12152}
12153
12154/// getRealTypeForBitwidth -
12155/// sets floating point QualTy according to specified bitwidth.
12156/// Returns empty type if there is no appropriate target types.
12158 FloatModeKind ExplicitType) const {
12159 FloatModeKind Ty =
12160 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType);
12161 switch (Ty) {
12163 return HalfTy;
12165 return FloatTy;
12167 return DoubleTy;
12169 return LongDoubleTy;
12171 return Float128Ty;
12173 return Ibm128Ty;
12175 return {};
12176 }
12177
12178 llvm_unreachable("Unhandled TargetInfo::RealType value");
12179}
12180
12181void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
12182 if (Number > 1)
12183 MangleNumbers[ND] = Number;
12184}
12185
12187 bool ForAuxTarget) const {
12188 auto I = MangleNumbers.find(ND);
12189 unsigned Res = I != MangleNumbers.end() ? I->second : 1;
12190 // CUDA/HIP host compilation encodes host and device mangling numbers
12191 // as lower and upper half of 32 bit integer.
12192 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
12193 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
12194 } else {
12195 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
12196 "number for aux target");
12197 }
12198 return Res > 1 ? Res : 1;
12199}
12200
12201void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
12202 if (Number > 1)
12203 StaticLocalNumbers[VD] = Number;
12204}
12205
12207 auto I = StaticLocalNumbers.find(VD);
12208 return I != StaticLocalNumbers.end() ? I->second : 1;
12209}
12210
12213 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
12214 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
12215 if (!MCtx)
12217 return *MCtx;
12218}
12219
12222 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
12223 std::unique_ptr<MangleNumberingContext> &MCtx =
12224 ExtraMangleNumberingContexts[D];
12225 if (!MCtx)
12227 return *MCtx;
12228}
12229
12230std::unique_ptr<MangleNumberingContext>
12232 return ABI->createMangleNumberingContext();
12233}
12234
12235const CXXConstructorDecl *
12237 return ABI->getCopyConstructorForExceptionObject(
12238 cast<CXXRecordDecl>(RD->getFirstDecl()));
12239}
12240
12242 CXXConstructorDecl *CD) {
12243 return ABI->addCopyConstructorForExceptionObject(
12244 cast<CXXRecordDecl>(RD->getFirstDecl()),
12245 cast<CXXConstructorDecl>(CD->getFirstDecl()));
12246}
12247
12249 TypedefNameDecl *DD) {
12250 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
12251}
12252
12255 return ABI->getTypedefNameForUnnamedTagDecl(TD);
12256}
12257
12259 DeclaratorDecl *DD) {
12260 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
12261}
12262
12264 return ABI->getDeclaratorForUnnamedTagDecl(TD);
12265}
12266
12267void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
12268 ParamIndices[D] = index;
12269}
12270
12272 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
12273 assert(I != ParamIndices.end() &&
12274 "ParmIndices lacks entry set by ParmVarDecl");
12275 return I->second;
12276}
12277
12279 unsigned Length) const {
12280 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
12281 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
12282 EltTy = EltTy.withConst();
12283
12284 EltTy = adjustStringLiteralBaseType(EltTy);
12285
12286 // Get an array type for the string, according to C99 6.4.5. This includes
12287 // the null terminator character.
12288 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
12289 ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0);
12290}
12291
12294 StringLiteral *&Result = StringLiteralCache[Key];
12295 if (!Result)
12297 *this, Key, StringLiteralKind::Ordinary,
12298 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
12299 SourceLocation());
12300 return Result;
12301}
12302
12303MSGuidDecl *
12305 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
12306
12307 llvm::FoldingSetNodeID ID;
12308 MSGuidDecl::Profile(ID, Parts);
12309
12310 void *InsertPos;
12311 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
12312 return Existing;
12313
12314 QualType GUIDType = getMSGuidType().withConst();
12315 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
12316 MSGuidDecls.InsertNode(New, InsertPos);
12317 return New;
12318}
12319
12322 const APValue &APVal) const {
12323 llvm::FoldingSetNodeID ID;
12325
12326 void *InsertPos;
12327 if (UnnamedGlobalConstantDecl *Existing =
12328 UnnamedGlobalConstantDecls.FindNodeOrInsertPos(ID, InsertPos))
12329 return Existing;
12330
12332 UnnamedGlobalConstantDecl::Create(*this, Ty, APVal);
12333 UnnamedGlobalConstantDecls.InsertNode(New, InsertPos);
12334 return New;
12335}
12336
12339 assert(T->isRecordType() && "template param object of unexpected type");
12340
12341 // C++ [temp.param]p8:
12342 // [...] a static storage duration object of type 'const T' [...]
12343 T.addConst();
12344
12345 llvm::FoldingSetNodeID ID;
12347
12348 void *InsertPos;
12349 if (TemplateParamObjectDecl *Existing =
12350 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
12351 return Existing;
12352
12353 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
12354 TemplateParamObjectDecls.InsertNode(New, InsertPos);
12355 return New;
12356}
12357
12359 const llvm::Triple &T = getTargetInfo().getTriple();
12360 if (!T.isOSDarwin())
12361 return false;
12362
12363 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
12364 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
12365 return false;
12366
12367 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
12368 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
12369 uint64_t Size = sizeChars.getQuantity();
12370 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
12371 unsigned Align = alignChars.getQuantity();
12372 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
12373 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
12374}
12375
12376bool
12378 const ObjCMethodDecl *MethodImpl) {
12379 // No point trying to match an unavailable/deprecated mothod.
12380 if (MethodDecl->hasAttr<UnavailableAttr>()
12381 || MethodDecl->hasAttr<DeprecatedAttr>())
12382 return false;
12383 if (MethodDecl->getObjCDeclQualifier() !=
12384 MethodImpl->getObjCDeclQualifier())
12385 return false;
12386 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
12387 return false;
12388
12389 if (MethodDecl->param_size() != MethodImpl->param_size())
12390 return false;
12391
12392 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
12393 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
12394 EF = MethodDecl->param_end();
12395 IM != EM && IF != EF; ++IM, ++IF) {
12396 const ParmVarDecl *DeclVar = (*IF);
12397 const ParmVarDecl *ImplVar = (*IM);
12398 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
12399 return false;
12400 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
12401 return false;
12402 }
12403
12404 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
12405}
12406
12408 LangAS AS;
12410 AS = LangAS::Default;
12411 else
12412 AS = QT->getPointeeType().getAddressSpace();
12413
12415}
12416
12419}
12420
12421bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
12422 if (X == Y)
12423 return true;
12424 if (!X || !Y)
12425 return false;
12426 llvm::FoldingSetNodeID IDX, IDY;
12427 X->Profile(IDX, *this, /*Canonical=*/true);
12428 Y->Profile(IDY, *this, /*Canonical=*/true);
12429 return IDX == IDY;
12430}
12431
12432// The getCommon* helpers return, for given 'same' X and Y entities given as
12433// inputs, another entity which is also the 'same' as the inputs, but which
12434// is closer to the canonical form of the inputs, each according to a given
12435// criteria.
12436// The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
12437// the regular ones.
12438
12440 if (!declaresSameEntity(X, Y))
12441 return nullptr;
12442 for (const Decl *DX : X->redecls()) {
12443 // If we reach Y before reaching the first decl, that means X is older.
12444 if (DX == Y)
12445 return X;
12446 // If we reach the first decl, then Y is older.
12447 if (DX->isFirstDecl())
12448 return Y;
12449 }
12450 llvm_unreachable("Corrupt redecls chain");
12451}
12452
12453template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
12454static T *getCommonDecl(T *X, T *Y) {
12455 return cast_or_null<T>(
12456 getCommonDecl(const_cast<Decl *>(cast_or_null<Decl>(X)),
12457 const_cast<Decl *>(cast_or_null<Decl>(Y))));
12458}
12459
12460template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
12461static T *getCommonDeclChecked(T *X, T *Y) {
12462 return cast<T>(getCommonDecl(const_cast<Decl *>(cast<Decl>(X)),
12463 const_cast<Decl *>(cast<Decl>(Y))));
12464}
12465
12467 TemplateName Y) {
12468 if (X.getAsVoidPointer() == Y.getAsVoidPointer())
12469 return X;
12470 // FIXME: There are cases here where we could find a common template name
12471 // with more sugar. For example one could be a SubstTemplateTemplate*
12472 // replacing the other.
12474 if (CX.getAsVoidPointer() !=
12476 return TemplateName();
12477 return CX;
12478}
12479
12480static TemplateName
12483 assert(R.getAsVoidPointer() != nullptr);
12484 return R;
12485}
12486
12488 ArrayRef<QualType> Ys, bool Unqualified = false) {
12489 assert(Xs.size() == Ys.size());
12490 SmallVector<QualType, 8> Rs(Xs.size());
12491 for (size_t I = 0; I < Rs.size(); ++I)
12492 Rs[I] = Ctx.getCommonSugaredType(Xs[I], Ys[I], Unqualified);
12493 return Rs;
12494}
12495
12496template <class T>
12497static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
12498 return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
12499 : SourceLocation();
12500}
12501
12503 const TemplateArgument &X,
12504 const TemplateArgument &Y) {
12505 if (X.getKind() != Y.getKind())
12506 return TemplateArgument();
12507
12508 switch (X.getKind()) {
12510 if (!Ctx.hasSameType(X.getAsType(), Y.getAsType()))
12511 return TemplateArgument();
12512 return TemplateArgument(
12513 Ctx.getCommonSugaredType(X.getAsType(), Y.getAsType()));
12515 if (!Ctx.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
12516 return TemplateArgument();
12517 return TemplateArgument(
12518 Ctx.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
12519 /*Unqualified=*/true);
12521 if (!Ctx.hasSameType(X.getAsExpr()->getType(), Y.getAsExpr()->getType()))
12522 return TemplateArgument();
12523 // FIXME: Try to keep the common sugar.
12524 return X;
12526 TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
12527 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
12528 if (!CTN.getAsVoidPointer())
12529 return TemplateArgument();
12530 return TemplateArgument(CTN);
12531 }
12533 TemplateName TX = X.getAsTemplateOrTemplatePattern(),
12535 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
12536 if (!CTN.getAsVoidPointer())
12537 return TemplateName();
12538 auto NExpX = X.getNumTemplateExpansions();
12539 assert(NExpX == Y.getNumTemplateExpansions());
12540 return TemplateArgument(CTN, NExpX);
12541 }
12542 default:
12543 // FIXME: Handle the other argument kinds.
12544 return X;
12545 }
12546}
12547
12552 if (Xs.size() != Ys.size())
12553 return true;
12554 R.resize(Xs.size());
12555 for (size_t I = 0; I < R.size(); ++I) {
12556 R[I] = getCommonTemplateArgument(Ctx, Xs[I], Ys[I]);
12557 if (R[I].isNull())
12558 return true;
12559 }
12560 return false;
12561}
12562
12567 bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
12568 assert(!Different);
12569 (void)Different;
12570 return R;
12571}
12572
12573template <class T>
12574static ElaboratedTypeKeyword getCommonTypeKeyword(const T *X, const T *Y) {
12575 return X->getKeyword() == Y->getKeyword() ? X->getKeyword()
12577}
12578
12579template <class T>
12581 const T *Y) {
12582 // FIXME: Try to keep the common NNS sugar.
12583 return X->getQualifier() == Y->getQualifier()
12584 ? X->getQualifier()
12585 : Ctx.getCanonicalNestedNameSpecifier(X->getQualifier());
12586}
12587
12588template <class T>
12589static QualType getCommonElementType(ASTContext &Ctx, const T *X, const T *Y) {
12590 return Ctx.getCommonSugaredType(X->getElementType(), Y->getElementType());
12591}
12592
12593template <class T>
12595 Qualifiers &QX, const T *Y,
12596 Qualifiers &QY) {
12597 QualType EX = X->getElementType(), EY = Y->getElementType();
12598 QualType R = Ctx.getCommonSugaredType(EX, EY,
12599 /*Unqualified=*/true);
12600 Qualifiers RQ = R.getQualifiers();
12601 QX += EX.getQualifiers() - RQ;
12602 QY += EY.getQualifiers() - RQ;
12603 return R;
12604}
12605
12606template <class T>
12607static QualType getCommonPointeeType(ASTContext &Ctx, const T *X, const T *Y) {
12608 return Ctx.getCommonSugaredType(X->getPointeeType(), Y->getPointeeType());
12609}
12610
12611template <class T> static auto *getCommonSizeExpr(ASTContext &Ctx, T *X, T *Y) {
12612 assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
12613 return X->getSizeExpr();
12614}
12615
12616static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
12617 assert(X->getSizeModifier() == Y->getSizeModifier());
12618 return X->getSizeModifier();
12619}
12620
12622 const ArrayType *Y) {
12623 assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
12624 return X->getIndexTypeCVRQualifiers();
12625}
12626
12627// Merges two type lists such that the resulting vector will contain
12628// each type (in a canonical sense) only once, in the order they appear
12629// from X to Y. If they occur in both X and Y, the result will contain
12630// the common sugared type between them.
12633 llvm::DenseMap<QualType, unsigned> Found;
12634 for (auto Ts : {X, Y}) {
12635 for (QualType T : Ts) {
12636 auto Res = Found.try_emplace(Ctx.getCanonicalType(T), Out.size());
12637 if (!Res.second) {
12638 QualType &U = Out[Res.first->second];
12639 U = Ctx.getCommonSugaredType(U, T);
12640 } else {
12641 Out.emplace_back(T);
12642 }
12643 }
12644 }
12645}
12646
12650 SmallVectorImpl<QualType> &ExceptionTypeStorage,
12651 bool AcceptDependent) {
12652 ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
12653
12654 // If either of them can throw anything, that is the result.
12655 for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
12656 if (EST1 == I)
12657 return ESI1;
12658 if (EST2 == I)
12659 return ESI2;
12660 }
12661
12662 // If either of them is non-throwing, the result is the other.
12663 for (auto I :
12665 if (EST1 == I)
12666 return ESI2;
12667 if (EST2 == I)
12668 return ESI1;
12669 }
12670
12671 // If we're left with value-dependent computed noexcept expressions, we're
12672 // stuck. Before C++17, we can just drop the exception specification entirely,
12673 // since it's not actually part of the canonical type. And this should never
12674 // happen in C++17, because it would mean we were computing the composite
12675 // pointer type of dependent types, which should never happen.
12676 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
12677 assert(AcceptDependent &&
12678 "computing composite pointer type of dependent types");
12680 }
12681
12682 // Switch over the possibilities so that people adding new values know to
12683 // update this function.
12684 switch (EST1) {
12685 case EST_None:
12686 case EST_DynamicNone:
12687 case EST_MSAny:
12688 case EST_BasicNoexcept:
12690 case EST_NoexceptFalse:
12691 case EST_NoexceptTrue:
12692 case EST_NoThrow:
12693 llvm_unreachable("These ESTs should be handled above");
12694
12695 case EST_Dynamic: {
12696 // This is the fun case: both exception specifications are dynamic. Form
12697 // the union of the two lists.
12698 assert(EST2 == EST_Dynamic && "other cases should already be handled");
12699 mergeTypeLists(*this, ExceptionTypeStorage, ESI1.Exceptions,
12700 ESI2.Exceptions);
12702 Result.Exceptions = ExceptionTypeStorage;
12703 return Result;
12704 }
12705
12706 case EST_Unevaluated:
12707 case EST_Uninstantiated:
12708 case EST_Unparsed:
12709 llvm_unreachable("shouldn't see unresolved exception specifications here");
12710 }
12711
12712 llvm_unreachable("invalid ExceptionSpecificationType");
12713}
12714
12716 Qualifiers &QX, const Type *Y,
12717 Qualifiers &QY) {
12718 Type::TypeClass TC = X->getTypeClass();
12719 assert(TC == Y->getTypeClass());
12720 switch (TC) {
12721#define UNEXPECTED_TYPE(Class, Kind) \
12722 case Type::Class: \
12723 llvm_unreachable("Unexpected " Kind ": " #Class);
12724
12725#define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
12726#define TYPE(Class, Base)
12727#include "clang/AST/TypeNodes.inc"
12728
12729#define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
12730 SUGAR_FREE_TYPE(Builtin)
12731 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
12732 SUGAR_FREE_TYPE(DependentBitInt)
12735 SUGAR_FREE_TYPE(ObjCInterface)
12737 SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
12738 SUGAR_FREE_TYPE(UnresolvedUsing)
12739#undef SUGAR_FREE_TYPE
12740#define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
12741 NON_UNIQUE_TYPE(TypeOfExpr)
12742 NON_UNIQUE_TYPE(VariableArray)
12743#undef NON_UNIQUE_TYPE
12744
12745 UNEXPECTED_TYPE(TypeOf, "sugar")
12746
12747#undef UNEXPECTED_TYPE
12748
12749 case Type::Auto: {
12750 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
12751 assert(AX->getDeducedType().isNull());
12752 assert(AY->getDeducedType().isNull());
12753 assert(AX->getKeyword() == AY->getKeyword());
12754 assert(AX->isInstantiationDependentType() ==
12755 AY->isInstantiationDependentType());
12756 auto As = getCommonTemplateArguments(Ctx, AX->getTypeConstraintArguments(),
12757 AY->getTypeConstraintArguments());
12758 return Ctx.getAutoType(QualType(), AX->getKeyword(),
12760 AX->containsUnexpandedParameterPack(),
12761 getCommonDeclChecked(AX->getTypeConstraintConcept(),
12762 AY->getTypeConstraintConcept()),
12763 As);
12764 }
12765 case Type::IncompleteArray: {
12766 const auto *AX = cast<IncompleteArrayType>(X),
12767 *AY = cast<IncompleteArrayType>(Y);
12768 return Ctx.getIncompleteArrayType(
12769 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
12771 }
12772 case Type::DependentSizedArray: {
12773 const auto *AX = cast<DependentSizedArrayType>(X),
12774 *AY = cast<DependentSizedArrayType>(Y);
12775 return Ctx.getDependentSizedArrayType(
12776 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
12777 getCommonSizeExpr(Ctx, AX, AY), getCommonSizeModifier(AX, AY),
12779 AX->getBracketsRange() == AY->getBracketsRange()
12780 ? AX->getBracketsRange()
12781 : SourceRange());
12782 }
12783 case Type::ConstantArray: {
12784 const auto *AX = cast<ConstantArrayType>(X),
12785 *AY = cast<ConstantArrayType>(Y);
12786 assert(AX->getSize() == AY->getSize());
12787 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
12788 ? AX->getSizeExpr()
12789 : nullptr;
12790 return Ctx.getConstantArrayType(
12791 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
12793 }
12794 case Type::Atomic: {
12795 const auto *AX = cast<AtomicType>(X), *AY = cast<AtomicType>(Y);
12796 return Ctx.getAtomicType(
12797 Ctx.getCommonSugaredType(AX->getValueType(), AY->getValueType()));
12798 }
12799 case Type::Complex: {
12800 const auto *CX = cast<ComplexType>(X), *CY = cast<ComplexType>(Y);
12801 return Ctx.getComplexType(getCommonArrayElementType(Ctx, CX, QX, CY, QY));
12802 }
12803 case Type::Pointer: {
12804 const auto *PX = cast<PointerType>(X), *PY = cast<PointerType>(Y);
12805 return Ctx.getPointerType(getCommonPointeeType(Ctx, PX, PY));
12806 }
12807 case Type::BlockPointer: {
12808 const auto *PX = cast<BlockPointerType>(X), *PY = cast<BlockPointerType>(Y);
12809 return Ctx.getBlockPointerType(getCommonPointeeType(Ctx, PX, PY));
12810 }
12811 case Type::ObjCObjectPointer: {
12812 const auto *PX = cast<ObjCObjectPointerType>(X),
12813 *PY = cast<ObjCObjectPointerType>(Y);
12814 return Ctx.getObjCObjectPointerType(getCommonPointeeType(Ctx, PX, PY));
12815 }
12816 case Type::MemberPointer: {
12817 const auto *PX = cast<MemberPointerType>(X),
12818 *PY = cast<MemberPointerType>(Y);
12819 return Ctx.getMemberPointerType(
12820 getCommonPointeeType(Ctx, PX, PY),
12821 Ctx.getCommonSugaredType(QualType(PX->getClass(), 0),
12822 QualType(PY->getClass(), 0))
12823 .getTypePtr());
12824 }
12825 case Type::LValueReference: {
12826 const auto *PX = cast<LValueReferenceType>(X),
12827 *PY = cast<LValueReferenceType>(Y);
12828 // FIXME: Preserve PointeeTypeAsWritten.
12829 return Ctx.getLValueReferenceType(getCommonPointeeType(Ctx, PX, PY),
12830 PX->isSpelledAsLValue() ||
12831 PY->isSpelledAsLValue());
12832 }
12833 case Type::RValueReference: {
12834 const auto *PX = cast<RValueReferenceType>(X),
12835 *PY = cast<RValueReferenceType>(Y);
12836 // FIXME: Preserve PointeeTypeAsWritten.
12837 return Ctx.getRValueReferenceType(getCommonPointeeType(Ctx, PX, PY));
12838 }
12839 case Type::DependentAddressSpace: {
12840 const auto *PX = cast<DependentAddressSpaceType>(X),
12841 *PY = cast<DependentAddressSpaceType>(Y);
12842 assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
12843 return Ctx.getDependentAddressSpaceType(getCommonPointeeType(Ctx, PX, PY),
12844 PX->getAddrSpaceExpr(),
12845 getCommonAttrLoc(PX, PY));
12846 }
12847 case Type::FunctionNoProto: {
12848 const auto *FX = cast<FunctionNoProtoType>(X),
12849 *FY = cast<FunctionNoProtoType>(Y);
12850 assert(FX->getExtInfo() == FY->getExtInfo());
12851 return Ctx.getFunctionNoProtoType(
12852 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType()),
12853 FX->getExtInfo());
12854 }
12855 case Type::FunctionProto: {
12856 const auto *FX = cast<FunctionProtoType>(X),
12857 *FY = cast<FunctionProtoType>(Y);
12858 FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
12859 EPIY = FY->getExtProtoInfo();
12860 assert(EPIX.ExtInfo == EPIY.ExtInfo);
12861 assert(EPIX.ExtParameterInfos == EPIY.ExtParameterInfos);
12862 assert(EPIX.RefQualifier == EPIY.RefQualifier);
12863 assert(EPIX.TypeQuals == EPIY.TypeQuals);
12864 assert(EPIX.Variadic == EPIY.Variadic);
12865
12866 // FIXME: Can we handle an empty EllipsisLoc?
12867 // Use emtpy EllipsisLoc if X and Y differ.
12868
12869 EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
12870
12871 QualType R =
12872 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType());
12873 auto P = getCommonTypes(Ctx, FX->param_types(), FY->param_types(),
12874 /*Unqualified=*/true);
12875
12876 SmallVector<QualType, 8> Exceptions;
12878 EPIX.ExceptionSpec, EPIY.ExceptionSpec, Exceptions, true);
12879 return Ctx.getFunctionType(R, P, EPIX);
12880 }
12881 case Type::ObjCObject: {
12882 const auto *OX = cast<ObjCObjectType>(X), *OY = cast<ObjCObjectType>(Y);
12883 assert(
12884 std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
12885 OY->getProtocols().begin(), OY->getProtocols().end(),
12886 [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
12887 return P0->getCanonicalDecl() == P1->getCanonicalDecl();
12888 }) &&
12889 "protocol lists must be the same");
12890 auto TAs = getCommonTypes(Ctx, OX->getTypeArgsAsWritten(),
12891 OY->getTypeArgsAsWritten());
12892 return Ctx.getObjCObjectType(
12893 Ctx.getCommonSugaredType(OX->getBaseType(), OY->getBaseType()), TAs,
12894 OX->getProtocols(),
12895 OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
12896 }
12897 case Type::ConstantMatrix: {
12898 const auto *MX = cast<ConstantMatrixType>(X),
12899 *MY = cast<ConstantMatrixType>(Y);
12900 assert(MX->getNumRows() == MY->getNumRows());
12901 assert(MX->getNumColumns() == MY->getNumColumns());
12902 return Ctx.getConstantMatrixType(getCommonElementType(Ctx, MX, MY),
12903 MX->getNumRows(), MX->getNumColumns());
12904 }
12905 case Type::DependentSizedMatrix: {
12906 const auto *MX = cast<DependentSizedMatrixType>(X),
12907 *MY = cast<DependentSizedMatrixType>(Y);
12908 assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
12909 assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
12910 return Ctx.getDependentSizedMatrixType(
12911 getCommonElementType(Ctx, MX, MY), MX->getRowExpr(),
12912 MX->getColumnExpr(), getCommonAttrLoc(MX, MY));
12913 }
12914 case Type::Vector: {
12915 const auto *VX = cast<VectorType>(X), *VY = cast<VectorType>(Y);
12916 assert(VX->getNumElements() == VY->getNumElements());
12917 assert(VX->getVectorKind() == VY->getVectorKind());
12918 return Ctx.getVectorType(getCommonElementType(Ctx, VX, VY),
12919 VX->getNumElements(), VX->getVectorKind());
12920 }
12921 case Type::ExtVector: {
12922 const auto *VX = cast<ExtVectorType>(X), *VY = cast<ExtVectorType>(Y);
12923 assert(VX->getNumElements() == VY->getNumElements());
12924 return Ctx.getExtVectorType(getCommonElementType(Ctx, VX, VY),
12925 VX->getNumElements());
12926 }
12927 case Type::DependentSizedExtVector: {
12928 const auto *VX = cast<DependentSizedExtVectorType>(X),
12929 *VY = cast<DependentSizedExtVectorType>(Y);
12931 getCommonSizeExpr(Ctx, VX, VY),
12932 getCommonAttrLoc(VX, VY));
12933 }
12934 case Type::DependentVector: {
12935 const auto *VX = cast<DependentVectorType>(X),
12936 *VY = cast<DependentVectorType>(Y);
12937 assert(VX->getVectorKind() == VY->getVectorKind());
12938 return Ctx.getDependentVectorType(
12939 getCommonElementType(Ctx, VX, VY), getCommonSizeExpr(Ctx, VX, VY),
12940 getCommonAttrLoc(VX, VY), VX->getVectorKind());
12941 }
12942 case Type::InjectedClassName: {
12943 const auto *IX = cast<InjectedClassNameType>(X),
12944 *IY = cast<InjectedClassNameType>(Y);
12945 return Ctx.getInjectedClassNameType(
12946 getCommonDeclChecked(IX->getDecl(), IY->getDecl()),
12947 Ctx.getCommonSugaredType(IX->getInjectedSpecializationType(),
12948 IY->getInjectedSpecializationType()));
12949 }
12950 case Type::TemplateSpecialization: {
12951 const auto *TX = cast<TemplateSpecializationType>(X),
12952 *TY = cast<TemplateSpecializationType>(Y);
12953 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
12954 TY->template_arguments());
12956 ::getCommonTemplateNameChecked(Ctx, TX->getTemplateName(),
12957 TY->getTemplateName()),
12958 As, X->getCanonicalTypeInternal());
12959 }
12960 case Type::Decltype: {
12961 const auto *DX = cast<DecltypeType>(X);
12962 [[maybe_unused]] const auto *DY = cast<DecltypeType>(Y);
12963 assert(DX->isDependentType());
12964 assert(DY->isDependentType());
12965 assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
12966 // As Decltype is not uniqued, building a common type would be wasteful.
12967 return QualType(DX, 0);
12968 }
12969 case Type::PackIndexing: {
12970 const auto *DX = cast<PackIndexingType>(X);
12971 [[maybe_unused]] const auto *DY = cast<PackIndexingType>(Y);
12972 assert(DX->isDependentType());
12973 assert(DY->isDependentType());
12974 assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr()));
12975 return QualType(DX, 0);
12976 }
12977 case Type::DependentName: {
12978 const auto *NX = cast<DependentNameType>(X),
12979 *NY = cast<DependentNameType>(Y);
12980 assert(NX->getIdentifier() == NY->getIdentifier());
12981 return Ctx.getDependentNameType(
12982 getCommonTypeKeyword(NX, NY), getCommonNNS(Ctx, NX, NY),
12983 NX->getIdentifier(), NX->getCanonicalTypeInternal());
12984 }
12985 case Type::DependentTemplateSpecialization: {
12986 const auto *TX = cast<DependentTemplateSpecializationType>(X),
12987 *TY = cast<DependentTemplateSpecializationType>(Y);
12988 assert(TX->getIdentifier() == TY->getIdentifier());
12989 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
12990 TY->template_arguments());
12992 getCommonTypeKeyword(TX, TY), getCommonNNS(Ctx, TX, TY),
12993 TX->getIdentifier(), As);
12994 }
12995 case Type::UnaryTransform: {
12996 const auto *TX = cast<UnaryTransformType>(X),
12997 *TY = cast<UnaryTransformType>(Y);
12998 assert(TX->getUTTKind() == TY->getUTTKind());
12999 return Ctx.getUnaryTransformType(
13000 Ctx.getCommonSugaredType(TX->getBaseType(), TY->getBaseType()),
13001 Ctx.getCommonSugaredType(TX->getUnderlyingType(),
13002 TY->getUnderlyingType()),
13003 TX->getUTTKind());
13004 }
13005 case Type::PackExpansion: {
13006 const auto *PX = cast<PackExpansionType>(X),
13007 *PY = cast<PackExpansionType>(Y);
13008 assert(PX->getNumExpansions() == PY->getNumExpansions());
13009 return Ctx.getPackExpansionType(
13010 Ctx.getCommonSugaredType(PX->getPattern(), PY->getPattern()),
13011 PX->getNumExpansions(), false);
13012 }
13013 case Type::Pipe: {
13014 const auto *PX = cast<PipeType>(X), *PY = cast<PipeType>(Y);
13015 assert(PX->isReadOnly() == PY->isReadOnly());
13016 auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
13018 return (Ctx.*MP)(getCommonElementType(Ctx, PX, PY));
13019 }
13020 case Type::TemplateTypeParm: {
13021 const auto *TX = cast<TemplateTypeParmType>(X),
13022 *TY = cast<TemplateTypeParmType>(Y);
13023 assert(TX->getDepth() == TY->getDepth());
13024 assert(TX->getIndex() == TY->getIndex());
13025 assert(TX->isParameterPack() == TY->isParameterPack());
13026 return Ctx.getTemplateTypeParmType(
13027 TX->getDepth(), TX->getIndex(), TX->isParameterPack(),
13028 getCommonDecl(TX->getDecl(), TY->getDecl()));
13029 }
13030 }
13031 llvm_unreachable("Unknown Type Class");
13032}
13033
13035 const Type *Y,
13036 SplitQualType Underlying) {
13037 Type::TypeClass TC = X->getTypeClass();
13038 if (TC != Y->getTypeClass())
13039 return QualType();
13040 switch (TC) {
13041#define UNEXPECTED_TYPE(Class, Kind) \
13042 case Type::Class: \
13043 llvm_unreachable("Unexpected " Kind ": " #Class);
13044#define TYPE(Class, Base)
13045#define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
13046#include "clang/AST/TypeNodes.inc"
13047
13048#define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
13051 CANONICAL_TYPE(BlockPointer)
13052 CANONICAL_TYPE(Builtin)
13054 CANONICAL_TYPE(ConstantArray)
13055 CANONICAL_TYPE(ConstantMatrix)
13057 CANONICAL_TYPE(ExtVector)
13058 CANONICAL_TYPE(FunctionNoProto)
13059 CANONICAL_TYPE(FunctionProto)
13060 CANONICAL_TYPE(IncompleteArray)
13061 CANONICAL_TYPE(LValueReference)
13062 CANONICAL_TYPE(MemberPointer)
13063 CANONICAL_TYPE(ObjCInterface)
13064 CANONICAL_TYPE(ObjCObject)
13065 CANONICAL_TYPE(ObjCObjectPointer)
13069 CANONICAL_TYPE(RValueReference)
13070 CANONICAL_TYPE(VariableArray)
13072#undef CANONICAL_TYPE
13073
13074#undef UNEXPECTED_TYPE
13075
13076 case Type::Adjusted: {
13077 const auto *AX = cast<AdjustedType>(X), *AY = cast<AdjustedType>(Y);
13078 QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
13079 if (!Ctx.hasSameType(OX, OY))
13080 return QualType();
13081 // FIXME: It's inefficient to have to unify the original types.
13082 return Ctx.getAdjustedType(Ctx.getCommonSugaredType(OX, OY),
13083 Ctx.getQualifiedType(Underlying));
13084 }
13085 case Type::Decayed: {
13086 const auto *DX = cast<DecayedType>(X), *DY = cast<DecayedType>(Y);
13087 QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
13088 if (!Ctx.hasSameType(OX, OY))
13089 return QualType();
13090 // FIXME: It's inefficient to have to unify the original types.
13091 return Ctx.getDecayedType(Ctx.getCommonSugaredType(OX, OY),
13092 Ctx.getQualifiedType(Underlying));
13093 }
13094 case Type::Attributed: {
13095 const auto *AX = cast<AttributedType>(X), *AY = cast<AttributedType>(Y);
13096 AttributedType::Kind Kind = AX->getAttrKind();
13097 if (Kind != AY->getAttrKind())
13098 return QualType();
13099 QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
13100 if (!Ctx.hasSameType(MX, MY))
13101 return QualType();
13102 // FIXME: It's inefficient to have to unify the modified types.
13103 return Ctx.getAttributedType(Kind, Ctx.getCommonSugaredType(MX, MY),
13104 Ctx.getQualifiedType(Underlying));
13105 }
13106 case Type::BTFTagAttributed: {
13107 const auto *BX = cast<BTFTagAttributedType>(X);
13108 const BTFTypeTagAttr *AX = BX->getAttr();
13109 // The attribute is not uniqued, so just compare the tag.
13110 if (AX->getBTFTypeTag() !=
13111 cast<BTFTagAttributedType>(Y)->getAttr()->getBTFTypeTag())
13112 return QualType();
13113 return Ctx.getBTFTagAttributedType(AX, Ctx.getQualifiedType(Underlying));
13114 }
13115 case Type::Auto: {
13116 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
13117
13118 AutoTypeKeyword KW = AX->getKeyword();
13119 if (KW != AY->getKeyword())
13120 return QualType();
13121
13122 ConceptDecl *CD = ::getCommonDecl(AX->getTypeConstraintConcept(),
13123 AY->getTypeConstraintConcept());
13125 if (CD &&
13126 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
13127 AY->getTypeConstraintArguments())) {
13128 CD = nullptr; // The arguments differ, so make it unconstrained.
13129 As.clear();
13130 }
13131
13132 // Both auto types can't be dependent, otherwise they wouldn't have been
13133 // sugar. This implies they can't contain unexpanded packs either.
13134 return Ctx.getAutoType(Ctx.getQualifiedType(Underlying), AX->getKeyword(),
13135 /*IsDependent=*/false, /*IsPack=*/false, CD, As);
13136 }
13137 case Type::PackIndexing:
13138 case Type::Decltype:
13139 return QualType();
13140 case Type::DeducedTemplateSpecialization:
13141 // FIXME: Try to merge these.
13142 return QualType();
13143
13144 case Type::Elaborated: {
13145 const auto *EX = cast<ElaboratedType>(X), *EY = cast<ElaboratedType>(Y);
13146 return Ctx.getElaboratedType(
13147 ::getCommonTypeKeyword(EX, EY), ::getCommonNNS(Ctx, EX, EY),
13148 Ctx.getQualifiedType(Underlying),
13149 ::getCommonDecl(EX->getOwnedTagDecl(), EY->getOwnedTagDecl()));
13150 }
13151 case Type::MacroQualified: {
13152 const auto *MX = cast<MacroQualifiedType>(X),
13153 *MY = cast<MacroQualifiedType>(Y);
13154 const IdentifierInfo *IX = MX->getMacroIdentifier();
13155 if (IX != MY->getMacroIdentifier())
13156 return QualType();
13157 return Ctx.getMacroQualifiedType(Ctx.getQualifiedType(Underlying), IX);
13158 }
13159 case Type::SubstTemplateTypeParm: {
13160 const auto *SX = cast<SubstTemplateTypeParmType>(X),
13161 *SY = cast<SubstTemplateTypeParmType>(Y);
13162 Decl *CD =
13163 ::getCommonDecl(SX->getAssociatedDecl(), SY->getAssociatedDecl());
13164 if (!CD)
13165 return QualType();
13166 unsigned Index = SX->getIndex();
13167 if (Index != SY->getIndex())
13168 return QualType();
13169 auto PackIndex = SX->getPackIndex();
13170 if (PackIndex != SY->getPackIndex())
13171 return QualType();
13172 return Ctx.getSubstTemplateTypeParmType(Ctx.getQualifiedType(Underlying),
13173 CD, Index, PackIndex);
13174 }
13175 case Type::ObjCTypeParam:
13176 // FIXME: Try to merge these.
13177 return QualType();
13178 case Type::Paren:
13179 return Ctx.getParenType(Ctx.getQualifiedType(Underlying));
13180
13181 case Type::TemplateSpecialization: {
13182 const auto *TX = cast<TemplateSpecializationType>(X),
13183 *TY = cast<TemplateSpecializationType>(Y);
13184 TemplateName CTN = ::getCommonTemplateName(Ctx, TX->getTemplateName(),
13185 TY->getTemplateName());
13186 if (!CTN.getAsVoidPointer())
13187 return QualType();
13189 if (getCommonTemplateArguments(Ctx, Args, TX->template_arguments(),
13190 TY->template_arguments()))
13191 return QualType();
13192 return Ctx.getTemplateSpecializationType(CTN, Args,
13193 Ctx.getQualifiedType(Underlying));
13194 }
13195 case Type::Typedef: {
13196 const auto *TX = cast<TypedefType>(X), *TY = cast<TypedefType>(Y);
13197 const TypedefNameDecl *CD = ::getCommonDecl(TX->getDecl(), TY->getDecl());
13198 if (!CD)
13199 return QualType();
13200 return Ctx.getTypedefType(CD, Ctx.getQualifiedType(Underlying));
13201 }
13202 case Type::TypeOf: {
13203 // The common sugar between two typeof expressions, where one is
13204 // potentially a typeof_unqual and the other is not, we unify to the
13205 // qualified type as that retains the most information along with the type.
13206 // We only return a typeof_unqual type when both types are unqual types.
13208 if (cast<TypeOfType>(X)->getKind() == cast<TypeOfType>(Y)->getKind() &&
13209 cast<TypeOfType>(X)->getKind() == TypeOfKind::Unqualified)
13211 return Ctx.getTypeOfType(Ctx.getQualifiedType(Underlying), Kind);
13212 }
13213 case Type::TypeOfExpr:
13214 return QualType();
13215
13216 case Type::UnaryTransform: {
13217 const auto *UX = cast<UnaryTransformType>(X),
13218 *UY = cast<UnaryTransformType>(Y);
13219 UnaryTransformType::UTTKind KX = UX->getUTTKind();
13220 if (KX != UY->getUTTKind())
13221 return QualType();
13222 QualType BX = UX->getBaseType(), BY = UY->getBaseType();
13223 if (!Ctx.hasSameType(BX, BY))
13224 return QualType();
13225 // FIXME: It's inefficient to have to unify the base types.
13226 return Ctx.getUnaryTransformType(Ctx.getCommonSugaredType(BX, BY),
13227 Ctx.getQualifiedType(Underlying), KX);
13228 }
13229 case Type::Using: {
13230 const auto *UX = cast<UsingType>(X), *UY = cast<UsingType>(Y);
13231 const UsingShadowDecl *CD =
13232 ::getCommonDecl(UX->getFoundDecl(), UY->getFoundDecl());
13233 if (!CD)
13234 return QualType();
13235 return Ctx.getUsingType(CD, Ctx.getQualifiedType(Underlying));
13236 }
13237 }
13238 llvm_unreachable("Unhandled Type Class");
13239}
13240
13241static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
13243 while (true) {
13246 if (NT == QualType(T.Ty, 0))
13247 break;
13248 R.push_back(T);
13249 T = NT.split();
13250 }
13251 return R;
13252}
13253
13255 bool Unqualified) {
13256 assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
13257 if (X == Y)
13258 return X;
13259 if (!Unqualified) {
13260 if (X.isCanonical())
13261 return X;
13262 if (Y.isCanonical())
13263 return Y;
13264 }
13265
13266 SplitQualType SX = X.split(), SY = Y.split();
13267 Qualifiers QX, QY;
13268 // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
13269 // until we reach their underlying "canonical nodes". Note these are not
13270 // necessarily canonical types, as they may still have sugared properties.
13271 // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
13272 auto Xs = ::unwrapSugar(SX, QX), Ys = ::unwrapSugar(SY, QY);
13273 if (SX.Ty != SY.Ty) {
13274 // The canonical nodes differ. Build a common canonical node out of the two,
13275 // unifying their sugar. This may recurse back here.
13276 SX.Ty =
13277 ::getCommonNonSugarTypeNode(*this, SX.Ty, QX, SY.Ty, QY).getTypePtr();
13278 } else {
13279 // The canonical nodes were identical: We may have desugared too much.
13280 // Add any common sugar back in.
13281 while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
13282 QX -= SX.Quals;
13283 QY -= SY.Quals;
13284 SX = Xs.pop_back_val();
13285 SY = Ys.pop_back_val();
13286 }
13287 }
13288 if (Unqualified)
13290 else
13291 assert(QX == QY);
13292
13293 // Even though the remaining sugar nodes in Xs and Ys differ, some may be
13294 // related. Walk up these nodes, unifying them and adding the result.
13295 while (!Xs.empty() && !Ys.empty()) {
13296 auto Underlying = SplitQualType(
13297 SX.Ty, Qualifiers::removeCommonQualifiers(SX.Quals, SY.Quals));
13298 SX = Xs.pop_back_val();
13299 SY = Ys.pop_back_val();
13300 SX.Ty = ::getCommonSugarTypeNode(*this, SX.Ty, SY.Ty, Underlying)
13302 // Stop at the first pair which is unrelated.
13303 if (!SX.Ty) {
13304 SX.Ty = Underlying.Ty;
13305 break;
13306 }
13307 QX -= Underlying.Quals;
13308 };
13309
13310 // Add back the missing accumulated qualifiers, which were stripped off
13311 // with the sugar nodes we could not unify.
13312 QualType R = getQualifiedType(SX.Ty, QX);
13313 assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
13314 return R;
13315}
13316
13318 assert(Ty->isFixedPointType());
13319
13321 return Ty;
13322
13323 switch (Ty->castAs<BuiltinType>()->getKind()) {
13324 default:
13325 llvm_unreachable("Not a saturated fixed point type!");
13326 case BuiltinType::SatShortAccum:
13327 return ShortAccumTy;
13328 case BuiltinType::SatAccum:
13329 return AccumTy;
13330 case BuiltinType::SatLongAccum:
13331 return LongAccumTy;
13332 case BuiltinType::SatUShortAccum:
13333 return UnsignedShortAccumTy;
13334 case BuiltinType::SatUAccum:
13335 return UnsignedAccumTy;
13336 case BuiltinType::SatULongAccum:
13337 return UnsignedLongAccumTy;
13338 case BuiltinType::SatShortFract:
13339 return ShortFractTy;
13340 case BuiltinType::SatFract:
13341 return FractTy;
13342 case BuiltinType::SatLongFract:
13343 return LongFractTy;
13344 case BuiltinType::SatUShortFract:
13345 return UnsignedShortFractTy;
13346 case BuiltinType::SatUFract:
13347 return UnsignedFractTy;
13348 case BuiltinType::SatULongFract:
13349 return UnsignedLongFractTy;
13350 }
13351}
13352
13354 assert(Ty->isFixedPointType());
13355
13356 if (Ty->isSaturatedFixedPointType()) return Ty;
13357
13358 switch (Ty->castAs<BuiltinType>()->getKind()) {
13359 default:
13360 llvm_unreachable("Not a fixed point type!");
13361 case BuiltinType::ShortAccum:
13362 return SatShortAccumTy;
13363 case BuiltinType::Accum:
13364 return SatAccumTy;
13365 case BuiltinType::LongAccum:
13366 return SatLongAccumTy;
13367 case BuiltinType::UShortAccum:
13369 case BuiltinType::UAccum:
13370 return SatUnsignedAccumTy;
13371 case BuiltinType::ULongAccum:
13373 case BuiltinType::ShortFract:
13374 return SatShortFractTy;
13375 case BuiltinType::Fract:
13376 return SatFractTy;
13377 case BuiltinType::LongFract:
13378 return SatLongFractTy;
13379 case BuiltinType::UShortFract:
13381 case BuiltinType::UFract:
13382 return SatUnsignedFractTy;
13383 case BuiltinType::ULongFract:
13385 }
13386}
13387
13389 if (LangOpts.OpenCL)
13391
13392 if (LangOpts.CUDA)
13394
13395 return getLangASFromTargetAS(AS);
13396}
13397
13398// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
13399// doesn't include ASTContext.h
13400template
13402 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
13404 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
13405 const clang::ASTContext &Ctx, Decl *Value);
13406
13408 assert(Ty->isFixedPointType());
13409
13410 const TargetInfo &Target = getTargetInfo();
13411 switch (Ty->castAs<BuiltinType>()->getKind()) {
13412 default:
13413 llvm_unreachable("Not a fixed point type!");
13414 case BuiltinType::ShortAccum:
13415 case BuiltinType::SatShortAccum:
13416 return Target.getShortAccumScale();
13417 case BuiltinType::Accum:
13418 case BuiltinType::SatAccum:
13419 return Target.getAccumScale();
13420 case BuiltinType::LongAccum:
13421 case BuiltinType::SatLongAccum:
13422 return Target.getLongAccumScale();
13423 case BuiltinType::UShortAccum:
13424 case BuiltinType::SatUShortAccum:
13425 return Target.getUnsignedShortAccumScale();
13426 case BuiltinType::UAccum:
13427 case BuiltinType::SatUAccum:
13428 return Target.getUnsignedAccumScale();
13429 case BuiltinType::ULongAccum:
13430 case BuiltinType::SatULongAccum:
13431 return Target.getUnsignedLongAccumScale();
13432 case BuiltinType::ShortFract:
13433 case BuiltinType::SatShortFract:
13434 return Target.getShortFractScale();
13435 case BuiltinType::Fract:
13436 case BuiltinType::SatFract:
13437 return Target.getFractScale();
13438 case BuiltinType::LongFract:
13439 case BuiltinType::SatLongFract:
13440 return Target.getLongFractScale();
13441 case BuiltinType::UShortFract:
13442 case BuiltinType::SatUShortFract:
13443 return Target.getUnsignedShortFractScale();
13444 case BuiltinType::UFract:
13445 case BuiltinType::SatUFract:
13446 return Target.getUnsignedFractScale();
13447 case BuiltinType::ULongFract:
13448 case BuiltinType::SatULongFract:
13449 return Target.getUnsignedLongFractScale();
13450 }
13451}
13452
13454 assert(Ty->isFixedPointType());
13455
13456 const TargetInfo &Target = getTargetInfo();
13457 switch (Ty->castAs<BuiltinType>()->getKind()) {
13458 default:
13459 llvm_unreachable("Not a fixed point type!");
13460 case BuiltinType::ShortAccum:
13461 case BuiltinType::SatShortAccum:
13462 return Target.getShortAccumIBits();
13463 case BuiltinType::Accum:
13464 case BuiltinType::SatAccum:
13465 return Target.getAccumIBits();
13466 case BuiltinType::LongAccum:
13467 case BuiltinType::SatLongAccum:
13468 return Target.getLongAccumIBits();
13469 case BuiltinType::UShortAccum:
13470 case BuiltinType::SatUShortAccum:
13471 return Target.getUnsignedShortAccumIBits();
13472 case BuiltinType::UAccum:
13473 case BuiltinType::SatUAccum:
13474 return Target.getUnsignedAccumIBits();
13475 case BuiltinType::ULongAccum:
13476 case BuiltinType::SatULongAccum:
13477 return Target.getUnsignedLongAccumIBits();
13478 case BuiltinType::ShortFract:
13479 case BuiltinType::SatShortFract:
13480 case BuiltinType::Fract:
13481 case BuiltinType::SatFract:
13482 case BuiltinType::LongFract:
13483 case BuiltinType::SatLongFract:
13484 case BuiltinType::UShortFract:
13485 case BuiltinType::SatUShortFract:
13486 case BuiltinType::UFract:
13487 case BuiltinType::SatUFract:
13488 case BuiltinType::ULongFract:
13489 case BuiltinType::SatULongFract:
13490 return 0;
13491 }
13492}
13493
13494llvm::FixedPointSemantics
13496 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
13497 "Can only get the fixed point semantics for a "
13498 "fixed point or integer type.");
13499 if (Ty->isIntegerType())
13500 return llvm::FixedPointSemantics::GetIntegerSemantics(
13501 getIntWidth(Ty), Ty->isSignedIntegerType());
13502
13503 bool isSigned = Ty->isSignedFixedPointType();
13504 return llvm::FixedPointSemantics(
13505 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
13507 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
13508}
13509
13510llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
13511 assert(Ty->isFixedPointType());
13512 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
13513}
13514
13515llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
13516 assert(Ty->isFixedPointType());
13517 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
13518}
13519
13521 assert(Ty->isUnsignedFixedPointType() &&
13522 "Expected unsigned fixed point type");
13523
13524 switch (Ty->castAs<BuiltinType>()->getKind()) {
13525 case BuiltinType::UShortAccum:
13526 return ShortAccumTy;
13527 case BuiltinType::UAccum:
13528 return AccumTy;
13529 case BuiltinType::ULongAccum:
13530 return LongAccumTy;
13531 case BuiltinType::SatUShortAccum:
13532 return SatShortAccumTy;
13533 case BuiltinType::SatUAccum:
13534 return SatAccumTy;
13535 case BuiltinType::SatULongAccum:
13536 return SatLongAccumTy;
13537 case BuiltinType::UShortFract:
13538 return ShortFractTy;
13539 case BuiltinType::UFract:
13540 return FractTy;
13541 case BuiltinType::ULongFract:
13542 return LongFractTy;
13543 case BuiltinType::SatUShortFract:
13544 return SatShortFractTy;
13545 case BuiltinType::SatUFract:
13546 return SatFractTy;
13547 case BuiltinType::SatULongFract:
13548 return SatLongFractTy;
13549 default:
13550 llvm_unreachable("Unexpected unsigned fixed point type");
13551 }
13552}
13553
13555 const TargetVersionAttr *TV) const {
13556 assert(TV != nullptr);
13558 std::vector<std::string> ResFeats;
13559 TV->getFeatures(Feats);
13560 for (auto &Feature : Feats)
13561 if (Target->validateCpuSupports(Feature.str()))
13562 // Use '?' to mark features that came from TargetVersion.
13563 ResFeats.push_back("?" + Feature.str());
13564 return ResFeats;
13565}
13566
13568ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
13569 assert(TD != nullptr);
13570 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TD->getFeaturesStr());
13571
13572 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) {
13573 return !Target->isValidFeatureName(StringRef{Feat}.substr(1));
13574 });
13575 return ParsedAttr;
13576}
13577
13578void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
13579 const FunctionDecl *FD) const {
13580 if (FD)
13581 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
13582 else
13583 Target->initFeatureMap(FeatureMap, getDiagnostics(),
13584 Target->getTargetOpts().CPU,
13585 Target->getTargetOpts().Features);
13586}
13587
13588// Fills in the supplied string map with the set of target features for the
13589// passed in function.
13590void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
13591 GlobalDecl GD) const {
13592 StringRef TargetCPU = Target->getTargetOpts().CPU;
13593 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
13594 if (const auto *TD = FD->getAttr<TargetAttr>()) {
13596
13597 // Make a copy of the features as passed on the command line into the
13598 // beginning of the additional features from the function to override.
13599 ParsedAttr.Features.insert(
13600 ParsedAttr.Features.begin(),
13601 Target->getTargetOpts().FeaturesAsWritten.begin(),
13602 Target->getTargetOpts().FeaturesAsWritten.end());
13603
13604 if (ParsedAttr.CPU != "" && Target->isValidCPUName(ParsedAttr.CPU))
13605 TargetCPU = ParsedAttr.CPU;
13606
13607 // Now populate the feature map, first with the TargetCPU which is either
13608 // the default or a new one from the target attribute string. Then we'll use
13609 // the passed in features (FeaturesAsWritten) along with the new ones from
13610 // the attribute.
13611 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
13612 ParsedAttr.Features);
13613 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
13615 Target->getCPUSpecificCPUDispatchFeatures(
13616 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
13617 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
13618 Features.insert(Features.begin(),
13619 Target->getTargetOpts().FeaturesAsWritten.begin(),
13620 Target->getTargetOpts().FeaturesAsWritten.end());
13621 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
13622 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
13623 std::vector<std::string> Features;
13624 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
13625 if (Target->getTriple().isAArch64()) {
13626 // TargetClones for AArch64
13627 if (VersionStr != "default") {
13628 SmallVector<StringRef, 1> VersionFeatures;
13629 VersionStr.split(VersionFeatures, "+");
13630 for (auto &VFeature : VersionFeatures) {
13631 VFeature = VFeature.trim();
13632 // Use '?' to mark features that came from AArch64 TargetClones.
13633 Features.push_back((StringRef{"?"} + VFeature).str());
13634 }
13635 }
13636 Features.insert(Features.begin(),
13637 Target->getTargetOpts().FeaturesAsWritten.begin(),
13638 Target->getTargetOpts().FeaturesAsWritten.end());
13639 } else {
13640 if (VersionStr.starts_with("arch="))
13641 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
13642 else if (VersionStr != "default")
13643 Features.push_back((StringRef{"+"} + VersionStr).str());
13644 }
13645 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
13646 } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
13647 std::vector<std::string> Feats = filterFunctionTargetVersionAttrs(TV);
13648 Feats.insert(Feats.begin(),
13649 Target->getTargetOpts().FeaturesAsWritten.begin(),
13650 Target->getTargetOpts().FeaturesAsWritten.end());
13651 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Feats);
13652 } else {
13653 FeatureMap = Target->getTargetOpts().FeatureMap;
13654 }
13655}
13656
13658 OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
13659 return *OMPTraitInfoVector.back();
13660}
13661
13664 const ASTContext::SectionInfo &Section) {
13665 if (Section.Decl)
13666 return DB << Section.Decl;
13667 return DB << "a prior #pragma section";
13668}
13669
13670bool ASTContext::mayExternalize(const Decl *D) const {
13671 bool IsInternalVar =
13672 isa<VarDecl>(D) &&
13673 basicGVALinkageForVariable(*this, cast<VarDecl>(D)) == GVA_Internal;
13674 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
13675 !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
13676 (D->hasAttr<CUDAConstantAttr>() &&
13677 !D->getAttr<CUDAConstantAttr>()->isImplicit());
13678 // CUDA/HIP: managed variables need to be externalized since it is
13679 // a declaration in IR, therefore cannot have internal linkage. Kernels in
13680 // anonymous name space needs to be externalized to avoid duplicate symbols.
13681 return (IsInternalVar &&
13682 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
13683 (D->hasAttr<CUDAGlobalAttr>() &&
13684 basicGVALinkageForFunction(*this, cast<FunctionDecl>(D)) ==
13685 GVA_Internal);
13686}
13687
13689 return mayExternalize(D) &&
13690 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
13691 CUDADeviceVarODRUsedByHost.count(cast<VarDecl>(D)));
13692}
13693
13694StringRef ASTContext::getCUIDHash() const {
13695 if (!CUIDHash.empty())
13696 return CUIDHash;
13697 if (LangOpts.CUID.empty())
13698 return StringRef();
13699 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
13700 return CUIDHash;
13701}
This file provides AST data structures related to concepts.
static void SortAndUniqueProtocols(SmallVectorImpl< ObjCProtocolDecl * > &Protocols)
static bool isCanonicalExceptionSpecification(const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType)
static SourceLocation getCommonAttrLoc(const T *X, const T *Y)
static auto getCommonTypes(ASTContext &Ctx, ArrayRef< QualType > Xs, ArrayRef< QualType > Ys, bool Unqualified=false)
static auto getCanonicalTemplateArguments(const ASTContext &C, ArrayRef< TemplateArgument > Args, bool &AnyNonCanonArgs)
static char getObjCEncodingForPrimitiveType(const ASTContext *C, const BuiltinType *BT)
static bool NeedsInjectedClassNameType(const RecordDecl *D)
#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS)
static bool unionHasUniqueObjectRepresentations(const ASTContext &Context, const RecordDecl *RD, bool CheckIfTriviallyCopyable)
static NamespaceDecl * getNamespace(const NestedNameSpecifier *X)
static TypedefDecl * CreateHexagonBuiltinVaListDecl(const ASTContext *Context)
#define CANONICAL_TYPE(Class)
static NestedNameSpecifier * getCommonNNS(ASTContext &Ctx, const T *X, const T *Y)
static Decl * getCommonDecl(Decl *X, Decl *Y)
static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context, const Decl *D, GVALinkage L)
static bool isTypeTypedefedAsBOOL(QualType T)
static void EncodeBitField(const ASTContext *Ctx, std::string &S, QualType T, const FieldDecl *FD)
static GVALinkage basicGVALinkageForVariable(const ASTContext &Context, const VarDecl *VD)
static uint64_t getSVETypeSize(ASTContext &Context, const BuiltinType *Ty)
getSVETypeSize - Return SVE vector or predicate register size.
#define SUGAR_FREE_TYPE(Class)
static bool getCommonTemplateArguments(ASTContext &Ctx, SmallVectorImpl< TemplateArgument > &R, ArrayRef< TemplateArgument > Xs, ArrayRef< TemplateArgument > Ys)
static bool hasTemplateSpecializationInEncodedString(const Type *T, bool VisitBasesAndFields)
static void getIntersectionOfProtocols(ASTContext &Context, const ObjCInterfaceDecl *CommonBase, const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT, SmallVectorImpl< ObjCProtocolDecl * > &IntersectionSet)
getIntersectionOfProtocols - This routine finds the intersection of set of protocols inherited from t...
static bool areCompatMatrixTypes(const ConstantMatrixType *LHS, const ConstantMatrixType *RHS)
areCompatMatrixTypes - Return true if the two specified matrix types are compatible.
static TypedefDecl * CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context)
static bool sameObjCTypeArgs(ASTContext &ctx, const ObjCInterfaceDecl *iface, ArrayRef< QualType > lhsArgs, ArrayRef< QualType > rhsArgs, bool stripKindOf)
static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs, QualType rhs)
Determine whether the first type is a subtype of the second.
static const Type * getIntegerTypeForEnum(const EnumType *ET)
static TemplateName getCommonTemplateNameChecked(ASTContext &Ctx, TemplateName X, TemplateName Y)
static const Decl & adjustDeclToTemplate(const Decl &D)
If we have a 'templated' declaration for a template, adjust 'D' to refer to the actual template.
Definition: ASTContext.cpp:335
static int CmpProtocolNames(ObjCProtocolDecl *const *LHS, ObjCProtocolDecl *const *RHS)
CmpProtocolNames - Comparison predicate for sorting protocols alphabetically.
static QualType getCommonElementType(ASTContext &Ctx, const T *X, const T *Y)
static TypedefDecl * CreatePowerABIBuiltinVaListDecl(const ASTContext *Context)
static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y)
static std::optional< int64_t > structHasUniqueObjectRepresentations(const ASTContext &Context, const RecordDecl *RD, bool CheckIfTriviallyCopyable)
static TemplateName getCommonTemplateName(ASTContext &Ctx, TemplateName X, TemplateName Y)
static bool hasSameOverloadableAttrs(const FunctionDecl *A, const FunctionDecl *B)
Determine whether the attributes we can overload on are identical for A and B.
static T * getCommonDeclChecked(T *X, T *Y)
static TypedefDecl * CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context)
static int64_t getSubobjectOffset(const FieldDecl *Field, const ASTContext &Context, const clang::ASTRecordLayout &)
static TypedefDecl * CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context)
static TypedefDecl * CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context)
static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET, QualType other, bool isBlockReturnType)
Given that we have an enum type and a non-enum type, try to merge them.
static GVALinkage adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D, GVALinkage L)
Adjust the GVALinkage for a declaration based on what an external AST source knows about whether ther...
static TypedefDecl * CreateSystemZBuiltinVaListDecl(const ASTContext *Context)
static std::optional< int64_t > getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context, bool CheckIfTriviallyCopyable)
static GVALinkage basicGVALinkageForFunction(const ASTContext &Context, const FunctionDecl *FD)
#define NON_UNIQUE_TYPE(Class)
static TypedefDecl * CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context)
static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI, const LangOptions &LangOpts)
Definition: ASTContext.cpp:857
static auto getCommonIndexTypeCVRQualifiers(const ArrayType *X, const ArrayType *Y)
#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS)
static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, ASTContext::GetBuiltinTypeError &Error, bool &RequiresICE, bool AllowTypeModifiers)
DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the pointer over the consume...
FloatingRank
Definition: ASTContext.cpp:105
@ FloatRank
Definition: ASTContext.cpp:109
@ LongDoubleRank
Definition: ASTContext.cpp:111
@ Float16Rank
Definition: ASTContext.cpp:107
@ Ibm128Rank
Definition: ASTContext.cpp:113
@ Float128Rank
Definition: ASTContext.cpp:112
@ BFloat16Rank
Definition: ASTContext.cpp:106
@ HalfRank
Definition: ASTContext.cpp:108
@ DoubleRank
Definition: ASTContext.cpp:110
static TypedefDecl * CreateCharPtrBuiltinVaListDecl(const ASTContext *Context)
static void mergeTypeLists(ASTContext &Ctx, SmallVectorImpl< QualType > &Out, ArrayRef< QualType > X, ArrayRef< QualType > Y)
static bool areSortedAndUniqued(ArrayRef< ObjCProtocolDecl * > Protocols)
static TypeInfoChars getConstantArrayInfoInChars(const ASTContext &Context, const ConstantArrayType *CAT)
getConstantArrayInfoInChars - Performing the computation in CharUnits instead of in bits prevents ove...
static FloatingRank getFloatingRank(QualType T)
getFloatingRank - Return a relative rank for floating point types.
static TemplateArgument getCommonTemplateArgument(ASTContext &Ctx, const TemplateArgument &X, const TemplateArgument &Y)
static auto * getCommonSizeExpr(ASTContext &Ctx, T *X, T *Y)
static std::optional< int64_t > structSubobjectsHaveUniqueObjectRepresentations(const RangeT &Subobjects, int64_t CurOffsetInBits, const ASTContext &Context, const clang::ASTRecordLayout &Layout, bool CheckIfTriviallyCopyable)
static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET)
static QualType getCommonArrayElementType(ASTContext &Ctx, const T *X, Qualifiers &QX, const T *Y, Qualifiers &QY)
static QualType getCommonPointeeType(ASTContext &Ctx, const T *X, const T *Y)
static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty)
getRVVTypeSize - Return RVV vector register size.
static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal)
static int compareObjCProtocolsByName(ObjCProtocolDecl *const *lhs, ObjCProtocolDecl *const *rhs)
Comparison routine for Objective-C protocols to be used with llvm::array_pod_sort.
static QualType getCommonNonSugarTypeNode(ASTContext &Ctx, const Type *X, Qualifiers &QX, const Type *Y, Qualifiers &QY)
static QualType getCommonSugarTypeNode(ASTContext &Ctx, const Type *X, const Type *Y, SplitQualType Underlying)
static bool isSameQualifier(const NestedNameSpecifier *X, const NestedNameSpecifier *Y)
static std::string charUnitsToString(const CharUnits &CU)
static bool hasAnyPackExpansions(ArrayRef< TemplateArgument > Args)
static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod, SmallVectorImpl< const NamedDecl * > &Redeclared)
Definition: ASTContext.cpp:479
static SmallVector< SourceLocation, 2 > getDeclLocsForCommentSearch(const Decl *D, SourceManager &SourceMgr)
Definition: ASTContext.cpp:119
static bool isCanonicalResultType(QualType T)
Determine whether T is canonical as the result type of a function.
static TypedefDecl * CreateMSVaListDecl(const ASTContext *Context)
static bool areCompatVectorTypes(const VectorType *LHS, const VectorType *RHS)
areCompatVectorTypes - Return true if the two specified vector types are compatible.
static TypedefDecl * CreateCharPtrNamedVaListDecl(const ASTContext *Context, StringRef Name)
#define UNEXPECTED_TYPE(Class, Kind)
static TypedefDecl * CreateVaListDecl(const ASTContext *Context, TargetInfo::BuiltinVaListKind Kind)
static ElaboratedTypeKeyword getCommonTypeKeyword(const T *X, const T *Y)
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3259
NodeId Parent
Definition: ASTDiff.cpp:191
int Id
Definition: ASTDiff.cpp:190
StringRef P
Provides definitions for the various language-specific address spaces.
static bool isUnsigned(SValBuilder &SVB, NonLoc Value)
#define SM(sm)
Definition: Cuda.cpp:82
static constexpr Builtin::Info BuiltinInfo[]
Definition: Builtins.cpp:32
Defines enum values for all the target-independent builtin functions.
static bool CanThrow(Expr *E, ASTContext &Ctx)
Definition: CFG.cpp:2679
Defines the clang::CommentOptions interface.
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1110
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
This file defines OpenMP nodes for declarative directives.
Defines the C++ template declaration subclasses.
Defines the ExceptionSpecificationType enumeration and various utility functions.
Defines the clang::Expr interface and subclasses for C++ expressions.
Defines Expressions and AST nodes for C++2a concepts.
StringRef Text
Definition: Format.cpp:2953
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
static const Decl * getCanonicalDecl(const Decl *D)
#define X(type, name)
Definition: Value.h:142
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
llvm::MachO::Target Target
Definition: MachO.h:40
llvm::MachO::Record Record
Definition: MachO.h:28
static bool hasFeature(StringRef Feature, const LangOptions &LangOpts, const TargetInfo &Target)
Determine whether a translation unit built using the current language options has the given feature.
Definition: Module.cpp:100
Defines the clang::Module class, which describes a module in the source code.
Defines types useful for describing an Objective-C runtime.
static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y)
static QualType getUnderlyingType(const SubRegion *R)
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
This file defines OpenACC AST classes for statement-level contructs.
Defines the TargetCXXABI class, which abstracts details of the C++ ABI that we're targeting.
Defines the clang::TypeLoc interface and its subclasses.
static const TemplateArgument & getArgument(const TemplateArgument &A)
C Language Family Type Representation.
SourceLocation Begin
__device__ __2f16 float c
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
bool isMemberPointerToDerivedMember() const
Definition: APValue.cpp:1060
const ValueDecl * getMemberPointerDecl() const
Definition: APValue.cpp:1053
ArrayRef< const CXXRecordDecl * > getMemberPointerPath() const
Definition: APValue.cpp:1067
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
bool getByrefLifetime(QualType Ty, Qualifiers::ObjCLifetime &Lifetime, bool &HasByrefExtendedLayout) const
Returns true, if given type has a known lifetime.
MSGuidDecl * getMSGuidDecl(MSGuidDeclParts Parts) const
Return a declaration for the global GUID object representing the given GUID value.
QualType getUsingType(const UsingShadowDecl *Found, QualType Underlying) const
CanQualType AccumTy
Definition: ASTContext.h:1099
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, const ObjCMethodDecl *MethodImp)
CanQualType ObjCBuiltinSelTy
Definition: ASTContext.h:1117
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1068
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2742
CanQualType getCanonicalFunctionResultType(QualType ResultType) const
Adjust the given function result type.
QualType getAtomicType(QualType T) const
Return the uniqued reference to the atomic type for the specified type.
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
llvm::PointerUnion< VarTemplateDecl *, MemberSpecializationInfo * > TemplateOrSpecializationInfo
A type synonym for the TemplateOrInstantiation mapping.
Definition: ASTContext.h:471
LangAS getOpenCLTypeAddrSpace(const Type *T) const
Get address space for OpenCL type.
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
void InitBuiltinTypes(const TargetInfo &Target, const TargetInfo *AuxTarget=nullptr)
Initialize built-in types.
ParentMapContext & getParentMapContext()
Returns the dynamic AST node parent map context.
Definition: ASTContext.cpp:851
QualType getParenType(QualType NamedType) const
size_t getSideTableAllocatedMemory() const
Return the total memory used for various side tables.
MemberSpecializationInfo * getInstantiatedFromStaticDataMember(const VarDecl *Var)
If this variable is an instantiated static data member of a class template specialization,...
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
CanQualType ARCUnbridgedCastTy
Definition: ASTContext.h:1116
QualType getDependentSizedMatrixType(QualType ElementType, Expr *RowExpr, Expr *ColumnExpr, SourceLocation AttrLoc) const
Return the unique reference to the matrix type of the specified element type and size.
llvm::DenseMap< const Decl *, comments::FullComment * > ParsedComments
Mapping from declarations to parsed comments attached to any redeclaration.
Definition: ASTContext.h:829
unsigned getManglingNumber(const NamedDecl *ND, bool ForAuxTarget=false) const
CanQualType LongTy
Definition: ASTContext.h:1095
void UnwrapSimilarArrayTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true)
Attempt to unwrap two types that may both be array types with the same bound (or both be array types ...
unsigned getIntWidth(QualType T) const
CanQualType getCanonicalParamType(QualType T) const
Return the canonical parameter type corresponding to the specific potentially non-canonical one.
QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr, QualType Wrapped)
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
TemplateOrSpecializationInfo getTemplateOrSpecializationInfo(const VarDecl *Var)
CanQualType WIntTy
Definition: ASTContext.h:1091
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType) const
@ Weak
Weak definition of inline variable.
@ WeakUnknown
Weak for now, might become strong later in this TU.
void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl)
TypedefDecl * getObjCClassDecl() const
Retrieve the typedef declaration corresponding to the predefined Objective-C 'Class' type.
TypedefNameDecl * getTypedefNameForUnnamedTagDecl(const TagDecl *TD)
TypedefDecl * getCFConstantStringDecl() const
CanQualType Int128Ty
Definition: ASTContext.h:1095
CanQualType SatUnsignedFractTy
Definition: ASTContext.h:1108
BuiltinTemplateDecl * getMakeIntegerSeqDecl() const
void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern)
Remember that the using decl Inst is an instantiation of the using decl Pattern of a class template.
bool areCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an RISC-V vector builtin type and a VectorType that is a fixed-len...
ExternCContextDecl * getExternCContextDecl() const
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
ParsedTargetAttr filterFunctionTargetAttrs(const TargetAttr *TD) const
Parses the target attributes passed in, and returns only the ones that are valid feature names.
QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent, bool IsPack=false, ConceptDecl *TypeConstraintConcept=nullptr, ArrayRef< TemplateArgument > TypeConstraintArgs={}) const
C++11 deduced auto type.
QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
TypedefDecl * getObjCSelDecl() const
Retrieve the typedef corresponding to the predefined 'SEL' type in Objective-C.
CanQualType UnsignedShortAccumTy
Definition: ASTContext.h:1101
TypedefDecl * getObjCInstanceTypeDecl()
Retrieve the typedef declaration corresponding to the Objective-C "instancetype" type.
uint64_t getFieldOffset(const ValueDecl *FD) const
Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, ArrayRef< TemplateArgumentLoc > Args) const
void setTemplateOrSpecializationInfo(VarDecl *Inst, TemplateOrSpecializationInfo TSI)
bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, ObjCProtocolDecl *rProto) const
ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the inheritance hierarchy of 'rProto...
bool hasSimilarType(QualType T1, QualType T2)
Determine if two types are similar, according to the C++ rules.
TypedefDecl * buildImplicitTypedef(QualType T, StringRef Name) const
Create a new implicit TU-level typedef declaration.
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
getObjCInterfaceType - Return the unique reference to the type for the specified ObjC interface decl.
void adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig, ObjCTypeParamDecl *New) const
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
QualType getAutoRRefDeductType() const
C++11 deduction pattern for 'auto &&' type.
TypedefDecl * getBuiltinMSVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_ms_va_list type.
bool ObjCQualifiedIdTypesAreCompatible(const ObjCObjectPointerType *LHS, const ObjCObjectPointerType *RHS, bool ForCompare)
ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an ObjCQualifiedIDType.
void addLazyModuleInitializers(Module *M, ArrayRef< uint32_t > IDs)
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
QualType getBuiltinVaListType() const
Retrieve the type of the __builtin_va_list type.
Definition: ASTContext.h:2103
QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool AllowCXX=false, bool IsConditionalOperator=false)
NamedDecl * getInstantiatedFromUsingDecl(NamedDecl *Inst)
If the given using decl Inst is an instantiation of another (possibly unresolved) using decl,...
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:643
comments::FullComment * cloneFullComment(comments::FullComment *FC, const Decl *D) const
Definition: ASTContext.cpp:558
TemplateName getCanonicalTemplateName(const TemplateName &Name) const
Retrieves the "canonical" template name that refers to a given template.
QualType getUnresolvedUsingType(const UnresolvedUsingTypenameDecl *Decl) const
CharUnits getObjCEncodingTypeSize(QualType T) const
Return the size of type T for Objective-C encoding purpose, in characters.
int getIntegerTypeOrder(QualType LHS, QualType RHS) const
Return the highest ranked integer type, see C99 6.3.1.8p1.
TypedefDecl * getObjCIdDecl() const
Retrieve the typedef corresponding to the predefined id type in Objective-C.
void setCurrentNamedModule(Module *M)
Set the (C++20) module we are building.
QualType getProcessIDType() const
Return the unique type for "pid_t" defined in <sys/types.h>.
CharUnits getMemberPointerPathAdjustment(const APValue &MP) const
Find the 'this' offset for the member path in a pointer-to-member APValue.
bool mayExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel may be externalized.
QualType getTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > Args, QualType Canon=QualType()) const
std::unique_ptr< MangleNumberingContext > createMangleNumberingContext() const
CanQualType SatAccumTy
Definition: ASTContext.h:1104
QualType getUnsignedPointerDiffType() const
Return the unique unsigned counterpart of "ptrdiff_t" integer type.
QualType getucontext_tType() const
Retrieve the C ucontext_t type.
Definition: ASTContext.h:1977
QualType getRecordType(const RecordDecl *Decl) const
QualType getScalableVectorType(QualType EltTy, unsigned NumElts, unsigned NumFields=1) const
Return the unique reference to a scalable vector type of the specified element type and scalable numb...
bool hasSameExpr(const Expr *X, const Expr *Y) const
Determine whether the given expressions X and Y are equivalent.
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
MangleContext * createMangleContext(const TargetInfo *T=nullptr)
If T is null pointer, assume the target in ASTContext.
QualType getRealTypeForBitwidth(unsigned DestWidth, FloatModeKind ExplicitType) const
getRealTypeForBitwidth - sets floating point QualTy according to specified bitwidth.
QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const
getInjectedClassNameType - Return the unique reference to the injected class name type for the specif...
QualType getVariableArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals, SourceRange Brackets) const
Return a non-unique reference to the type for a variable array of the specified element type.
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
CanQualType ShortAccumTy
Definition: ASTContext.h:1099
ASTMutationListener * getASTMutationListener() const
Retrieve a pointer to the AST mutation listener associated with this AST context, if any.
Definition: ASTContext.h:1197
unsigned NumImplicitCopyAssignmentOperatorsDeclared
The number of implicitly-declared copy assignment operators for which declarations were built.
Definition: ASTContext.h:3209
uint64_t getTargetNullPointerValue(QualType QT) const
Get target-dependent integer value for null pointer which is used for constant folding.
unsigned getTypeUnadjustedAlign(QualType T) const
Return the ABI-specified natural alignment of a (complete) type T, before alignment adjustments,...
Definition: ASTContext.h:2354
unsigned char getFixedPointIBits(QualType Ty) const
QualType getCorrespondingSignedFixedPointType(QualType Ty) const
CanQualType FloatTy
Definition: ASTContext.h:1098
QualType getPackExpansionType(QualType Pattern, std::optional< unsigned > NumExpansions, bool ExpectPackInType=true)
Form a pack expansion type with the given pattern.
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2549
unsigned NumImplicitDestructorsDeclared
The number of implicitly-declared destructors for which declarations were built.
Definition: ASTContext.h:3223
bool mergeExtParameterInfo(const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType, bool &CanUseFirst, bool &CanUseSecond, SmallVectorImpl< FunctionProtoType::ExtParameterInfo > &NewParamInfos)
This function merges the ExtParameterInfo lists of two functions.
bool ObjCQualifiedClassTypesAreCompatible(const ObjCObjectPointerType *LHS, const ObjCObjectPointerType *RHS)
ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and Class<pr1, ...>.
bool shouldExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel should be externalized.
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2565
bool propertyTypesAreCompatible(QualType, QualType)
void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, UsingShadowDecl *Pattern)
CanQualType DoubleTy
Definition: ASTContext.h:1098
TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
QualType getDependentVectorType(QualType VectorType, Expr *SizeExpr, SourceLocation AttrLoc, VectorKind VecKind) const
Return the unique reference to the type for a dependently sized vector of the specified element type.
CanQualType SatLongAccumTy
Definition: ASTContext.h:1104
CanQualType getIntMaxType() const
Return the unique type for "intmax_t" (C99 7.18.1.5), defined in <stdint.h>.
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
std::vector< std::string > filterFunctionTargetVersionAttrs(const TargetVersionAttr *TV) const
OpenCLTypeKind getOpenCLTypeKind(const Type *T) const
Map an AST Type to an OpenCLTypeKind enum value.
QualType getFILEType() const
Retrieve the C FILE type.
Definition: ASTContext.h:1941
ArrayRef< Decl * > getModuleInitializers(Module *M)
Get the initializations to perform when importing a module, if any.
void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, std::string &S) const
Put the string version of the type qualifiers QT into S.
unsigned getPreferredTypeAlign(QualType T) const
Return the "preferred" alignment of the specified type T for the current target, in bits.
Definition: ASTContext.h:2406
void getInjectedTemplateArgs(const TemplateParameterList *Params, SmallVectorImpl< TemplateArgument > &Args)
Get a template argument list with one argument per template parameter in a template parameter list,...
std::string getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, bool Extended=false) const
Emit the encoded type for the method declaration Decl into S.
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
CanQualType LongDoubleTy
Definition: ASTContext.h:1098
CanQualType OMPArrayShapingTy
Definition: ASTContext.h:1125
ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents, SelectorTable &sels, Builtin::Context &builtins, TranslationUnitKind TUKind)
Definition: ASTContext.cpp:870
QualType getReadPipeType(QualType T) const
Return a read_only pipe type for the specified type.
std::string getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, const Decl *Container) const
getObjCEncodingForPropertyDecl - Return the encoded type for this method declaration.
CanQualType Char16Ty
Definition: ASTContext.h:1093
unsigned getStaticLocalNumber(const VarDecl *VD) const
void addComment(const RawComment &RC)
Definition: ASTContext.cpp:326
void getLegacyIntegralTypeEncoding(QualType &t) const
getLegacyIntegralTypeEncoding - Another legacy compatibility encoding: 32-bit longs are encoded as 'l...
bool isSameTypeConstraint(const TypeConstraint *XTC, const TypeConstraint *YTC) const
Determine whether two type contraint are similar enough that they could used in declarations of the s...
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod, bool IsBuiltin=false) const
Retrieves the default calling convention for the current target.
RecordDecl * buildImplicitRecord(StringRef Name, RecordDecl::TagKind TK=RecordDecl::TagKind::Struct) const
Create a new implicit TU-level CXXRecordDecl or RecordDecl declaration.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
QualType getMSGuidType() const
Retrieve the implicitly-predeclared 'struct _GUID' type.
Definition: ASTContext.h:2125
const CXXMethodDecl * getCurrentKeyFunction(const CXXRecordDecl *RD)
Get our current best idea for the key function of the given record decl, or nullptr if there isn't on...
const ASTRecordLayout & getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const
Get or compute information about the layout of the specified Objective-C implementation.
CanQualType UnsignedLongFractTy
Definition: ASTContext.h:1103
QualType getEnumType(const EnumDecl *Decl) const
overridden_method_range overridden_methods(const CXXMethodDecl *Method) const
QualType getDependentBitIntType(bool Unsigned, Expr *BitsExpr) const
Return a dependent bit-precise integer type with the specified signedness and bit count.
void setObjCImplementation(ObjCInterfaceDecl *IFaceD, ObjCImplementationDecl *ImplD)
Set the implementation of ObjCInterfaceDecl.
StringRef getCUIDHash() const
bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const
Returns true if this is an inline-initialized static data member which is treated as a definition for...
bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
canAssignObjCInterfaces - Return true if the two interface types are compatible for assignment from R...
CanQualType VoidPtrTy
Definition: ASTContext.h:1113
QualType getReferenceQualifiedType(const Expr *e) const
getReferenceQualifiedType - Given an expr, will return the type for that expression,...
bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U) const
Determine whether two function types are the same, ignoring exception specifications in cases where t...
QualType getBlockDescriptorExtendedType() const
Gets the struct used to keep track of the extended descriptor for pointer to blocks.
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
Definition: ASTContext.h:1114
IdentifierInfo * getMakeIntegerSeqName() const
Definition: ASTContext.h:1915
bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT, ObjCInterfaceDecl *IDecl)
QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in QT's qualified-id protocol list adopt...
bool isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const
Determine whether two 'requires' expressions are similar enough that they may be used in re-declarati...
IdentifierInfo * getTypePackElementName() const
Definition: ASTContext.h:1921
bool BlockRequiresCopying(QualType Ty, const VarDecl *D)
Returns true iff we need copy/dispose helpers for the given type.
CanQualType NullPtrTy
Definition: ASTContext.h:1113
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1575
CanQualType WideCharTy
Definition: ASTContext.h:1090
CanQualType OMPIteratorTy
Definition: ASTContext.h:1125
IdentifierTable & Idents
Definition: ASTContext.h:639
TemplateName getSubstTemplateTemplateParm(TemplateName replacement, Decl *AssociatedDecl, unsigned Index, std::optional< unsigned > PackIndex) const
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:641
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
void addModuleInitializer(Module *M, Decl *Init)
Add a declaration to the list of declarations that are initialized for a module.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:770
TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl)
QualType getFunctionTypeWithoutPtrSizes(QualType T)
Get a function type and produce the equivalent function type where pointer size address spaces in the...
llvm::iterator_range< overridden_cxx_method_iterator > overridden_method_range
Definition: ASTContext.h:996
unsigned getMinGlobalAlignOfVar(uint64_t Size, const VarDecl *VD) const
Return the minimum alignement as specified by the target.
RawCommentList Comments
All comments in this translation unit.
Definition: ASTContext.h:800
bool isSameDefaultTemplateArgument(const NamedDecl *X, const NamedDecl *Y) const
Determine whether two default template arguments are similar enough that they may be used in declarat...
QualType applyObjCProtocolQualifiers(QualType type, ArrayRef< ObjCProtocolDecl * > protocols, bool &hasError, bool allowOnPointerType=false) const
Apply Objective-C protocol qualifiers to the given type.
QualType getMacroQualifiedType(QualType UnderlyingTy, const IdentifierInfo *MacroII) const
QualType removePtrSizeAddrSpace(QualType T) const
Remove the existing address space on the type if it is a pointer size address space and return the ty...
bool areLaxCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible RISC-V vector types as defined by -flax-vect...
CanQualType SatShortFractTy
Definition: ASTContext.h:1107
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
bool canBindObjCObjectType(QualType To, QualType From)
int getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const
Compare the rank of two floating point types as above, but compare equal if both types have the same ...
QualType getUIntPtrType() const
Return a type compatible with "uintptr_t" (C99 7.18.1.4), as defined by the target.
void setParameterIndex(const ParmVarDecl *D, unsigned index)
Used by ParmVarDecl to store on the side the index of the parameter when it exceeds the size of the n...
QualType getFunctionTypeWithExceptionSpec(QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const
Get a function type and produce the equivalent function type with the specified exception specificati...
Qualifiers::GC getObjCGCAttrKind(QualType Ty) const
Return one of the GCNone, Weak or Strong Objective-C garbage collection attributes.
CanQualType Ibm128Ty
Definition: ASTContext.h:1098
bool hasUniqueObjectRepresentations(QualType Ty, bool CheckIfTriviallyCopyable=true) const
Return true if the specified type has unique object representations according to (C++17 [meta....
bool typesAreBlockPointerCompatible(QualType, QualType)
CanQualType SatUnsignedAccumTy
Definition: ASTContext.h:1105
const ASTRecordLayout & getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const
Get or compute information about the layout of the specified Objective-C interface.
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
void setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst, UsingEnumDecl *Pattern)
Remember that the using enum decl Inst is an instantiation of the using enum decl Pattern of a class ...
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
QualType getSignatureParameterType(QualType T) const
Retrieve the parameter type as adjusted for use in the signature of a function, decaying array and fu...
QualType getCanonicalTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > Args) const
CanQualType ObjCBuiltinIdTy
Definition: ASTContext.h:1117
overridden_cxx_method_iterator overridden_methods_end(const CXXMethodDecl *Method) const
VTableContextBase * getVTableContext()
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const
ObjCPropertyImplDecl * getObjCPropertyImplDeclForPropertyDecl(const ObjCPropertyDecl *PD, const Decl *Container) const
bool isNearlyEmpty(const CXXRecordDecl *RD) const
QualType AutoDeductTy
Definition: ASTContext.h:1142
CanQualType BoolTy
Definition: ASTContext.h:1087
void cacheRawCommentForDecl(const Decl &OriginalD, const RawComment &Comment) const
Attaches Comment to OriginalD and to its redeclaration chain and removes the redeclaration chain from...
Definition: ASTContext.cpp:470
void attachCommentsToJustParsedDecls(ArrayRef< Decl * > Decls, const Preprocessor *PP)
Searches existing comments for doc comments that should be attached to Decls.
Definition: ASTContext.cpp:496
QualType getIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
getIntTypeForBitwidth - sets integer QualTy according to specified details: bitwidth,...
void setStaticLocalNumber(const VarDecl *VD, unsigned Number)
QualType getCFConstantStringType() const
Return the C structure type used to represent constant CFStrings.
FieldDecl * getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field)
void eraseDeclAttrs(const Decl *D)
Erase the attributes corresponding to the given declaration.
UsingEnumDecl * getInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst)
If the given using-enum decl Inst is an instantiation of another using-enum decl, return it.
RecordDecl * getCFConstantStringTagDecl() const
QualType getObjCSelType() const
Retrieve the type that corresponds to the predefined Objective-C 'SEL' type.
Definition: ASTContext.h:2058
QualType getDeducedTemplateSpecializationType(TemplateName Template, QualType DeducedType, bool IsDependent) const
C++17 deduced class template specialization type.
std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const
Emit the encoded type for the function Decl into S.
QualType getTemplateTypeParmType(unsigned Depth, unsigned Index, bool ParameterPack, TemplateTypeParmDecl *ParmDecl=nullptr) const
Retrieve the template type parameter type for a template parameter or parameter pack with the given d...
CanQualType UnsignedFractTy
Definition: ASTContext.h:1103
QualType getjmp_bufType() const
Retrieve the C jmp_buf type.
Definition: ASTContext.h:1953
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
QualType mergeFunctionParameterTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false)
mergeFunctionParameterTypes - merge two types which appear as function parameter types
QualType getsigjmp_bufType() const
Retrieve the C sigjmp_buf type.
Definition: ASTContext.h:1965
void addOverriddenMethod(const CXXMethodDecl *Method, const CXXMethodDecl *Overridden)
Note that the given C++ Method overrides the given Overridden method.
CanQualType Float128Ty
Definition: ASTContext.h:1098
CanQualType ObjCBuiltinClassTy
Definition: ASTContext.h:1117
unsigned NumImplicitDefaultConstructorsDeclared
The number of implicitly-declared default constructors for which declarations were built.
Definition: ASTContext.h:3188
OMPTraitInfo & getNewOMPTraitInfo()
Return a new OMPTraitInfo object owned by this context.
CanQualType UnsignedLongTy
Definition: ASTContext.h:1096
bool hasSameTemplateName(const TemplateName &X, const TemplateName &Y) const
Determine whether the given template names refer to the same template.
void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass, SmallVectorImpl< const ObjCIvarDecl * > &Ivars) const
DeepCollectObjCIvars - This routine first collects all declared, but not synthesized,...
llvm::APFixedPoint getFixedPointMin(QualType Ty) const
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
void addedLocalImportDecl(ImportDecl *Import)
Notify the AST context that a new import declaration has been parsed or implicitly created within thi...
CanQualType UnsignedLongAccumTy
Definition: ASTContext.h:1101
QualType AutoRRefDeductTy
Definition: ASTContext.h:1143
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
CanQualType ShortFractTy
Definition: ASTContext.h:1102
QualType getStringLiteralArrayType(QualType EltTy, unsigned Length) const
Return a type for a constant array for a string literal of the specified element type and length.
QualType getCorrespondingSaturatedType(QualType Ty) const
bool isSameEntity(const NamedDecl *X, const NamedDecl *Y) const
Determine whether the two declarations refer to the same entity.
TypeSourceInfo * getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc, const TemplateArgumentListInfo &Args, QualType Canon=QualType()) const
QualType getSubstTemplateTypeParmPackType(Decl *AssociatedDecl, unsigned Index, bool Final, const TemplateArgument &ArgPack)
Retrieve a.
CanQualType BoundMemberTy
Definition: ASTContext.h:1114
CanQualType SatUnsignedShortFractTy
Definition: ASTContext.h:1108
CanQualType CharTy
Definition: ASTContext.h:1088
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
TypedefDecl * getInt128Decl() const
Retrieve the declaration for the 128-bit signed integer type.
unsigned getOpenMPDefaultSimdAlign(QualType T) const
Get default simd alignment of the specified complete type in bits.
QualType getObjCSuperType() const
Returns the C struct type for objc_super.
QualType getBlockDescriptorType() const
Gets the struct used to keep track of the descriptor for pointer to blocks.
bool CommentsLoaded
True if comments are already loaded from ExternalASTSource.
Definition: ASTContext.h:803
BlockVarCopyInit getBlockVarCopyInit(const VarDecl *VD) const
Get the copy initialization expression of the VarDecl VD, or nullptr if none exists.
unsigned NumImplicitMoveConstructorsDeclared
The number of implicitly-declared move constructors for which declarations were built.
Definition: ASTContext.h:3202
unsigned NumImplicitCopyConstructorsDeclared
The number of implicitly-declared copy constructors for which declarations were built.
Definition: ASTContext.h:3195
CanQualType IntTy
Definition: ASTContext.h:1095
llvm::DenseSet< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
Definition: ASTContext.h:1156
CanQualType PseudoObjectTy
Definition: ASTContext.h:1116
QualType getWebAssemblyExternrefType() const
Return a WebAssembly externref type.
void setTraversalScope(const std::vector< Decl * > &)
Definition: ASTContext.cpp:936
CharUnits getTypeUnadjustedAlignInChars(QualType T) const
getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a type, in characters,...
QualType getAdjustedType(QualType Orig, QualType New) const
Return the uniqued reference to a type adjusted from the original type to a new type.
void PrintStats() const
Definition: ASTContext.cpp:950
unsigned getAlignOfGlobalVar(QualType T, const VarDecl *VD) const
Return the alignment in bits that should be given to a global variable with type T.
TypeInfoChars getTypeInfoDataSizeInChars(QualType T) const
MangleNumberingContext & getManglingNumberContext(const DeclContext *DC)
Retrieve the context for computing mangling numbers in the given DeclContext.
comments::FullComment * getLocalCommentForDeclUncached(const Decl *D) const
Return parsed documentation comment attached to a given declaration.
Definition: ASTContext.cpp:573
unsigned NumImplicitDestructors
The number of implicitly-declared destructors.
Definition: ASTContext.h:3219
CanQualType Float16Ty
Definition: ASTContext.h:1112
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2141
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
bool isAlignmentRequired(const Type *T) const
Determine if the alignment the type has was required using an alignment attribute.
TagDecl * MSGuidTagDecl
Definition: ASTContext.h:1150
bool areComparableObjCPointerTypes(QualType LHS, QualType RHS)
MangleContext * createDeviceMangleContext(const TargetInfo &T)
Creates a device mangle context to correctly mangle lambdas in a mixed architecture compile by settin...
CharUnits getExnObjectAlignment() const
Return the alignment (in bytes) of the thrown exception object.
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals)
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
CanQualType SignedCharTy
Definition: ASTContext.h:1095
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
ASTMutationListener * Listener
Definition: ASTContext.h:645
CanQualType ObjCBuiltinBoolTy
Definition: ASTContext.h:1118
TypeInfoChars getTypeInfoInChars(const Type *T) const
QualType getObjCObjectType(QualType Base, ObjCProtocolDecl *const *Protocols, unsigned NumProtocols) const
Legacy interface: cannot provide type arguments or __kindof.
TemplateParamObjectDecl * getTemplateParamObjectDecl(QualType T, const APValue &V) const
Return the template parameter object of the given type with the given value.
CanQualType OverloadTy
Definition: ASTContext.h:1114
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
CanQualType OCLClkEventTy
Definition: ASTContext.h:1122
void adjustExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, bool AsWritten=false)
Change the exception specification on a function once it is delay-parsed, instantiated,...
TypedefDecl * getUInt128Decl() const
Retrieve the declaration for the 128-bit unsigned integer type.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:692
ArrayRef< Module * > getModulesWithMergedDefinition(const NamedDecl *Def)
Get the additional modules in which the definition Def has been merged.
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals, SourceRange Brackets) const
Return a non-unique reference to the type for a dependently-sized array of the specified element type...
uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID, const ObjCImplementationDecl *ID, const ObjCIvarDecl *Ivar) const
Get the offset of an ObjCIvarDecl in bits.
CanQualType SatUnsignedShortAccumTy
Definition: ASTContext.h:1105
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false, bool IsConditionalOperator=false)
const RawComment * getRawCommentForAnyRedecl(const Decl *D, const Decl **OriginalDecl=nullptr) const
Return the documentation comment attached to a given declaration.
Definition: ASTContext.cpp:402
CharUnits getAlignOfGlobalVarInChars(QualType T, const VarDecl *VD) const
Return the alignment in characters that should be given to a global variable with type T.
const ObjCMethodDecl * getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const
Get the duplicate declaration of a ObjCMethod in the same interface, or null if none exists.
static bool isObjCNSObjectType(QualType Ty)
Return true if this is an NSObject object with its NSObject attribute set.
Definition: ASTContext.h:2295
GVALinkage GetGVALinkageForVariable(const VarDecl *VD) const
UsingShadowDecl * getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst)
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2048
Decl * getVaListTagDecl() const
Retrieve the C type declaration corresponding to the predefined __va_list_tag type used to help defin...
QualType getUnsignedWCharType() const
Return the type of "unsigned wchar_t".
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2592
QualType getCorrespondingUnsaturatedType(QualType Ty) const
comments::FullComment * getCommentForDecl(const Decl *D, const Preprocessor *PP) const
Return parsed documentation comment attached to a given declaration.
Definition: ASTContext.cpp:578
FunctionProtoType::ExceptionSpecInfo mergeExceptionSpecs(FunctionProtoType::ExceptionSpecInfo ESI1, FunctionProtoType::ExceptionSpecInfo ESI2, SmallVectorImpl< QualType > &ExceptionTypeStorage, bool AcceptDependent)
unsigned getTargetDefaultAlignForAttributeAligned() const
Return the default alignment for attribute((aligned)) on this target, to be used if no alignment valu...
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
bool isSameTemplateParameterList(const TemplateParameterList *X, const TemplateParameterList *Y) const
Determine whether two template parameter lists are similar enough that they may be used in declaratio...
QualType getWritePipeType(QualType T) const
Return a write_only pipe type for the specified type.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2315
CanQualType UnsignedInt128Ty
Definition: ASTContext.h:1097
CanQualType BuiltinFnTy
Definition: ASTContext.h:1115
ObjCInterfaceDecl * getObjCProtocolDecl() const
Retrieve the Objective-C class declaration corresponding to the predefined Protocol class.
unsigned NumImplicitDefaultConstructors
The number of implicitly-declared default constructors.
Definition: ASTContext.h:3184
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
unsigned NumImplicitMoveAssignmentOperatorsDeclared
The number of implicitly-declared move assignment operators for which declarations were built.
Definition: ASTContext.h:3216
void setManglingNumber(const NamedDecl *ND, unsigned Number)
llvm::DenseMap< const Decl *, const RawComment * > DeclRawComments
Mapping from declaration to directly attached comment.
Definition: ASTContext.h:809
CanQualType OCLSamplerTy
Definition: ASTContext.h:1122
TypedefDecl * getBuiltinVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_va_list type.
CanQualType VoidTy
Definition: ASTContext.h:1086
CanQualType UnsignedCharTy
Definition: ASTContext.h:1096
CanQualType UnsignedShortFractTy
Definition: ASTContext.h:1103
BuiltinTemplateDecl * buildBuiltinTemplateDecl(BuiltinTemplateKind BTK, const IdentifierInfo *II) const
void * Allocate(size_t Size, unsigned Align=8) const
Definition: ASTContext.h:713
bool canBuiltinBeRedeclared(const FunctionDecl *) const
Return whether a declaration to a builtin is allowed to be overloaded/redeclared.
CanQualType UnsignedIntTy
Definition: ASTContext.h:1096
TemplateName getDependentTemplateName(NestedNameSpecifier *NNS, const IdentifierInfo *Name) const
Retrieve the template name that represents a dependent template name such as MetaFun::template apply.
unsigned NumImplicitMoveConstructors
The number of implicitly-declared move constructors.
Definition: ASTContext.h:3198
QualType getObjCTypeParamType(const ObjCTypeParamDecl *Decl, ArrayRef< ObjCProtocolDecl * > protocols) const
QualType getVolatileType(QualType T) const
Return the uniqued reference to the type for a volatile qualified type.
Definition: ASTContext.h:1281
void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, QualType T, std::string &S, bool Extended) const
getObjCEncodingForMethodParameter - Return the encoded type for a single method parameter or return t...
void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD)
unsigned overridden_methods_size(const CXXMethodDecl *Method) const
std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const
Return the encoded type for this block declaration.
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
QualType getExceptionObjectType(QualType T) const
CanQualType UnknownAnyTy
Definition: ASTContext.h:1114
void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
Note that the static data member Inst is an instantiation of the static data member template Tmpl of ...
DeclaratorDecl * getDeclaratorForUnnamedTagDecl(const TagDecl *TD)
bool ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *Decl)
ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's protocol list adopt all protocols in Q...
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1097
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
QualType getCommonSugaredType(QualType X, QualType Y, bool Unqualified=false)
CanQualType OCLReserveIDTy
Definition: ASTContext.h:1123
bool isSameTemplateParameter(const NamedDecl *X, const NamedDecl *Y) const
Determine whether two template parameters are similar enough that they may be used in declarations of...
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
overridden_cxx_method_iterator overridden_methods_begin(const CXXMethodDecl *Method) const
CanQualType UnsignedShortTy
Definition: ASTContext.h:1096
unsigned getTypeAlignIfKnown(QualType T, bool NeedsPreferredAlignment=false) const
Return the alignment of a type, in bits, or 0 if the type is incomplete and we cannot determine the a...
bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1553
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
bool canAssignObjCInterfacesInBlockPointer(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT, bool BlockReturnType)
canAssignObjCInterfacesInBlockPointer - This routine is specifically written for providing type-safet...
CanQualType SatUnsignedLongFractTy
Definition: ASTContext.h:1109
const CXXConstructorDecl * getCopyConstructorForExceptionObject(CXXRecordDecl *RD)
QualType getDependentAddressSpaceType(QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttrLoc) const
QualType getPackIndexingType(QualType Pattern, Expr *IndexExpr, bool FullySubstituted=false, ArrayRef< QualType > Expansions={}, int Index=-1) const
RawComment * getRawCommentForDeclNoCache(const Decl *D) const
Return the documentation comment attached to a given declaration, without looking into cache.
Definition: ASTContext.cpp:293
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
const VariableArrayType * getAsVariableArrayType(QualType T) const
Definition: ASTContext.h:2745
QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType, UnaryTransformType::UTTKind UKind) const
Unary type transforms.
void setExternalSource(IntrusiveRefCntPtr< ExternalASTSource > Source)
Attach an external AST source to the AST context.
Definition: ASTContext.cpp:946
const ObjCInterfaceDecl * getObjContainingInterface(const NamedDecl *ND) const
Returns the Objective-C interface that ND belongs to if it is an Objective-C method/property/ivar etc...
CanQualType ShortTy
Definition: ASTContext.h:1095
StringLiteral * getPredefinedStringLiteralFromCache(StringRef Key) const
Return a string representing the human readable name for the specified function declaration or file n...
bool UnwrapSimilarTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true)
Attempt to unwrap two types that may be similar (C++ [conv.qual]).
llvm::APFixedPoint getFixedPointMax(QualType Ty) const
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type.
bool areCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an SVE builtin and a VectorType that is a fixed-length representat...
bool hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
CanQualType FractTy
Definition: ASTContext.h:1102
Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const
Recurses in pointer/array types until it finds an Objective-C retainable type and returns its ownersh...
void addCopyConstructorForExceptionObject(CXXRecordDecl *RD, CXXConstructorDecl *CD)
DiagnosticsEngine & getDiagnostics() const
QualType getAdjustedParameterType(QualType T) const
Perform adjustment on the parameter type of a function.
void ResetObjCLayout(const ObjCContainerDecl *CD)
CanQualType LongAccumTy
Definition: ASTContext.h:1100
interp::Context & getInterpContext()
Returns the clang bytecode interpreter context.
Definition: ASTContext.cpp:844
CanQualType Char32Ty
Definition: ASTContext.h:1094
UnnamedGlobalConstantDecl * getUnnamedGlobalConstantDecl(QualType Ty, const APValue &Value) const
Return a declaration for a uniquified anonymous global constant corresponding to a given APValue.
CanQualType SatFractTy
Definition: ASTContext.h:1107
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec)
Return true if the given vector types are of the same unqualified type or if they are equivalent to t...
void getOverriddenMethods(const NamedDecl *Method, SmallVectorImpl< const NamedDecl * > &Overridden) const
Return C++ or ObjC overridden methods for the given Method.
DeclarationNameInfo getNameForTemplate(TemplateName Name, SourceLocation NameLoc) const
CanQualType SatLongFractTy
Definition: ASTContext.h:1107
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:752
void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl)
CanQualType OCLQueueTy
Definition: ASTContext.h:1123
CanQualType LongFractTy
Definition: ASTContext.h:1102
CanQualType SatShortAccumTy
Definition: ASTContext.h:1104
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
CanQualType BFloat16Ty
Definition: ASTContext.h:1111
unsigned NumImplicitCopyConstructors
The number of implicitly-declared copy constructors.
Definition: ASTContext.h:3191
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType IncompleteMatrixIdxTy
Definition: ASTContext.h:1124
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
CanQualType getNSIntegerType() const
QualType getCorrespondingUnsignedType(QualType T) const
void setBlockVarCopyInit(const VarDecl *VD, Expr *CopyExpr, bool CanThrow)
Set the copy initialization expression of a block var decl.
TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, UnresolvedSetIterator End) const
Retrieve the template name that corresponds to a non-empty lookup.
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
TemplateName getSubstTemplateTemplateParmPack(const TemplateArgument &ArgPack, Decl *AssociatedDecl, unsigned Index, bool Final) const
TargetCXXABI::Kind getCXXABIKind() const
Return the C++ ABI kind that should be used.
Definition: ASTContext.cpp:818
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
Definition: ASTContext.h:1182
uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const
Return number of constant array elements.
BuiltinTemplateDecl * getTypePackElementDecl() const
CanQualType SatUnsignedLongAccumTy
Definition: ASTContext.h:1106
QualType getUnconstrainedType(QualType T) const
Remove any type constraints from a template parameter type, for equivalence comparison of template pa...
CanQualType LongLongTy
Definition: ASTContext.h:1095
QualType getTypeOfType(QualType QT, TypeOfKind Kind) const
getTypeOfType - Unlike many "get<Type>" functions, we don't unique TypeOfType nodes.
QualType getCorrespondingSignedType(QualType T) const
QualType mergeObjCGCQualifiers(QualType, QualType)
mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 'RHS' attributes and ret...
llvm::DenseMap< const Decl *, const Decl * > CommentlessRedeclChains
Keeps track of redeclaration chains that don't have any comment attached.
Definition: ASTContext.h:825
uint64_t getArrayInitLoopExprElementCount(const ArrayInitLoopExpr *AILE) const
Return number of elements initialized in an ArrayInitLoopExpr.
void deduplicateMergedDefinitonsFor(NamedDecl *ND)
Clean up the merged definition list.
unsigned getTargetAddressSpace(LangAS AS) const
QualType getWideCharType() const
Return the type of wide characters.
Definition: ASTContext.h:1778
QualType getIntPtrType() const
Return a type compatible with "intptr_t" (C99 7.18.1.4), as defined by the target.
void mergeDefinitionIntoModule(NamedDecl *ND, Module *M, bool NotifyListeners=true)
Note that the definition ND has been merged into module M, and should be visible whenever M is visibl...
void addTranslationUnitDecl()
Definition: ASTContext.h:1071
CanQualType WCharTy
Definition: ASTContext.h:1089
void getObjCEncodingForPropertyType(QualType T, std::string &S) const
Emit the Objective-C property type encoding for the given type T into S.
unsigned NumImplicitCopyAssignmentOperators
The number of implicitly-declared copy assignment operators.
Definition: ASTContext.h:3205
void CollectInheritedProtocols(const Decl *CDecl, llvm::SmallPtrSet< ObjCProtocolDecl *, 8 > &Protocols)
CollectInheritedProtocols - Collect all protocols in current class and those inherited by it.
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
llvm::DenseMap< const Decl *, const Decl * > RedeclChainComments
Mapping from canonical declaration to the first redeclaration in chain that has a comment attached.
Definition: ASTContext.h:816
CanQualType getSignedSizeType() const
Return the unique signed counterpart of the integer type corresponding to size_t.
void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType)
Change the result type of a function type once it is deduced.
QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const
Return the uniqued reference to the type for an Objective-C gc-qualified type.
QualType getDecltypeType(Expr *e, QualType UnderlyingType) const
C++11 decltype.
NestedNameSpecifier * getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const
Retrieves the "canonical" nested name specifier for a given nested name specifier.
QualType getTypedefType(const TypedefNameDecl *Decl, QualType Underlying=QualType()) const
Return the unique reference to the type for the specified typedef-name decl.
InlineVariableDefinitionKind getInlineVariableDefinitionKind(const VarDecl *VD) const
Determine whether a definition of this inline variable should be treated as a weak or strong definiti...
CanQualType getUIntMaxType() const
Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in <stdint.h>.
QualType getSubstTemplateTypeParmType(QualType Replacement, Decl *AssociatedDecl, unsigned Index, std::optional< unsigned > PackIndex) const
Retrieve a substitution-result type.
CharUnits getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const
Loading virtual member pointers using the virtual inheritance model always results in an adjustment u...
LangAS getLangASForBuiltinAddressSpace(unsigned AS) const
bool hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U)
Determine whether two function types are the same, ignoring pointer sizes in the return type and para...
unsigned char getFixedPointScale(QualType Ty) const
QualType getIncompleteArrayType(QualType EltTy, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a unique reference to the type for an incomplete array of the specified element type.
QualType getDependentSizedExtVectorType(QualType VectorType, Expr *SizeExpr, SourceLocation AttrLoc) const
QualType DecodeTypeStr(const char *&Str, const ASTContext &Context, ASTContext::GetBuiltinTypeError &Error, bool &RequireICE, bool AllowTypeModifiers) const
TemplateName getAssumedTemplateName(DeclarationName Name) const
Retrieve a template name representing an unqualified-id that has been assumed to name a template for ...
@ GE_None
No error.
Definition: ASTContext.h:2217
@ GE_Missing_stdio
Missing a type from <stdio.h>
Definition: ASTContext.h:2223
@ GE_Missing_type
Missing a type.
Definition: ASTContext.h:2220
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
Definition: ASTContext.h:2229
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
Definition: ASTContext.h:2226
QualType adjustStringLiteralBaseType(QualType StrLTy) const
QualType getTypeOfExprType(Expr *E, TypeOfKind Kind) const
C23 feature and GCC extension.
CanQualType Char8Ty
Definition: ASTContext.h:1092
QualType getSignedWCharType() const
Return the type of "signed wchar_t".
bool hasCvrSimilarType(QualType T1, QualType T2)
Determine if two types are similar, ignoring only CVR qualifiers.
ObjCImplementationDecl * getObjCImplementation(ObjCInterfaceDecl *D)
Get the implementation of the ObjCInterfaceDecl D, or nullptr if none exists.
CanQualType HalfTy
Definition: ASTContext.h:1110
CanQualType UnsignedAccumTy
Definition: ASTContext.h:1101
void setObjCMethodRedeclaration(const ObjCMethodDecl *MD, const ObjCMethodDecl *Redecl)
void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND)
QualType getConstantMatrixType(QualType ElementType, unsigned NumRows, unsigned NumColumns) const
Return the unique reference to the matrix type of the specified element type and size.
QualType getVariableArrayDecayedType(QualType Ty) const
Returns a vla type where known sizes are replaced with [*].
void setCFConstantStringType(QualType T)
unsigned getParameterIndex(const ParmVarDecl *D) const
Used by ParmVarDecl to retrieve on the side the index of the parameter when it exceeds the size of th...
CanQualType OCLEventTy
Definition: ASTContext.h:1122
void AddDeallocation(void(*Callback)(void *), void *Data) const
Add a deallocation callback that will be invoked when the ASTContext is destroyed.
Definition: ASTContext.cpp:941
AttrVec & getDeclAttrs(const Decl *D)
Retrieve the attributes for the given declaration.
CXXMethodVector::const_iterator overridden_cxx_method_iterator
Definition: ASTContext.h:986
RawComment * getRawCommentForDeclNoCacheImpl(const Decl *D, const SourceLocation RepresentativeLocForDecl, const std::map< unsigned, RawComment * > &CommentsInFile) const
Definition: ASTContext.cpp:215
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
Definition: ASTContext.h:2346
QualType mergeTransparentUnionType(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false)
mergeTransparentUnionType - if T is a transparent union type and a member of T is compatible with Sub...
QualType isPromotableBitField(Expr *E) const
Whether this is a promotable bitfield reference according to C99 6.3.1.1p2, bullet 2 (and GCC extensi...
bool isSentinelNullExpr(const Expr *E)
CanQualType getNSUIntegerType() const
CanQualType OMPArraySectionTy
Definition: ASTContext.h:1125
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2319
QualType getBitIntType(bool Unsigned, unsigned NumBits) const
Return a bit-precise integer type with the specified signedness and bit count.
unsigned NumImplicitMoveAssignmentOperators
The number of implicitly-declared move assignment operators.
Definition: ASTContext.h:3212
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
virtual void RedefinedHiddenDefinition(const NamedDecl *D, Module *M)
A definition has been made visible by being redefined locally.
virtual void DeducedReturnType(const FunctionDecl *FD, QualType ReturnType)
A function's return type has been deduced.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
CharUnits getAlignment() const
getAlignment - Get the record alignment in characters.
Definition: RecordLayout.h:182
const CXXRecordDecl * getBaseSharingVBPtr() const
Definition: RecordLayout.h:329
CharUnits getSize() const
getSize - Get the record size in characters.
Definition: RecordLayout.h:193
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:200
CharUnits getDataSize() const
getDataSize() - Get the record data size, which is the record size without tail padding,...
Definition: RecordLayout.h:206
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:249
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:259
CharUnits getNonVirtualSize() const
getNonVirtualSize - Get the non-virtual size (in chars) of an object, which is the size of the object...
Definition: RecordLayout.h:210
CharUnits getUnadjustedAlignment() const
getUnadjustedAlignment - Get the record alignment in characters, before alignment adjustement.
Definition: RecordLayout.h:190
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons.
Definition: Type.h:2927
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:2946
Represents a loop initializing the elements of an array.
Definition: Expr.h:5505
llvm::APInt getArraySize() const
Definition: Expr.h:5527
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition: Expr.h:5525
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3147
ArraySizeModifier getSizeModifier() const
Definition: Type.h:3161
Qualifiers getIndexTypeQualifiers() const
Definition: Type.h:3165
QualType getElementType() const
Definition: Type.h:3159
unsigned getIndexTypeCVRQualifiers() const
Definition: Type.h:3169
A structure for storing the information associated with a name that has been assumed to be a template...
DeclarationName getDeclName() const
Get the name of the template.
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition: Expr.h:6431
Expr * getPtr() const
Definition: Expr.h:6463
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:6732
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6737
Attr - This represents one attribute.
Definition: Attr.h:42
An attributed type is a type to which a type attribute has been applied.
Definition: Type.h:5147
static Kind getNullabilityAttrKind(NullabilityKind kind)
Retrieve the attribute kind corresponding to the given nullability kind.
Definition: Type.h:5202
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5230
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:5524
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.cpp:4911
bool isConstrained() const
Definition: Type.h:5543
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5265
A fixed int type of a specified bitwidth.
Definition: Type.h:6785
void Profile(llvm::FoldingSetNodeID &ID) const
Definition: Type.h:6802
unsigned getNumBits() const
Definition: Type.h:6797
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4459
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6167
Pointer to a block type.
Definition: Type.h:2978
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:2995
Represents the builtin template declaration which is used to implement __make_integer_seq and other b...
static BuiltinTemplateDecl * Create(const ASTContext &C, DeclContext *DC, DeclarationName Name, BuiltinTemplateKind BTK)
This class is used for builtin types like 'int'.
Definition: Type.h:2740
Kind getKind() const
Definition: Type.h:2782
StringRef getName(const PrintingPolicy &Policy) const
Definition: Type.cpp:3220
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition: Builtins.h:85
const char * getTypeString(unsigned ID) const
Get the type descriptor string for the specified builtin.
Definition: Builtins.h:106
bool hasCustomTypechecking(unsigned ID) const
Determines whether this builtin has custom typechecking.
Definition: Builtins.h:196
bool canBeRedeclared(unsigned ID) const
Returns true if this is a builtin that can be redeclared.
Definition: Builtins.cpp:236
bool isNoReturn(unsigned ID) const
Return true if we know this builtin never returns.
Definition: Builtins.h:132
bool isNoThrow(unsigned ID) const
Return true if we know this builtin never throws an exception.
Definition: Builtins.h:127
Implements C++ ABI-specific semantic analysis functions.
Definition: CXXABI.h:29
virtual ~CXXABI()
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2528
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2053
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2149
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr, bool DelayTypeCreation=false)
Definition: DeclCXX.cpp:131
bool isDynamicClass() const
Definition: DeclCXX.h:584
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition: DeclCXX.h:1189
SplitQualType split() const
static CanQual< Type > CreateUnsafe(QualType Other)
Builds a canonical type from a QualType.
QualType withConst() const
Retrieves a version of this type with const applied.
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
bool isNull() const
Definition: CanonicalType.h:97
Qualifiers getQualifiers() const
Retrieve all qualifiers.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:83
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
bool isPositive() const
isPositive - Test whether the quantity is greater than zero.
Definition: CharUnits.h:128
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:122
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition: CharUnits.h:53
Declaration of a class template.
llvm::PointerUnion< ClassTemplateDecl *, ClassTemplatePartialSpecializationDecl * > getSpecializedTemplateOrPartial() const
Retrieve the class template or class template partial specialization which was specialized by this.
Complex values, per C99 6.2.5p11.
Definition: Type.h:2845
QualType getElementType() const
Definition: Type.h:2855
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:2860
Declaration of a C++20 concept.
ConceptDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
bool hasExplicitTemplateArgs() const
Whether or not template arguments were explicitly specified in the concept reference (they might not ...
Definition: ASTConcept.h:213
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Definition: ASTConcept.h:207
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3186
const llvm::APInt & getSize() const
Definition: Type.h:3207
const Expr * getSizeExpr() const
Definition: Type.h:3208
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.h:3228
Represents a concrete matrix type with constant number of rows and columns.
Definition: Type.h:3710
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition: Type.h:3731
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3748
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition: Type.h:3728
static constexpr bool isDimensionValid(size_t NumElements)
Returns true if NumElements is a valid matrix dimension.
Definition: Type.h:3739
Represents a pointer type decayed from an array or function type.
Definition: Type.h:2961
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1446
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2076
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1265
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:2092
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1785
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1921
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1699
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1260
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:85
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition: DeclBase.h:1061
const DeclContext * getParentFunctionOrMethod(bool LexicalParent=false) const
If this decl is defined inside a function/method/block it returns the corresponding DeclContext,...
Definition: DeclBase.cpp:295
T * getAttr() const
Definition: DeclBase.h:578
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:501
void addAttr(Attr *A)
Definition: DeclBase.cpp:975
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:598
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition: DeclBase.cpp:515
static Decl * castFromDeclContext(const DeclContext *)
Definition: DeclBase.cpp:1003
bool isCanonicalDecl() const
Whether this particular Decl is a canonical one.
Definition: DeclBase.h:984
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:227
ObjCDeclQualifier
ObjCDeclQualifier - 'Qualifiers' written next to the return and parameter types in method declaration...
Definition: DeclBase.h:197
@ OBJC_TQ_Byref
Definition: DeclBase.h:203
@ OBJC_TQ_Oneway
Definition: DeclBase.h:204
@ OBJC_TQ_Bycopy
Definition: DeclBase.h:202
@ OBJC_TQ_None
Definition: DeclBase.h:198
@ OBJC_TQ_Inout
Definition: DeclBase.h:200
bool isInvalidDecl() const
Definition: DeclBase.h:593
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:564
SourceLocation getLocation() const
Definition: DeclBase.h:444
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition: DeclBase.cpp:210
void setImplicit(bool I=true)
Definition: DeclBase.h:599
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: DeclBase.h:1049
DeclContext * getDeclContext()
Definition: DeclBase.h:453
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:436
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:336
bool hasAttr() const
Definition: DeclBase.h:582
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:978
Kind getKind() const
Definition: DeclBase.h:447
DeclarationNameLoc - Additional source/type location info for a declaration name.
static DeclarationNameLoc makeCXXOperatorNameLoc(SourceLocation BeginLoc, SourceLocation EndLoc)
Construct location information for a non-literal C++ operator.
DeclarationName getIdentifier(const IdentifierInfo *ID)
Create a declaration name that is a simple identifier.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
The name of a declaration.
static int compare(DeclarationName LHS, DeclarationName RHS)
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:770
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:799
Represents the type decltype(expr) (C++11).
Definition: Type.h:4901
Represents a C++17 deduced template specialization type.
Definition: Type.h:5572
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5594
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:5490
Represents an extended address space qualifier where the input address space value is dependent.
Definition: Type.h:3402
Expr * getAddrSpaceExpr() const
Definition: Type.h:3413
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:3424
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:6830
Internal representation of canonical, dependent decltype(expr) types.
Definition: Type.h:4929
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:4933
Represents a qualified type name for which the type name is dependent.
Definition: Type.h:5995
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6027
Represents an array type in C++ whose size is a value-dependent expression.
Definition: Type.h:3344
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:3381
Expr * getSizeExpr() const
Definition: Type.h:3364
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:3442
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:3467
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition: Type.h:3769
Expr * getRowExpr() const
Definition: Type.h:3781
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:3789
Represents a dependent template name that cannot be resolved prior to template instantiation.
Definition: TemplateName.h:488
OverloadedOperatorKind getOperator() const
Return the overloaded operator to which this template name refers.
Definition: TemplateName.h:560
bool isIdentifier() const
Determine whether this template name refers to an identifier.
Definition: TemplateName.h:547
const IdentifierInfo * getIdentifier() const
Returns the identifier to which this template name refers.
Definition: TemplateName.h:550
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TemplateName.h:566
Represents a template specialization type whose template cannot be resolved, e.g.
Definition: Type.h:6047
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:6074
Internal representation of canonical, dependent typeof(expr) types.
Definition: Type.h:4850
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:4854
Internal representation of canonical, dependent __underlying_type(type) types.
Definition: Type.h:5052
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5057
Represents a vector type where either the type or size is dependent.
Definition: Type.h:3564
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:3589
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:192
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1547
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition: Diagnostic.h:873
Represents a type that was referred to using an elaborated type keyword, e.g., struct S,...
Definition: Type.h:5914
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5967
Represents an enum.
Definition: Decl.h:3832
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4037
bool isComplete() const
Returns true if this can be considered a complete type.
Definition: Decl.h:4051
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:3992
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:4905
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5118
EnumDecl * getDecl() const
Definition: Type.h:5125
This represents one expression.
Definition: Expr.h:110
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:3050
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:437
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition: Expr.cpp:4065
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:821
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition: Expr.h:221
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3025
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition: Expr.cpp:3904
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
QualType getType() const
Definition: Expr.h:142
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition: Expr.h:427
We can encode up to four bits in the low bits of a type pointer, but there are many more type qualifi...
Definition: Type.h:1490
void Profile(llvm::FoldingSetNodeID &ID) const
Definition: Type.h:1537
ExtVectorType - Extended vector type.
Definition: Type.h:3604
Declaration context for names declared as extern "C" in C++.
Definition: Decl.h:222
static ExternCContextDecl * Create(const ASTContext &C, TranslationUnitDecl *TU)
Definition: Decl.cpp:5291
Abstract interface for external sources of AST nodes.
virtual ExtKind hasExternalDefinitions(const Decl *D)
virtual void ReadComments()
Loads comment ranges.
virtual void CompleteRedeclChain(const Decl *D)
Gives the external AST source an opportunity to complete the redeclaration chain for a declaration.
virtual void PrintStats()
Print any statistics that have been gathered regarding the external AST source.
Represents a member of a struct/union/class.
Definition: Decl.h:3025
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3116
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.cpp:4611
unsigned getBitWidthValue(const ASTContext &Ctx) const
Computes the bit width of this field, if this is a bit field.
Definition: Decl.cpp:4559
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3238
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
Definition: Decl.cpp:4512
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Represents a function declaration or definition.
Definition: Decl.h:1959
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition: Decl.h:2574
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3597
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2798
bool isMSExternInline() const
The combination of the extern and inline keywords under MSVC forces the function to be required.
Definition: Decl.cpp:3722
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:4233
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition: Decl.h:2347
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:3979
bool isInlineDefinitionExternallyVisible() const
For an inline function definition in C, or for a gnu_inline function in C++, determine whether the de...
Definition: Decl.cpp:3892
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition: Type.h:4154
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4170
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4199
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:4644
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:4458
unsigned getNumParams() const
Definition: Type.h:4432
QualType getParamType(unsigned i) const
Definition: Type.h:4434
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.cpp:3706
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: Type.h:4464
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:4555
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4443
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:4439
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
Definition: Type.h:4620
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition: Type.h:4616
Declaration of a template function.
Definition: DeclTemplate.h:958
A class which abstracts out some details necessary for making a call.
Definition: Type.h:3910
CallingConv getCC() const
Definition: Type.h:3972
bool getNoCfCheck() const
Definition: Type.h:3962
unsigned getRegParm() const
Definition: Type.h:3965
bool getNoCallerSavedRegs() const
Definition: Type.h:3961
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:3984
bool getHasRegParm() const
Definition: Type.h:3963
bool getNoReturn() const
Definition: Type.h:3958
bool getProducesResult() const
Definition: Type.h:3959
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition: Type.h:3825
ExtParameterInfo withIsNoEscape(bool NoEscape) const
Definition: Type.h:3865
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3799
ExtInfo getExtInfo() const
Definition: Type.h:4128
QualType getReturnType() const
Definition: Type.h:4116
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:56
unsigned getMultiVersionIndex() const
Definition: GlobalDecl.h:122
const Decl * getDecl() const
Definition: GlobalDecl.h:103
One of these records is kept for each identifier that is lexed.
Implements an efficient mapping from strings to IdentifierInfo nodes.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
Describes a module import declaration, which makes the contents of the named module visible in the cu...
Definition: Decl.h:4764
Represents a C array with an unspecified size.
Definition: Type.h:3246
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3263
The injected class name of a C++ class template or class template partial specialization.
Definition: Type.h:5764
static ItaniumMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
@ Relative
Components in the vtable are relative offsets between the vtable and the other structs/functions.
@ Pointer
Components in the vtable are pointers to other structs/functions.
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3053
@ Swift
Interoperability with the latest known version of the Swift runtime.
@ Swift4_2
Interoperability with the Swift 4.2 runtime.
@ Swift4_1
Interoperability with the Swift 4.1 runtime.
@ Integer
Permit vector bitcasts between integer vectors with different numbers of elements but the same total ...
@ All
Permit vector bitcasts between all vectors with the same total bit-width.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:418
std::optional< TargetCXXABI::Kind > CXXABI
C++ ABI to compile with, if specified by the frontend through -fc++-abi=.
Definition: LangOptions.h:506
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:453
CoreFoundationABI CFRuntime
Definition: LangOptions.h:455
CommentOptions CommentOpts
Options for parsing comments.
Definition: LangOptions.h:482
std::string CUID
The user provided compilation unit ID, if non-empty.
Definition: LangOptions.h:502
A global _GUID constant.
Definition: DeclCXX.h:4282
static void Profile(llvm::FoldingSetNodeID &ID, Parts P)
Definition: DeclCXX.h:4319
Sugar type that represents a type that was qualified by a qualifier written as a macro invocation.
Definition: Type.h:4785
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
Definition: Mangle.h:45
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition: Type.h:3688
static bool isValidElementType(QualType T)
Valid elements types are the following:
Definition: Type.h:3695
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3089
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3125
QualType getPointeeType() const
Definition: Type.h:3105
const Type * getClass() const
Definition: Type.h:3119
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:616
static MicrosoftMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
Describes a module or submodule.
Definition: Module.h:105
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition: Module.h:185
This represents a decl that may have a name.
Definition: Decl.h:249
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:462
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
std::string getNameAsString() const
Get a human-readable name for the declaration, even if it is one of the special kinds of names (C++ c...
Definition: Decl.h:292
bool isExternallyVisible() const
Definition: Decl.h:408
NamespaceDecl * getNamespace()
Retrieve the namespace declaration aliased by this directive.
Definition: DeclCXX.h:3185
Represent a C++ namespace.
Definition: Decl.h:547
NamespaceDecl * getOriginalNamespace()
Get the original (first) namespace declaration.
Definition: DeclCXX.cpp:2993
static NamespaceDecl * Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl, bool Nested)
Definition: DeclCXX.cpp:2980
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
NamespaceAliasDecl * getAsNamespaceAlias() const
Retrieve the namespace alias stored in this nested name specifier.
IdentifierInfo * getAsIdentifier() const
Retrieve the identifier stored in this nested name specifier.
NestedNameSpecifier * getPrefix() const
Return the prefix of this nested name specifier.
@ NamespaceAlias
A namespace alias, stored as a NamespaceAliasDecl*.
@ TypeSpec
A type, stored as a Type*.
@ TypeSpecWithTemplate
A type that was preceded by the 'template' keyword, stored as a Type*.
@ Super
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Identifier
An identifier, stored as an IdentifierInfo*.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace, stored as a NamespaceDecl*.
NamespaceDecl * getAsNamespace() const
Retrieve the namespace stored in this nested name specifier.
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
Helper data structure representing the traits in a match clause of an declare variant or metadirectiv...
ObjCCategoryDecl - Represents a category declaration.
Definition: DeclObjC.h:2323
ObjCCategoryImplDecl - An object of this class encapsulates a category @implementation declaration.
Definition: DeclObjC.h:2542
ObjCContainerDecl - Represents a container for method declarations.
Definition: DeclObjC.h:944
const ObjCInterfaceDecl * getClassInterface() const
Definition: DeclObjC.h:2483
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2595
Represents an ObjC class declaration.
Definition: DeclObjC.h:1150
ObjCTypeParamList * getTypeParamList() const
Retrieve the type parameters of this class.
Definition: DeclObjC.cpp:321
static ObjCInterfaceDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation atLoc, IdentifierInfo *Id, ObjCTypeParamList *typeParamList, ObjCInterfaceDecl *PrevDecl, SourceLocation ClassLoc=SourceLocation(), bool isInternal=false)
Definition: DeclObjC.cpp:1542
bool hasDefinition() const
Determine whether this class has been defined.
Definition: DeclObjC.h:1524
ivar_range ivars() const
Definition: DeclObjC.h:1447
bool ClassImplementsProtocol(ObjCProtocolDecl *lProto, bool lookupCategory, bool RHSIsQualifiedID=false)
ClassImplementsProtocol - Checks that 'lProto' protocol has been implemented in IDecl class,...
Definition: DeclObjC.cpp:1794
StringRef getObjCRuntimeNameAsString() const
Produce a name to be used for class's metadata.
Definition: DeclObjC.cpp:1619
ObjCImplementationDecl * getImplementation() const
Definition: DeclObjC.cpp:1635
ObjCInterfaceDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this Objective-C class.
Definition: DeclObjC.h:1910
ObjCInterfaceDecl * getSuperClass() const
Definition: DeclObjC.cpp:351
bool isSuperClassOf(const ObjCInterfaceDecl *I) const
isSuperClassOf - Return true if this class is the specified class or is a super class of the specifie...
Definition: DeclObjC.h:1805
known_extensions_range known_extensions() const
Definition: DeclObjC.h:1757
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:6495
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
Definition: Type.cpp:849
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1947
ObjCIvarDecl * getNextIvar()
Definition: DeclObjC.h:1983
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
ObjCDeclQualifier getObjCDeclQualifier() const
Definition: DeclObjC.h:246
unsigned param_size() const
Definition: DeclObjC.h:347
param_const_iterator param_end() const
Definition: DeclObjC.h:358
param_const_iterator param_begin() const
Definition: DeclObjC.h:354
bool isVariadic() const
Definition: DeclObjC.h:431
const ParmVarDecl *const * param_const_iterator
Definition: DeclObjC.h:349
Selector getSelector() const
Definition: DeclObjC.h:327
bool isInstanceMethod() const
Definition: DeclObjC.h:426
QualType getReturnType() const
Definition: DeclObjC.h:329
Represents a pointer to an Objective C object.
Definition: Type.h:6551
bool isObjCQualifiedClassType() const
True if this is equivalent to 'Class.
Definition: Type.h:6632
const ObjCObjectPointerType * stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const
Strip off the Objective-C "kindof" type and (with it) any protocol qualifiers.
Definition: Type.cpp:856
bool isObjCQualifiedIdType() const
True if this is equivalent to 'id.
Definition: Type.h:6626
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6708
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:6588
bool qual_empty() const
Definition: Type.h:6680
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition: Type.h:6609
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:6563
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition: Type.h:6603
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition: Type.cpp:1736
qual_range quals() const
Definition: Type.h:6670
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition: Type.h:6615
A class providing a concrete implementation of ObjCObjectType, so as to not increase the footprint of...
Definition: Type.h:6448
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.cpp:4210
Represents a class type in Objective C.
Definition: Type.h:6297
bool isKindOfTypeAsWritten() const
Whether this is a "__kindof" type as written.
Definition: Type.h:6412
bool isSpecialized() const
Determine whether this object type is "specialized", meaning that it has type arguments.
Definition: Type.cpp:778
ArrayRef< QualType > getTypeArgsAsWritten() const
Retrieve the type arguments of this object type as they were written.
Definition: Type.h:6407
bool isObjCQualifiedClass() const
Definition: Type.h:6379
QualType getBaseType() const
Gets the base type of this object type.
Definition: Type.h:6359
bool isObjCClass() const
Definition: Type.h:6365
bool isKindOfType() const
Whether this ia a "__kindof" type (semantically).
Definition: Type.cpp:814
bool isObjCQualifiedId() const
Definition: Type.h:6378
ArrayRef< QualType > getTypeArgs() const
Retrieve the type arguments of this object type (semantically).
Definition: Type.cpp:796
bool isObjCUnqualifiedId() const
Definition: Type.h:6369
ObjCInterfaceDecl * getInterface() const
Gets the interface declaration for this object type, if the base type really is an interface.
Definition: Type.h:6530
QualType getSuperClassType() const
Retrieve the type of the superclass of this object type.
Definition: Type.h:6423
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:729
bool isReadOnly() const
isReadOnly - Return true iff the property has a setter.
Definition: DeclObjC.h:834
static ObjCPropertyDecl * findPropertyDecl(const DeclContext *DC, const IdentifierInfo *propertyID, ObjCPropertyQueryKind queryKind)
Lookup a property by name in the specified DeclContext.
Definition: DeclObjC.cpp:178
bool isOptional() const
Definition: DeclObjC.h:912
SetterKind getSetterKind() const
getSetterKind - Return the method used for doing assignment in the property setter.
Definition: DeclObjC.h:869
Selector getSetterName() const
Definition: DeclObjC.h:889
QualType getType() const
Definition: DeclObjC.h:800
Selector getGetterName() const
Definition: DeclObjC.h:881
ObjCPropertyAttribute::Kind getPropertyAttributes() const
Definition: DeclObjC.h:811
ObjCPropertyImplDecl - Represents implementation declaration of a property in a class or category imp...
Definition: DeclObjC.h:2802
ObjCIvarDecl * getPropertyIvarDecl() const
Definition: DeclObjC.h:2875
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:2079
protocol_range protocols() const
Definition: DeclObjC.h:2155
unsigned getNumProtocols() const
Return the number of qualifying protocols in this type, or 0 if there are none.
Definition: Type.h:6203
qual_iterator qual_end() const
Definition: Type.h:6197
qual_iterator qual_begin() const
Definition: Type.h:6196
qual_range quals() const
Definition: Type.h:6195
bool isGNUFamily() const
Is this runtime basically of the GNU family of runtimes?
Definition: ObjCRuntime.h:127
Represents the declaration of an Objective-C type parameter.
Definition: DeclObjC.h:578
ObjCTypeParamVariance getVariance() const
Determine the variance of this type parameter.
Definition: DeclObjC.h:622
Stores a list of Objective-C type parameters for a parameterized class or a category/extension thereo...
Definition: DeclObjC.h:658
Represents a type parameter type in Objective C.
Definition: Type.h:6223
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.cpp:4227
A structure for storing the information associated with an overloaded template name.
Definition: TemplateName.h:108
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition: ExprCXX.h:4142
Represents a pack expansion of types.
Definition: Type.h:6112
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6146
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4988
Sugar for parentheses used when specifying types.
Definition: Type.h:2872
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:2886
void clear()
Clear parent maps.
Represents a parameter to a function.
Definition: Decl.h:1749
ObjCDeclQualifier getObjCDeclQualifier() const
Definition: Decl.h:1813
QualType getOriginalType() const
Definition: Decl.cpp:2924
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:126
PipeType - OpenCL20.
Definition: Type.h:6751
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6768
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2898
QualType getPointeeType() const
Definition: Type.h:2908
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:2913
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:128
A (possibly-)qualified type.
Definition: Type.h:737
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:6985
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2665
Qualifiers::GC getObjCGCAttr() const
Returns gc attribute of this type.
Definition: Type.h:7032
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:6990
QualType withConst() const
Definition: Type.h:951
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:948
bool hasLocalQualifiers() const
Determine whether this particular QualType instance has any qualifiers, without looking through any t...
Definition: Type.h:864
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:804
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:6902
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7027
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:6942
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1229
QualType getCanonicalType() const
Definition: Type.h:6954
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:6995
SplitQualType getSplitDesugaredType() const
Definition: Type.h:1092
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition: Type.h:6923
void * getAsOpaquePtr() const
Definition: Type.h:784
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:6974
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:7022
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1323
bool isCanonical() const
Definition: Type.h:6959
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition: Type.h:1101
const Type * getTypePtrOrNull() const
Definition: Type.h:6906
PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const
Check if this is a non-trivial type that would cause a C struct transitively containing this type to ...
Definition: Type.cpp:2825
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: Type.h:6934
Represents a template name that was expressed as a qualified name.
Definition: TemplateName.h:431
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TemplateName.h:468
A qualifier set is used to build a set of qualifiers.
Definition: Type.h:6842
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:6849
The collection of all-type qualifiers we support.
Definition: Type.h:147
unsigned getCVRQualifiers() const
Definition: Type.h:295
void removeCVRQualifiers(unsigned mask)
Definition: Type.h:302
GC getObjCGCAttr() const
Definition: Type.h:326
void addAddressSpace(LangAS space)
Definition: Type.h:404
static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R)
Returns the common set of qualifiers while removing them from the given sets.
Definition: Type.h:198
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:175
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:168
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:164
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:178
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:181
void removeObjCLifetime()
Definition: Type.h:358
bool hasNonFastQualifiers() const
Return true if the set contains any qualifiers which require an ExtQuals node to be allocated.
Definition: Type.h:431
void addConsistentQualifiers(Qualifiers qs)
Add the qualifiers from the given set to this set, given that they don't conflict.
Definition: Type.h:478
void removeFastQualifiers(unsigned mask)
Definition: Type.h:417
bool hasUnaligned() const
Definition: Type.h:318
bool hasAddressSpace() const
Definition: Type.h:377
unsigned getFastQualifiers() const
Definition: Type.h:412
void removeAddressSpace()
Definition: Type.h:403
void setAddressSpace(LangAS space)
Definition: Type.h:398
unsigned getAsOpaqueValue() const
Definition: Type.h:260
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B)
Returns true if address space A is equal to or a superset of B.
Definition: Type.h:495
bool hasObjCGCAttr() const
Definition: Type.h:325
bool hasObjCLifetime() const
Definition: Type.h:351
ObjCLifetime getObjCLifetime() const
Definition: Type.h:352
bool empty() const
Definition: Type.h:440
void addObjCGCAttr(GC type)
Definition: Type.h:331
LangAS getAddressSpace() const
Definition: Type.h:378
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3071
unsigned getCommentBeginLine(RawComment *C, FileID File, unsigned Offset) const
const std::map< unsigned, RawComment * > * getCommentsInFile(FileID File) const
unsigned getCommentEndOffset(RawComment *C) const
void addComment(const RawComment &RC, const CommentOptions &CommentOpts, llvm::BumpPtrAllocator &Allocator)
bool isTrailingComment() const LLVM_READONLY
Returns true if it is a comment that should be put after a member:
SourceRange getSourceRange() const LLVM_READONLY
bool isDocumentation() const LLVM_READONLY
Returns true if this comment any kind of a documentation comment.
comments::FullComment * parse(const ASTContext &Context, const Preprocessor *PP, const Decl *D) const
Parse the comment, assuming it is attached to decl D.
Represents a struct/union/class.
Definition: Decl.h:4133
bool hasFlexibleArrayMember() const
Definition: Decl.h:4166
field_range fields() const
Definition: Decl.h:4339
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition: Decl.cpp:4982
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition: Decl.cpp:5047
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4324
bool field_empty() const
Definition: Decl.h:4347
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5092
RecordDecl * getDecl() const
Definition: Type.h:5102
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:216
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:204
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:226
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:296
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3009
QualType getPointeeType() const
Definition: Type.h:3027
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3035
This table allows us to fully hide how we implement multi-keyword caching.
std::string getAsString() const
Derive the full selector name (e.g.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
DiagnosticsEngine & getDiagnostics() const
StringRef getBufferData(FileID FID, bool *Invalid=nullptr) const
Return a StringRef to the source buffer data for the specified FileID.
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
unsigned getLineNumber(FileID FID, unsigned FilePos, bool *Invalid=nullptr) const
Given a SourceLocation, return the spelling line number for the position indicated.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
std::pair< FileID, unsigned > getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical, bool ProfileLambdaExpr=false) const
Produce a unique representation of the given statement.
The streaming interface shared between DiagnosticBuilder and PartialDiagnostic.
Definition: Diagnostic.h:1115
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1773
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, const SourceLocation *Loc, unsigned NumConcatenated)
This is the "fully general" constructor that allows representation of strings formed from multiple co...
Definition: Expr.cpp:1171
A structure for storing an already-substituted template template parameter pack.
Definition: TemplateName.h:141
Decl * getAssociatedDecl() const
A template-like entity which owns the whole pattern being substituted.
void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context)
TemplateTemplateParmDecl * getParameterPack() const
Retrieve the template template parameter pack being substituted.
TemplateArgument getArgumentPack() const
Retrieve the template template argument pack with which this parameter was substituted.
unsigned getIndex() const
Returns the index of the replaced parameter in the associated declaration.
Definition: TemplateName.h:156
A structure for storing the information associated with a substituted template template parameter.
Definition: TemplateName.h:373
void Profile(llvm::FoldingSetNodeID &ID)
TemplateTemplateParmDecl * getParameter() const
Represents the result of substituting a set of types for a template type parameter pack.
Definition: Type.h:5432
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.cpp:4073
Represents the result of substituting a type for a template type parameter.
Definition: Type.h:5362
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5401
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3549
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4704
bool isUnion() const
Definition: Decl.h:3755
TagDecl * getDecl() const
Definition: Type.cpp:3902
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
Kind
The basic C++ ABI kind.
Definition: TargetCXXABI.h:31
static Kind getKind(StringRef Name)
Definition: TargetCXXABI.h:59
Exposes information about the current target.
Definition: TargetInfo.h:213
TargetOptions & getTargetOpts() const
Retrieve the target options.
Definition: TargetInfo.h:304
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1220
IntType getInt64Type() const
Definition: TargetInfo.h:397
unsigned getMaxAtomicInlineWidth() const
Return the maximum width lock-free atomic operation which can be inlined given the supported features...
Definition: TargetInfo.h:810
virtual LangAS getCUDABuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space.
Definition: TargetInfo.h:1588
virtual LangAS getOpenCLBuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space.
Definition: TargetInfo.h:1582
unsigned getDefaultAlignForAttributeAligned() const
Return the default alignment for attribute((aligned)) on this target, to be used if no alignment valu...
Definition: TargetInfo.h:703
unsigned getBFloat16Width() const
getBFloat16Width/Align/Format - Return the size/align/format of '__bf16'.
Definition: TargetInfo.h:748
BuiltinVaListKind
The different kinds of __builtin_va_list types defined by the target implementation.
Definition: TargetInfo.h:311
@ AArch64ABIBuiltinVaList
__builtin_va_list as defined by the AArch64 ABI http://infocenter.arm.com/help/topic/com....
Definition: TargetInfo.h:320
@ PNaClABIBuiltinVaList
__builtin_va_list as defined by the PNaCl ABI: http://www.chromium.org/nativeclient/pnacl/bitcode-abi...
Definition: TargetInfo.h:324
@ PowerABIBuiltinVaList
__builtin_va_list as defined by the Power ABI: https://www.power.org /resources/downloads/Power-Arch-...
Definition: TargetInfo.h:329
@ AAPCSABIBuiltinVaList
__builtin_va_list as defined by ARM AAPCS ABI http://infocenter.arm.com
Definition: TargetInfo.h:338
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition: TargetInfo.h:313
@ VoidPtrBuiltinVaList
typedef void* __builtin_va_list;
Definition: TargetInfo.h:316
@ X86_64ABIBuiltinVaList
__builtin_va_list as defined by the x86-64 ABI: http://refspecs.linuxbase.org/elf/x86_64-abi-0....
Definition: TargetInfo.h:333
virtual uint64_t getNullPointerValue(LangAS AddrSpace) const
Get integer value for null pointer.
Definition: TargetInfo.h:480
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:464
static bool isTypeSigned(IntType T)
Returns true if the type is signed; false otherwise.
Definition: TargetInfo.cpp:369
unsigned getHalfAlign() const
Definition: TargetInfo.h:739
unsigned getBFloat16Align() const
Definition: TargetInfo.h:749
FloatModeKind getRealTypeByWidth(unsigned BitWidth, FloatModeKind ExplicitType) const
Return floating point type with specified width.
Definition: TargetInfo.cpp:315
virtual IntType getIntTypeByWidth(unsigned BitWidth, bool IsSigned) const
Return integer type with specified width.
Definition: TargetInfo.cpp:285
unsigned getHalfWidth() const
getHalfWidth/Align/Format - Return the size/align/format of 'half'.
Definition: TargetInfo.h:738
unsigned getMaxAlignedAttribute() const
Get the maximum alignment in bits for a static variable with aligned attribute.
Definition: TargetInfo.h:911
virtual unsigned getMinGlobalAlign(uint64_t Size, bool HasNonWeakDef) const
getMinGlobalAlign - Return the minimum alignment of a global variable, unless its alignment is explic...
Definition: TargetInfo.h:711
unsigned getTargetAddressSpace(LangAS AS) const
Definition: TargetInfo.h:1569
unsigned getFloat128Width() const
getFloat128Width/Align/Format - Return the size/align/format of '__float128'.
Definition: TargetInfo.h:767
const llvm::fltSemantics & getLongDoubleFormat() const
Definition: TargetInfo.h:761
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1291
bool useAddressSpaceMapMangling() const
Specify if mangling based on address space map should be used or not for language specific address sp...
Definition: TargetInfo.h:962
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
Definition: TargetInfo.h:506
unsigned getFloat128Align() const
Definition: TargetInfo.h:768
virtual bool hasBFloat16Type() const
Determine whether the _BFloat16 type is supported on this target.
Definition: TargetInfo.h:675
const llvm::fltSemantics & getFloat128Format() const
Definition: TargetInfo.h:769
unsigned getLongDoubleWidth() const
getLongDoubleWidth/Align/Format - Return the size/align/format of 'long double'.
Definition: TargetInfo.h:759
unsigned getLongDoubleAlign() const
Definition: TargetInfo.h:760
virtual std::optional< std::pair< unsigned, unsigned > > getVScaleRange(const LangOptions &LangOpts) const
Returns target-specific min and max values VScale_Range.
Definition: TargetInfo.h:981
llvm::StringMap< bool > FeatureMap
The map of which features have been enabled disabled based on the command line.
Definition: TargetOptions.h:62
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
SourceLocation getRAngleLoc() const
Definition: TemplateBase.h:648
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:659
SourceLocation getLAngleLoc() const
Definition: TemplateBase.h:647
A template argument list.
Definition: DeclTemplate.h:244
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:274
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
Represents a template argument.
Definition: TemplateBase.h:61
QualType getStructuralValueType() const
Get the type of a StructuralValue.
Definition: TemplateBase.h:399
QualType getParamTypeForDecl() const
Definition: TemplateBase.h:331
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:408
std::optional< unsigned > getNumTemplateExpansions() const
Retrieve the number of expansions that a template template argument expansion will produce,...
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:319
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
Definition: TemplateBase.h:337
static TemplateArgument CreatePackCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument pack by copying the given set of template arguments.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
Definition: TemplateBase.h:343
bool structurallyEquals(const TemplateArgument &Other) const
Determines whether two template arguments are superficially the same.
QualType getIntegralType() const
Retrieve the type of the integral value.
Definition: TemplateBase.h:377
bool getIsDefaulted() const
If returns 'true', this TemplateArgument corresponds to a default template parameter.
Definition: TemplateBase.h:393
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:326
ArrayRef< TemplateArgument > pack_elements() const
Iterator range referencing all of the elements of a template argument pack.
Definition: TemplateBase.h:432
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:74
@ Template
The template argument is a template name that was provided for a template template parameter.
Definition: TemplateBase.h:93
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
Definition: TemplateBase.h:89
@ Pack
The template argument is actually a parameter pack.
Definition: TemplateBase.h:107
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
Definition: TemplateBase.h:97
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:78
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
Definition: TemplateBase.h:67
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
Definition: TemplateBase.h:82
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
Definition: TemplateBase.h:103
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion,...
Definition: TemplateBase.h:350
const APValue & getAsStructuralValue() const
Get the value of a StructuralValue.
Definition: TemplateBase.h:396
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:394
bool isTypeAlias() const
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:413
Represents a C++ template name within the type system.
Definition: TemplateName.h:202
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
QualifiedTemplateName * getAsQualifiedTemplateName() const
Retrieve the underlying qualified template name structure, if any.
void * getAsVoidPointer() const
Retrieve the template name as a void pointer.
Definition: TemplateName.h:357
@ UsingTemplate
A template name that refers to a template declaration found through a specific using shadow declarati...
Definition: TemplateName.h:247
@ OverloadedTemplate
A set of overloaded template declarations.
Definition: TemplateName.h:222
@ Template
A single template declaration.
Definition: TemplateName.h:219
@ DependentTemplate
A dependent template name that has not been resolved to a template (or set of templates).
Definition: TemplateName.h:234
@ SubstTemplateTemplateParm
A template template parameter that has been substituted for some other template name.
Definition: TemplateName.h:238
@ SubstTemplateTemplateParmPack
A template template parameter pack that has been substituted for a template template argument pack,...
Definition: TemplateName.h:243
@ QualifiedTemplate
A qualified template name, where the qualification is kept to describe the source code as written.
Definition: TemplateName.h:230
@ AssumedTemplate
An unqualified-id that has been assumed to name a function template that will be found by ADL.
Definition: TemplateName.h:226
A template parameter object.
static void Profile(llvm::FoldingSetNodeID &ID, QualType T, const APValue &V)
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:144
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
NamedDecl *const * const_iterator
Iterates through the template parameters in this list.
Definition: DeclTemplate.h:129
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
Definition: DeclTemplate.h:180
void setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI)
Definition: TypeLoc.h:1656
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1632
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1673
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1640
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1648
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:5632
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.cpp:4162
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
unsigned getPosition() const
Get the position of the template parameter within its parameter list.
bool isParameterPack() const
Whether this template template parameter is a template parameter pack.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
bool isExpandedParameterPack() const
Whether this parameter is a template template parameter pack that has a known list of different templ...
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, bool ParameterPack, IdentifierInfo *Id, TemplateParameterList *Params)
Declaration of a template type parameter.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, std::optional< unsigned > NumExpanded=std::nullopt)
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5334
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition: ASTConcept.h:231
ConceptDecl * getNamedConcept() const
Definition: ASTConcept.h:254
Expr * getImmediatelyDeclaredConstraint() const
Get the immediately-declared constraint expression introduced by this type-constraint,...
Definition: ASTConcept.h:246
ConceptReference * getConceptReference() const
Definition: ASTConcept.h:250
Represents a declaration of a type.
Definition: Decl.h:3357
void setTypeForDecl(const Type *TD)
Definition: Decl.h:3382
const Type * getTypeForDecl() const
Definition: Decl.h:3381
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition: TypeLoc.h:78
static unsigned getFullDataSizeForType(QualType Ty)
Returns the size of type source info data block for the given type.
Definition: TypeLoc.cpp:94
void initialize(ASTContext &Context, SourceLocation Loc) const
Initializes this to state that every location in this type is the given location.
Definition: TypeLoc.h:200
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition: Type.h:4817
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition: Type.h:4865
A container of type source information.
Definition: Type.h:6873
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
The base class of the type hierarchy.
Definition: Type.h:1606
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1819
bool isBlockPointerType() const
Definition: Type.h:7162
bool isBooleanType() const
Definition: Type.h:7567
bool isObjCBuiltinType() const
Definition: Type.h:7333
QualType getRVVEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an RVV builtin type.
Definition: Type.cpp:2493
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:686
bool isIncompleteArrayType() const
Definition: Type.h:7228
bool isPlaceholderType() const
Test for a type which does not represent an actual type-system type but is instead used as a placehol...
Definition: Type.h:7419
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2083
bool hasIntegerRepresentation() const
Determine whether this type has an integer representation of some sort, e.g., it is an integer type o...
Definition: Type.cpp:1958
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition: Type.cpp:2289
bool isArrayType() const
Definition: Type.h:7220
bool isCharType() const
Definition: Type.cpp:2026
QualType getLocallyUnqualifiedSingleStepDesugaredType() const
Pull a single level of sugar off of this locally-unqualified type.
Definition: Type.cpp:444
bool isPointerType() const
Definition: Type.h:7154
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:7479
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition: Type.cpp:2409
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:7724
bool isSpecificPlaceholderType(unsigned K) const
Test for a specific placeholder type.
Definition: Type.h:7432
bool isSignedFixedPointType() const
Return true if this is a fixed point type that is signed according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:7520
bool isEnumeralType() const
Definition: Type.h:7248
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2436
bool isObjCQualifiedIdType() const
Definition: Type.h:7303
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:651
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:7554
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e....
Definition: Type.cpp:2173
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition: Type.cpp:2462
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2525
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2428
bool isBitIntType() const
Definition: Type.h:7378
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:7412
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:7240
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2420
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:7492
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:7508
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:2094
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition: Type.cpp:2123
QualType getCanonicalTypeInternal() const
Definition: Type.h:2703
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:7607
bool isMemberPointerType() const
Definition: Type.h:7202
bool isObjCIdType() const
Definition: Type.h:7315
bool isUnsaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:7516
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:7710
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2299
bool isFunctionType() const
Definition: Type.h:7150
bool isObjCObjectPointerType() const
Definition: Type.h:7282
bool isUnsignedFixedPointType() const
Return true if this is a fixed point type that is unsigned according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:7534
bool isVectorType() const
Definition: Type.h:7256
bool isObjCClassType() const
Definition: Type.h:7321
bool isRVVVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'riscv_rvv_vector_bits' type attribute,...
Definition: Type.cpp:2475
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2423
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition: Type.cpp:2133
bool isAnyPointerType() const
Definition: Type.h:7158
TypeClass getTypeClass() const
Definition: Type.h:2074
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition: Type.h:2100
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:7657
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition: Type.cpp:565
bool isNullPtrType() const
Definition: Type.h:7472
bool isRecordType() const
Definition: Type.h:7244
bool isObjCRetainableType() const
Definition: Type.cpp:4758
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4516
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition: Decl.h:3501
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5462
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3399
QualType getUnderlyingType() const
Definition: Decl.h:3454
void setTypeSourceInfo(TypeSourceInfo *newType)
Definition: Decl.h:3461
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4770
A unary type transform, which is a type constructed from another.
Definition: Type.h:5009
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition: DeclCXX.h:4339
static void Profile(llvm::FoldingSetNodeID &ID, QualType Ty, const APValue &APVal)
Definition: DeclCXX.h:4367
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition: Type.h:4687
Represents a dependent using declaration which was marked with typename.
Definition: DeclCXX.h:3952
Represents a C++ using-enum-declaration.
Definition: DeclCXX.h:3706
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3313
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition: DeclCXX.h:3377
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4738
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:706
void setType(QualType newType)
Definition: Decl.h:718
QualType getType() const
Definition: Decl.h:717
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition: Decl.cpp:5324
void clear()
Definition: Value.cpp:218
Represents a variable declaration or definition.
Definition: Decl.h:918
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition: Decl.cpp:2787
bool hasInit() const
Definition: Decl.cpp:2395
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a static data member.
Definition: Decl.cpp:2438
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1267
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:1192
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition: Decl.cpp:2749
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1528
@ DeclarationOnly
This declaration is only a declaration.
Definition: Decl.h:1279
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition: Decl.cpp:2372
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2756
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:3290
Expr * getSizeExpr() const
Definition: Type.h:3309
Represents a GCC generic vector type.
Definition: Type.h:3512
unsigned getNumElements() const
Definition: Type.h:3527
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3536
VectorKind getVectorKind() const
Definition: Type.h:3532
QualType getElementType() const
Definition: Type.h:3526
A full comment attached to a declaration, contains block content.
Definition: Comment.h:1083
ArrayRef< BlockContentComment * > getBlocks() const
Definition: Comment.h:1121
const DeclInfo * getDeclInfo() const LLVM_READONLY
Definition: Comment.h:1115
const Decl * getDecl() const LLVM_READONLY
Definition: Comment.h:1111
Holds all information required to evaluate constexpr code in a module.
Definition: Context.h:40
Defines the Linkage enumeration and various utility functions.
Defines the clang::TargetInfo interface.
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< ArrayType > arrayType
Matches all kinds of arrays.
const AstTypeMatcher< TagType > tagType
Matches tag types (record and enum types).
The JSON file list parser is used to communicate input to InstallAPI.
@ Vector
'vector' clause, allowed on 'loop', Combined, and 'routine' directives.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
@ OpenCL
Definition: LangStandard.h:64
@ CPlusPlus20
Definition: LangStandard.h:58
@ CPlusPlus
Definition: LangStandard.h:54
GVALinkage
A more specific kind of linkage than enum Linkage.
Definition: Linkage.h:72
@ GVA_StrongODR
Definition: Linkage.h:77
@ GVA_StrongExternal
Definition: Linkage.h:76
@ GVA_AvailableExternally
Definition: Linkage.h:74
@ GVA_DiscardableODR
Definition: Linkage.h:75
@ GVA_Internal
Definition: Linkage.h:73
AutoTypeKeyword
Which keyword(s) were used to create an AutoType.
Definition: Type.h:1565
OpenCLTypeKind
OpenCL type kinds.
Definition: TargetInfo.h:199
@ OCLTK_ReserveID
Definition: TargetInfo.h:206
@ OCLTK_Sampler
Definition: TargetInfo.h:207
@ OCLTK_Pipe
Definition: TargetInfo.h:204
@ OCLTK_ClkEvent
Definition: TargetInfo.h:201
@ OCLTK_Event
Definition: TargetInfo.h:202
@ OCLTK_Default
Definition: TargetInfo.h:200
@ OCLTK_Queue
Definition: TargetInfo.h:205
FunctionType::ExtInfo getFunctionExtInfo(const Type &t)
Definition: Type.h:7054
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
@ ICIS_NoInit
No in-class initializer.
Definition: Specifiers.h:269
CXXABI * CreateMicrosoftCXXABI(ASTContext &Ctx)
TypeOfKind
The kind of 'typeof' expression we're after.
Definition: Type.h:718
@ SC_Register
Definition: Specifiers.h:254
@ SC_Static
Definition: Specifiers.h:249
CXXABI * CreateItaniumCXXABI(ASTContext &Ctx)
Creates an instance of a C++ ABI class.
const StreamingDiagnostic & operator<<(const StreamingDiagnostic &DB, const ASTContext::SectionInfo &Section)
Insertion operator for diagnostics.
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition: Linkage.h:24
@ External
External linkage, which indicates that the entity can be referred to from other translation units.
@ Result
The result type of a method or function.
ArraySizeModifier
Capture whether this is a normal array (e.g.
Definition: Type.h:3144
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
TagTypeKind
The kind of a tag type.
Definition: Type.h:5842
@ Interface
The "__interface" keyword.
@ Struct
The "struct" keyword.
@ Class
The "class" keyword.
bool isDiscardableGVALinkage(GVALinkage L)
Definition: Linkage.h:80
BuiltinTemplateKind
Kinds of BuiltinTemplateDecl.
Definition: Builtins.h:302
@ BTK__type_pack_element
This names the __type_pack_element BuiltinTemplateDecl.
Definition: Builtins.h:307
@ BTK__make_integer_seq
This names the __make_integer_seq BuiltinTemplateDecl.
Definition: Builtins.h:304
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
TranslationUnitKind
Describes the kind of translation unit being processed.
Definition: LangOptions.h:982
@ TypeAlignment
Definition: Type.h:70
FloatModeKind
Definition: TargetInfo.h:71
bool isPtrSizeAddressSpace(LangAS AS)
Definition: AddressSpaces.h:91
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:132
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:141
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:136
void printTemplateArgumentList(raw_ostream &OS, ArrayRef< TemplateArgument > Args, const PrintingPolicy &Policy, const TemplateParameterList *TPL=nullptr)
Print a template argument list, including the '<' and '>' enclosing the template arguments.
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1285
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:185
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:203
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:199
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:195
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:191
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:188
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:275
@ CC_C
Definition: Specifiers.h:276
@ CC_M68kRTD
Definition: Specifiers.h:297
@ CC_X86RegCall
Definition: Specifiers.h:284
@ CC_X86VectorCall
Definition: Specifiers.h:280
@ CC_X86StdCall
Definition: Specifiers.h:277
@ CC_X86FastCall
Definition: Specifiers.h:278
@ Invariant
The parameter is invariant: must match exactly.
@ Contravariant
The parameter is contravariant, e.g., X<T> is a subtype of X when the type parameter is covariant and...
@ Covariant
The parameter is covariant, e.g., X<T> is a subtype of X when the type parameter is covariant and T i...
VectorKind
Definition: Type.h:3475
@ AltiVecBool
is AltiVec 'vector bool ...'
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
@ AltiVecPixel
is AltiVec 'vector Pixel'
@ Generic
not a target-specific vector type
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
LangAS getLangASFromTargetAS(unsigned TargetAS)
Definition: AddressSpaces.h:86
AlignRequirementKind
Definition: ASTContext.h:138
@ None
The alignment was not explicit in code.
@ RequiredByEnum
The alignment comes from an alignment attribute on a enum type.
@ RequiredByTypedef
The alignment comes from an alignment attribute on a typedef.
@ RequiredByRecord
The alignment comes from an alignment attribute on a record type.
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: Type.h:5817
@ None
No keyword precedes the qualified type name.
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
@ EST_DependentNoexcept
noexcept(expression), value-dependent
@ EST_DynamicNone
throw()
@ EST_Uninstantiated
not instantiated yet
@ EST_Unparsed
not parsed yet
@ EST_NoThrow
Microsoft __declspec(nothrow) extension.
@ EST_None
no exception specification
@ EST_MSAny
Microsoft throw(...) extension.
@ EST_BasicNoexcept
noexcept
@ EST_NoexceptFalse
noexcept(expression), evals to 'false'
@ EST_Unevaluated
not evaluated yet, for special member function
@ EST_NoexceptTrue
noexcept(expression), evals to 'true'
@ EST_Dynamic
throw(T1, T2)
@ AS_public
Definition: Specifiers.h:121
unsigned long uint64_t
unsigned NumTemplateArgs
The number of template arguments in TemplateArgs.
Definition: TemplateBase.h:694
Copy initialization expr of a __block variable and a boolean flag that indicates whether the expressi...
Definition: Expr.h:6213
Expr * getCopyExpr() const
Definition: Expr.h:6220
bool ParseAllComments
Treat ordinary comments as documentation comments.
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
Holds information about the various types of exception specification.
Definition: Type.h:4250
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:4252
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition: Type.h:4255
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition: Type.h:4258
Extra information about a function prototype.
Definition: Type.h:4278
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:4285
bool requiresFunctionProtoTypeArmAttributes() const
Definition: Type.h:4308
const ExtParameterInfo * ExtParameterInfos
Definition: Type.h:4286
bool requiresFunctionProtoTypeExtraBitfields() const
Definition: Type.h:4303
FunctionType::ExtInfo ExtInfo
Definition: Type.h:4279
A simple holder for a QualType representing a type in an exception specification.
Definition: Type.h:4037
A holder for Arm type attributes as described in the Arm C/C++ Language extensions which are not part...
Definition: Type.h:4093
A simple holder for various uncommon bits which do not fit in FunctionTypeBitfields.
Definition: Type.h:4042
A lazy value (of type T) that is within an AST node of type Owner, where the value might change in la...
Parts of a decomposed MSGuidDecl.
Definition: DeclCXX.h:4257
Contains information gathered from parsing the contents of TargetAttr.
Definition: TargetInfo.h:56
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition: Type.h:670
const Type * Ty
The locally-unqualified type.
Definition: Type.h:672
Qualifiers Quals
The local qualifiers.
Definition: Type.h:675
A this pointer adjustment.
Definition: Thunk.h:91
IntType
===-— Target Data Type Query Methods ----------------------------—===//
Definition: TargetInfo.h:137
AlignRequirementKind AlignRequirement
Definition: ASTContext.h:169
bool isAlignRequired()
Definition: ASTContext.h:161
AlignRequirementKind AlignRequirement
Definition: ASTContext.h:155
uint64_t Width
Definition: ASTContext.h:153
unsigned Align
Definition: ASTContext.h:154
Information about the declaration, useful to clients of FullComment.
Definition: Comment.h:962
const TemplateParameterList * TemplateParameters
Template parameters that can be referenced by \tparam if CommentDecl is a template (IsTemplateDecl or...
Definition: Comment.h:988
const Decl * CommentDecl
Declaration the comment is actually attached to (in the source).
Definition: Comment.h:965