clang 22.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 "ByteCode/Context.h"
15#include "CXXABI.h"
16#include "clang/AST/APValue.h"
21#include "clang/AST/Attr.h"
23#include "clang/AST/CharUnits.h"
24#include "clang/AST/Comment.h"
25#include "clang/AST/Decl.h"
26#include "clang/AST/DeclBase.h"
27#include "clang/AST/DeclCXX.h"
29#include "clang/AST/DeclObjC.h"
34#include "clang/AST/Expr.h"
35#include "clang/AST/ExprCXX.h"
37#include "clang/AST/Mangle.h"
43#include "clang/AST/Stmt.h"
46#include "clang/AST/Type.h"
47#include "clang/AST/TypeLoc.h"
55#include "clang/Basic/LLVM.h"
57#include "clang/Basic/Linkage.h"
58#include "clang/Basic/Module.h"
68#include "llvm/ADT/APFixedPoint.h"
69#include "llvm/ADT/APInt.h"
70#include "llvm/ADT/APSInt.h"
71#include "llvm/ADT/ArrayRef.h"
72#include "llvm/ADT/DenseMap.h"
73#include "llvm/ADT/DenseSet.h"
74#include "llvm/ADT/FoldingSet.h"
75#include "llvm/ADT/PointerUnion.h"
76#include "llvm/ADT/STLExtras.h"
77#include "llvm/ADT/SmallPtrSet.h"
78#include "llvm/ADT/SmallVector.h"
79#include "llvm/ADT/StringExtras.h"
80#include "llvm/ADT/StringRef.h"
81#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
82#include "llvm/Support/Capacity.h"
83#include "llvm/Support/Casting.h"
84#include "llvm/Support/Compiler.h"
85#include "llvm/Support/ErrorHandling.h"
86#include "llvm/Support/MD5.h"
87#include "llvm/Support/MathExtras.h"
88#include "llvm/Support/SipHash.h"
89#include "llvm/Support/raw_ostream.h"
90#include "llvm/TargetParser/AArch64TargetParser.h"
91#include "llvm/TargetParser/Triple.h"
92#include <algorithm>
93#include <cassert>
94#include <cstddef>
95#include <cstdint>
96#include <cstdlib>
97#include <map>
98#include <memory>
99#include <optional>
100#include <string>
101#include <tuple>
102#include <utility>
103
104using namespace clang;
105
116
117template <> struct llvm::DenseMapInfo<llvm::FoldingSetNodeID> {
118 static FoldingSetNodeID getEmptyKey() { return FoldingSetNodeID{}; }
119
120 static FoldingSetNodeID getTombstoneKey() {
121 FoldingSetNodeID id;
122 for (size_t i = 0; i < sizeof(id) / sizeof(unsigned); ++i) {
123 id.AddInteger(std::numeric_limits<unsigned>::max());
124 }
125 return id;
126 }
127
128 static unsigned getHashValue(const FoldingSetNodeID &Val) {
129 return Val.ComputeHash();
130 }
131
132 static bool isEqual(const FoldingSetNodeID &LHS,
133 const FoldingSetNodeID &RHS) {
134 return LHS == RHS;
135 }
136};
137
138/// \returns The locations that are relevant when searching for Doc comments
139/// related to \p D.
142 assert(D);
143
144 // User can not attach documentation to implicit declarations.
145 if (D->isImplicit())
146 return {};
147
148 // User can not attach documentation to implicit instantiations.
149 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
150 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
151 return {};
152 }
153
154 if (const auto *VD = dyn_cast<VarDecl>(D)) {
155 if (VD->isStaticDataMember() &&
156 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
157 return {};
158 }
159
160 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
161 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
162 return {};
163 }
164
165 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
166 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
167 if (TSK == TSK_ImplicitInstantiation ||
168 TSK == TSK_Undeclared)
169 return {};
170 }
171
172 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
173 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
174 return {};
175 }
176 if (const auto *TD = dyn_cast<TagDecl>(D)) {
177 // When tag declaration (but not definition!) is part of the
178 // decl-specifier-seq of some other declaration, it doesn't get comment
179 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
180 return {};
181 }
182 // TODO: handle comments for function parameters properly.
183 if (isa<ParmVarDecl>(D))
184 return {};
185
186 // TODO: we could look up template parameter documentation in the template
187 // documentation.
191 return {};
192
194 // Find declaration location.
195 // For Objective-C declarations we generally don't expect to have multiple
196 // declarators, thus use declaration starting location as the "declaration
197 // location".
198 // For all other declarations multiple declarators are used quite frequently,
199 // so we use the location of the identifier as the "declaration location".
200 SourceLocation BaseLocation;
204 // Allow association with Y across {} in `typedef struct X {} Y`.
206 BaseLocation = D->getBeginLoc();
207 else
208 BaseLocation = D->getLocation();
209
210 if (!D->getLocation().isMacroID()) {
211 Locations.emplace_back(BaseLocation);
212 } else {
213 const auto *DeclCtx = D->getDeclContext();
214
215 // When encountering definitions generated from a macro (that are not
216 // contained by another declaration in the macro) we need to try and find
217 // the comment at the location of the expansion but if there is no comment
218 // there we should retry to see if there is a comment inside the macro as
219 // well. To this end we return first BaseLocation to first look at the
220 // expansion site, the second value is the spelling location of the
221 // beginning of the declaration defined inside the macro.
222 if (!(DeclCtx &&
223 Decl::castFromDeclContext(DeclCtx)->getLocation().isMacroID())) {
224 Locations.emplace_back(SourceMgr.getExpansionLoc(BaseLocation));
225 }
226
227 // We use Decl::getBeginLoc() and not just BaseLocation here to ensure that
228 // we don't refer to the macro argument location at the expansion site (this
229 // can happen if the name's spelling is provided via macro argument), and
230 // always to the declaration itself.
231 Locations.emplace_back(SourceMgr.getSpellingLoc(D->getBeginLoc()));
232 }
233
234 return Locations;
235}
236
238 const Decl *D, const SourceLocation RepresentativeLocForDecl,
239 const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
240 // If the declaration doesn't map directly to a location in a file, we
241 // can't find the comment.
242 if (RepresentativeLocForDecl.isInvalid() ||
243 !RepresentativeLocForDecl.isFileID())
244 return nullptr;
245
246 // If there are no comments anywhere, we won't find anything.
247 if (CommentsInTheFile.empty())
248 return nullptr;
249
250 // Decompose the location for the declaration and find the beginning of the
251 // file buffer.
252 const FileIDAndOffset DeclLocDecomp =
253 SourceMgr.getDecomposedLoc(RepresentativeLocForDecl);
254
255 // Slow path.
256 auto OffsetCommentBehindDecl =
257 CommentsInTheFile.lower_bound(DeclLocDecomp.second);
258
259 // First check whether we have a trailing comment.
260 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
261 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
262 if ((CommentBehindDecl->isDocumentation() ||
263 LangOpts.CommentOpts.ParseAllComments) &&
264 CommentBehindDecl->isTrailingComment() &&
267
268 // Check that Doxygen trailing comment comes after the declaration, starts
269 // on the same line and in the same file as the declaration.
270 if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) ==
271 Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first,
272 OffsetCommentBehindDecl->first)) {
273 return CommentBehindDecl;
274 }
275 }
276 }
277
278 // The comment just after the declaration was not a trailing comment.
279 // Let's look at the previous comment.
280 if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
281 return nullptr;
282
283 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
284 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
285
286 // Check that we actually have a non-member Doxygen comment.
287 if (!(CommentBeforeDecl->isDocumentation() ||
288 LangOpts.CommentOpts.ParseAllComments) ||
289 CommentBeforeDecl->isTrailingComment())
290 return nullptr;
291
292 // Decompose the end of the comment.
293 const unsigned CommentEndOffset =
294 Comments.getCommentEndOffset(CommentBeforeDecl);
295
296 // Get the corresponding buffer.
297 bool Invalid = false;
298 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
299 &Invalid).data();
300 if (Invalid)
301 return nullptr;
302
303 // Extract text between the comment and declaration.
304 StringRef Text(Buffer + CommentEndOffset,
305 DeclLocDecomp.second - CommentEndOffset);
306
307 // There should be no other declarations or preprocessor directives between
308 // comment and declaration.
309 if (Text.find_last_of(";{}#@") != StringRef::npos)
310 return nullptr;
311
312 return CommentBeforeDecl;
313}
314
316 const auto DeclLocs = getDeclLocsForCommentSearch(D, SourceMgr);
317
318 for (const auto DeclLoc : DeclLocs) {
319 // If the declaration doesn't map directly to a location in a file, we
320 // can't find the comment.
321 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
322 continue;
323
325 ExternalSource->ReadComments();
326 CommentsLoaded = true;
327 }
328
329 if (Comments.empty())
330 continue;
331
332 const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first;
333 if (!File.isValid())
334 continue;
335
336 const auto CommentsInThisFile = Comments.getCommentsInFile(File);
337 if (!CommentsInThisFile || CommentsInThisFile->empty())
338 continue;
339
340 if (RawComment *Comment =
341 getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile))
342 return Comment;
343 }
344
345 return nullptr;
346}
347
349 assert(LangOpts.RetainCommentsFromSystemHeaders ||
350 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
351 Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
352}
353
354/// If we have a 'templated' declaration for a template, adjust 'D' to
355/// refer to the actual template.
356/// If we have an implicit instantiation, adjust 'D' to refer to template.
357static const Decl &adjustDeclToTemplate(const Decl &D) {
358 if (const auto *FD = dyn_cast<FunctionDecl>(&D)) {
359 // Is this function declaration part of a function template?
360 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
361 return *FTD;
362
363 // Nothing to do if function is not an implicit instantiation.
364 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
365 return D;
366
367 // Function is an implicit instantiation of a function template?
368 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
369 return *FTD;
370
371 // Function is instantiated from a member definition of a class template?
372 if (const FunctionDecl *MemberDecl =
374 return *MemberDecl;
375
376 return D;
377 }
378 if (const auto *VD = dyn_cast<VarDecl>(&D)) {
379 // Static data member is instantiated from a member definition of a class
380 // template?
381 if (VD->isStaticDataMember())
382 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
383 return *MemberDecl;
384
385 return D;
386 }
387 if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) {
388 // Is this class declaration part of a class template?
389 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
390 return *CTD;
391
392 // Class is an implicit instantiation of a class template or partial
393 // specialization?
394 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
395 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
396 return D;
397 llvm::PointerUnion<ClassTemplateDecl *,
400 return isa<ClassTemplateDecl *>(PU)
401 ? *static_cast<const Decl *>(cast<ClassTemplateDecl *>(PU))
402 : *static_cast<const Decl *>(
404 }
405
406 // Class is instantiated from a member definition of a class template?
407 if (const MemberSpecializationInfo *Info =
408 CRD->getMemberSpecializationInfo())
409 return *Info->getInstantiatedFrom();
410
411 return D;
412 }
413 if (const auto *ED = dyn_cast<EnumDecl>(&D)) {
414 // Enum is instantiated from a member definition of a class template?
415 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
416 return *MemberDecl;
417
418 return D;
419 }
420 // FIXME: Adjust alias templates?
421 return D;
422}
423
425 const Decl *D,
426 const Decl **OriginalDecl) const {
427 if (!D) {
428 if (OriginalDecl)
429 OriginalDecl = nullptr;
430 return nullptr;
431 }
432
433 D = &adjustDeclToTemplate(*D);
434
435 // Any comment directly attached to D?
436 {
437 auto DeclComment = DeclRawComments.find(D);
438 if (DeclComment != DeclRawComments.end()) {
439 if (OriginalDecl)
440 *OriginalDecl = D;
441 return DeclComment->second;
442 }
443 }
444
445 // Any comment attached to any redeclaration of D?
446 const Decl *CanonicalD = D->getCanonicalDecl();
447 if (!CanonicalD)
448 return nullptr;
449
450 {
451 auto RedeclComment = RedeclChainComments.find(CanonicalD);
452 if (RedeclComment != RedeclChainComments.end()) {
453 if (OriginalDecl)
454 *OriginalDecl = RedeclComment->second;
455 auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second);
456 assert(CommentAtRedecl != DeclRawComments.end() &&
457 "This decl is supposed to have comment attached.");
458 return CommentAtRedecl->second;
459 }
460 }
461
462 // Any redeclarations of D that we haven't checked for comments yet?
463 const Decl *LastCheckedRedecl = [&]() {
464 const Decl *LastChecked = CommentlessRedeclChains.lookup(CanonicalD);
465 bool CanUseCommentlessCache = false;
466 if (LastChecked) {
467 for (auto *Redecl : CanonicalD->redecls()) {
468 if (Redecl == D) {
469 CanUseCommentlessCache = true;
470 break;
471 }
472 if (Redecl == LastChecked)
473 break;
474 }
475 }
476 // FIXME: This could be improved so that even if CanUseCommentlessCache
477 // is false, once we've traversed past CanonicalD we still skip ahead
478 // LastChecked.
479 return CanUseCommentlessCache ? LastChecked : nullptr;
480 }();
481
482 for (const Decl *Redecl : D->redecls()) {
483 assert(Redecl);
484 // Skip all redeclarations that have been checked previously.
485 if (LastCheckedRedecl) {
486 if (LastCheckedRedecl == Redecl) {
487 LastCheckedRedecl = nullptr;
488 }
489 continue;
490 }
491 const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl);
492 if (RedeclComment) {
493 cacheRawCommentForDecl(*Redecl, *RedeclComment);
494 if (OriginalDecl)
495 *OriginalDecl = Redecl;
496 return RedeclComment;
497 }
498 CommentlessRedeclChains[CanonicalD] = Redecl;
499 }
500
501 if (OriginalDecl)
502 *OriginalDecl = nullptr;
503 return nullptr;
504}
505
507 const RawComment &Comment) const {
508 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
509 DeclRawComments.try_emplace(&OriginalD, &Comment);
510 const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl();
511 RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD);
512 CommentlessRedeclChains.erase(CanonicalDecl);
513}
514
515static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
517 const DeclContext *DC = ObjCMethod->getDeclContext();
518 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
519 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
520 if (!ID)
521 return;
522 // Add redeclared method here.
523 for (const auto *Ext : ID->known_extensions()) {
524 if (ObjCMethodDecl *RedeclaredMethod =
525 Ext->getMethod(ObjCMethod->getSelector(),
526 ObjCMethod->isInstanceMethod()))
527 Redeclared.push_back(RedeclaredMethod);
528 }
529 }
530}
531
533 const Preprocessor *PP) {
534 if (Comments.empty() || Decls.empty())
535 return;
536
537 FileID File;
538 for (const Decl *D : Decls) {
539 if (D->isInvalidDecl())
540 continue;
541
542 D = &adjustDeclToTemplate(*D);
543 SourceLocation Loc = D->getLocation();
544 if (Loc.isValid()) {
545 // See if there are any new comments that are not attached to a decl.
546 // The location doesn't have to be precise - we care only about the file.
547 File = SourceMgr.getDecomposedLoc(Loc).first;
548 break;
549 }
550 }
551
552 if (File.isInvalid())
553 return;
554
555 auto CommentsInThisFile = Comments.getCommentsInFile(File);
556 if (!CommentsInThisFile || CommentsInThisFile->empty() ||
557 CommentsInThisFile->rbegin()->second->isAttached())
558 return;
559
560 // There is at least one comment not attached to a decl.
561 // Maybe it should be attached to one of Decls?
562 //
563 // Note that this way we pick up not only comments that precede the
564 // declaration, but also comments that *follow* the declaration -- thanks to
565 // the lookahead in the lexer: we've consumed the semicolon and looked
566 // ahead through comments.
567 for (const Decl *D : Decls) {
568 assert(D);
569 if (D->isInvalidDecl())
570 continue;
571
572 D = &adjustDeclToTemplate(*D);
573
574 if (DeclRawComments.count(D) > 0)
575 continue;
576
577 const auto DeclLocs = getDeclLocsForCommentSearch(D, SourceMgr);
578
579 for (const auto DeclLoc : DeclLocs) {
580 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
581 continue;
582
583 if (RawComment *const DocComment = getRawCommentForDeclNoCacheImpl(
584 D, DeclLoc, *CommentsInThisFile)) {
585 cacheRawCommentForDecl(*D, *DocComment);
586 comments::FullComment *FC = DocComment->parse(*this, PP, D);
587 ParsedComments[D->getCanonicalDecl()] = FC;
588 break;
589 }
590 }
591 }
592}
593
595 const Decl *D) const {
596 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
597 ThisDeclInfo->CommentDecl = D;
598 ThisDeclInfo->IsFilled = false;
599 ThisDeclInfo->fill();
600 ThisDeclInfo->CommentDecl = FC->getDecl();
601 if (!ThisDeclInfo->TemplateParameters)
602 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
604 new (*this) comments::FullComment(FC->getBlocks(),
605 ThisDeclInfo);
606 return CFC;
607}
608
611 return RC ? RC->parse(*this, nullptr, D) : nullptr;
612}
613
615 const Decl *D,
616 const Preprocessor *PP) const {
617 if (!D || D->isInvalidDecl())
618 return nullptr;
619 D = &adjustDeclToTemplate(*D);
620
621 const Decl *Canonical = D->getCanonicalDecl();
622 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
623 ParsedComments.find(Canonical);
624
625 if (Pos != ParsedComments.end()) {
626 if (Canonical != D) {
627 comments::FullComment *FC = Pos->second;
629 return CFC;
630 }
631 return Pos->second;
632 }
633
634 const Decl *OriginalDecl = nullptr;
635
636 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
637 if (!RC) {
640 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
641 if (OMD && OMD->isPropertyAccessor())
642 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
643 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
644 return cloneFullComment(FC, D);
645 if (OMD)
646 addRedeclaredMethods(OMD, Overridden);
647 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
648 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
649 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
650 return cloneFullComment(FC, D);
651 }
652 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
653 // Attach any tag type's documentation to its typedef if latter
654 // does not have one of its own.
655 QualType QT = TD->getUnderlyingType();
656 if (const auto *TT = QT->getAs<TagType>())
657 if (comments::FullComment *FC =
658 getCommentForDecl(TT->getOriginalDecl(), PP))
659 return cloneFullComment(FC, D);
660 }
661 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
662 while (IC->getSuperClass()) {
663 IC = IC->getSuperClass();
665 return cloneFullComment(FC, D);
666 }
667 }
668 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
669 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
671 return cloneFullComment(FC, D);
672 }
673 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
674 if (!(RD = RD->getDefinition()))
675 return nullptr;
676 // Check non-virtual bases.
677 for (const auto &I : RD->bases()) {
678 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
679 continue;
680 QualType Ty = I.getType();
681 if (Ty.isNull())
682 continue;
684 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
685 continue;
686
688 return cloneFullComment(FC, D);
689 }
690 }
691 // Check virtual bases.
692 for (const auto &I : RD->vbases()) {
693 if (I.getAccessSpecifier() != AS_public)
694 continue;
695 QualType Ty = I.getType();
696 if (Ty.isNull())
697 continue;
698 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
699 if (!(VirtualBase= VirtualBase->getDefinition()))
700 continue;
702 return cloneFullComment(FC, D);
703 }
704 }
705 }
706 return nullptr;
707 }
708
709 // If the RawComment was attached to other redeclaration of this Decl, we
710 // should parse the comment in context of that other Decl. This is important
711 // because comments can contain references to parameter names which can be
712 // different across redeclarations.
713 if (D != OriginalDecl && OriginalDecl)
714 return getCommentForDecl(OriginalDecl, PP);
715
716 comments::FullComment *FC = RC->parse(*this, PP, D);
717 ParsedComments[Canonical] = FC;
718 return FC;
719}
720
721void ASTContext::CanonicalTemplateTemplateParm::Profile(
722 llvm::FoldingSetNodeID &ID, const ASTContext &C,
724 ID.AddInteger(Parm->getDepth());
725 ID.AddInteger(Parm->getPosition());
726 ID.AddBoolean(Parm->isParameterPack());
727 ID.AddInteger(Parm->templateParameterKind());
728
730 ID.AddInteger(Params->size());
732 PEnd = Params->end();
733 P != PEnd; ++P) {
734 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
735 ID.AddInteger(0);
736 ID.AddBoolean(TTP->isParameterPack());
737 ID.AddInteger(
738 TTP->getNumExpansionParameters().toInternalRepresentation());
739 continue;
740 }
741
742 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
743 ID.AddInteger(1);
744 ID.AddBoolean(NTTP->isParameterPack());
745 ID.AddPointer(C.getUnconstrainedType(C.getCanonicalType(NTTP->getType()))
746 .getAsOpaquePtr());
747 if (NTTP->isExpandedParameterPack()) {
748 ID.AddBoolean(true);
749 ID.AddInteger(NTTP->getNumExpansionTypes());
750 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
751 QualType T = NTTP->getExpansionType(I);
752 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
753 }
754 } else
755 ID.AddBoolean(false);
756 continue;
757 }
758
759 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
760 ID.AddInteger(2);
761 Profile(ID, C, TTP);
762 }
763}
764
765TemplateTemplateParmDecl *
767 TemplateTemplateParmDecl *TTP) const {
768 // Check if we already have a canonical template template parameter.
769 llvm::FoldingSetNodeID ID;
770 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
771 void *InsertPos = nullptr;
772 CanonicalTemplateTemplateParm *Canonical
773 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
774 if (Canonical)
775 return Canonical->getParam();
776
777 // Build a canonical template parameter list.
779 SmallVector<NamedDecl *, 4> CanonParams;
780 CanonParams.reserve(Params->size());
782 PEnd = Params->end();
783 P != PEnd; ++P) {
784 // Note that, per C++20 [temp.over.link]/6, when determining whether
785 // template-parameters are equivalent, constraints are ignored.
786 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
789 TTP->getDepth(), TTP->getIndex(), nullptr, false,
790 TTP->isParameterPack(), /*HasTypeConstraint=*/false,
791 TTP->getNumExpansionParameters());
792 CanonParams.push_back(NewTTP);
793 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
797 if (NTTP->isExpandedParameterPack()) {
798 SmallVector<QualType, 2> ExpandedTypes;
800 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
801 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
802 ExpandedTInfos.push_back(
803 getTrivialTypeSourceInfo(ExpandedTypes.back()));
804 }
805
809 NTTP->getDepth(),
810 NTTP->getPosition(), nullptr,
811 T,
812 TInfo,
813 ExpandedTypes,
814 ExpandedTInfos);
815 } else {
819 NTTP->getDepth(),
820 NTTP->getPosition(), nullptr,
821 T,
822 NTTP->isParameterPack(),
823 TInfo);
824 }
825 CanonParams.push_back(Param);
826 } else
827 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
829 }
830
833 TTP->getPosition(), TTP->isParameterPack(), nullptr,
835 /*Typename=*/false,
837 CanonParams, SourceLocation(),
838 /*RequiresClause=*/nullptr));
839
840 // Get the new insert position for the node we care about.
841 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
842 assert(!Canonical && "Shouldn't be in the map!");
843 (void)Canonical;
844
845 // Create the canonical template template parameter entry.
846 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
847 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
848 return CanonTTP;
849}
850
853 TemplateTemplateParmDecl *TTP) const {
854 llvm::FoldingSetNodeID ID;
855 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
856 void *InsertPos = nullptr;
857 CanonicalTemplateTemplateParm *Canonical =
858 CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
859 return Canonical ? Canonical->getParam() : nullptr;
860}
861
864 TemplateTemplateParmDecl *CanonTTP) const {
865 llvm::FoldingSetNodeID ID;
866 CanonicalTemplateTemplateParm::Profile(ID, *this, CanonTTP);
867 void *InsertPos = nullptr;
868 if (auto *Existing =
869 CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos))
870 return Existing->getParam();
871 CanonTemplateTemplateParms.InsertNode(
872 new (*this) CanonicalTemplateTemplateParm(CanonTTP), InsertPos);
873 return CanonTTP;
874}
875
876/// Check if a type can have its sanitizer instrumentation elided based on its
877/// presence within an ignorelist.
879 const QualType &Ty) const {
880 std::string TyName = Ty.getUnqualifiedType().getAsString(getPrintingPolicy());
881 return NoSanitizeL->containsType(Mask, TyName);
882}
883
885 auto Kind = getTargetInfo().getCXXABI().getKind();
886 return getLangOpts().CXXABI.value_or(Kind);
887}
888
889CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
890 if (!LangOpts.CPlusPlus) return nullptr;
891
892 switch (getCXXABIKind()) {
893 case TargetCXXABI::AppleARM64:
894 case TargetCXXABI::Fuchsia:
895 case TargetCXXABI::GenericARM: // Same as Itanium at this level
896 case TargetCXXABI::iOS:
897 case TargetCXXABI::WatchOS:
898 case TargetCXXABI::GenericAArch64:
899 case TargetCXXABI::GenericMIPS:
900 case TargetCXXABI::GenericItanium:
901 case TargetCXXABI::WebAssembly:
902 case TargetCXXABI::XL:
903 return CreateItaniumCXXABI(*this);
904 case TargetCXXABI::Microsoft:
905 return CreateMicrosoftCXXABI(*this);
906 }
907 llvm_unreachable("Invalid CXXABI type!");
908}
909
911 if (!InterpContext) {
912 InterpContext.reset(new interp::Context(*this));
913 }
914 return *InterpContext;
915}
916
918 if (!ParentMapCtx)
919 ParentMapCtx.reset(new ParentMapContext(*this));
920 return *ParentMapCtx;
921}
922
924 const LangOptions &LangOpts) {
925 switch (LangOpts.getAddressSpaceMapMangling()) {
927 return TI.useAddressSpaceMapMangling();
929 return true;
931 return false;
932 }
933 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
934}
935
937 IdentifierTable &idents, SelectorTable &sels,
939 : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize),
940 DependentSizedArrayTypes(this_()), DependentSizedExtVectorTypes(this_()),
941 DependentAddressSpaceTypes(this_()), DependentVectorTypes(this_()),
942 DependentSizedMatrixTypes(this_()),
943 FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize),
944 DependentTypeOfExprTypes(this_()), DependentDecltypeTypes(this_()),
945 DependentPackIndexingTypes(this_()), TemplateSpecializationTypes(this_()),
946 DependentBitIntTypes(this_()), SubstTemplateTemplateParmPacks(this_()),
947 DeducedTemplates(this_()), ArrayParameterTypes(this_()),
948 CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
949 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
950 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
951 LangOpts.XRayNeverInstrumentFiles,
952 LangOpts.XRayAttrListFiles, SM)),
953 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
954 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
955 BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this),
956 Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
957 CompCategories(this_()), LastSDM(nullptr, 0) {
959}
960
962 // Release the DenseMaps associated with DeclContext objects.
963 // FIXME: Is this the ideal solution?
964 ReleaseDeclContextMaps();
965
966 // Call all of the deallocation functions on all of their targets.
967 for (auto &Pair : Deallocations)
968 (Pair.first)(Pair.second);
969 Deallocations.clear();
970
971 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
972 // because they can contain DenseMaps.
973 for (llvm::DenseMap<const ObjCInterfaceDecl *,
975 I = ObjCLayouts.begin(),
976 E = ObjCLayouts.end();
977 I != E;)
978 // Increment in loop to prevent using deallocated memory.
979 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
980 R->Destroy(*this);
981 ObjCLayouts.clear();
982
983 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
984 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
985 // Increment in loop to prevent using deallocated memory.
986 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
987 R->Destroy(*this);
988 }
989 ASTRecordLayouts.clear();
990
991 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
992 AEnd = DeclAttrs.end();
993 A != AEnd; ++A)
994 A->second->~AttrVec();
995 DeclAttrs.clear();
996
997 for (const auto &Value : ModuleInitializers)
998 Value.second->~PerModuleInitializers();
999 ModuleInitializers.clear();
1000}
1001
1003
1004void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
1005 TraversalScope = TopLevelDecls;
1007}
1008
1009void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
1010 Deallocations.push_back({Callback, Data});
1011}
1012
1013void
1017
1019 llvm::errs() << "\n*** AST Context Stats:\n";
1020 llvm::errs() << " " << Types.size() << " types total.\n";
1021
1022 unsigned counts[] = {
1023#define TYPE(Name, Parent) 0,
1024#define ABSTRACT_TYPE(Name, Parent)
1025#include "clang/AST/TypeNodes.inc"
1026 0 // Extra
1027 };
1028
1029 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1030 Type *T = Types[i];
1031 counts[(unsigned)T->getTypeClass()]++;
1032 }
1033
1034 unsigned Idx = 0;
1035 unsigned TotalBytes = 0;
1036#define TYPE(Name, Parent) \
1037 if (counts[Idx]) \
1038 llvm::errs() << " " << counts[Idx] << " " << #Name \
1039 << " types, " << sizeof(Name##Type) << " each " \
1040 << "(" << counts[Idx] * sizeof(Name##Type) \
1041 << " bytes)\n"; \
1042 TotalBytes += counts[Idx] * sizeof(Name##Type); \
1043 ++Idx;
1044#define ABSTRACT_TYPE(Name, Parent)
1045#include "clang/AST/TypeNodes.inc"
1046
1047 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
1048
1049 // Implicit special member functions.
1050 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1052 << " implicit default constructors created\n";
1053 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1055 << " implicit copy constructors created\n";
1056 if (getLangOpts().CPlusPlus)
1057 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1059 << " implicit move constructors created\n";
1060 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1062 << " implicit copy assignment operators created\n";
1063 if (getLangOpts().CPlusPlus)
1064 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1066 << " implicit move assignment operators created\n";
1067 llvm::errs() << NumImplicitDestructorsDeclared << "/"
1069 << " implicit destructors created\n";
1070
1071 if (ExternalSource) {
1072 llvm::errs() << "\n";
1073 ExternalSource->PrintStats();
1074 }
1075
1076 BumpAlloc.PrintStats();
1077}
1078
1080 bool NotifyListeners) {
1081 if (NotifyListeners)
1082 if (auto *Listener = getASTMutationListener();
1084 Listener->RedefinedHiddenDefinition(ND, M);
1085
1086 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
1087}
1088
1090 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1091 if (It == MergedDefModules.end())
1092 return;
1093
1094 auto &Merged = It->second;
1095 llvm::DenseSet<Module*> Found;
1096 for (Module *&M : Merged)
1097 if (!Found.insert(M).second)
1098 M = nullptr;
1099 llvm::erase(Merged, nullptr);
1100}
1101
1104 auto MergedIt =
1105 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
1106 if (MergedIt == MergedDefModules.end())
1107 return {};
1108 return MergedIt->second;
1109}
1110
1111void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1112 if (LazyInitializers.empty())
1113 return;
1114
1115 auto *Source = Ctx.getExternalSource();
1116 assert(Source && "lazy initializers but no external source");
1117
1118 auto LazyInits = std::move(LazyInitializers);
1119 LazyInitializers.clear();
1120
1121 for (auto ID : LazyInits)
1122 Initializers.push_back(Source->GetExternalDecl(ID));
1123
1124 assert(LazyInitializers.empty() &&
1125 "GetExternalDecl for lazy module initializer added more inits");
1126}
1127
1129 // One special case: if we add a module initializer that imports another
1130 // module, and that module's only initializer is an ImportDecl, simplify.
1131 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1132 auto It = ModuleInitializers.find(ID->getImportedModule());
1133
1134 // Maybe the ImportDecl does nothing at all. (Common case.)
1135 if (It == ModuleInitializers.end())
1136 return;
1137
1138 // Maybe the ImportDecl only imports another ImportDecl.
1139 auto &Imported = *It->second;
1140 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1141 Imported.resolve(*this);
1142 auto *OnlyDecl = Imported.Initializers.front();
1143 if (isa<ImportDecl>(OnlyDecl))
1144 D = OnlyDecl;
1145 }
1146 }
1147
1148 auto *&Inits = ModuleInitializers[M];
1149 if (!Inits)
1150 Inits = new (*this) PerModuleInitializers;
1151 Inits->Initializers.push_back(D);
1152}
1153
1156 auto *&Inits = ModuleInitializers[M];
1157 if (!Inits)
1158 Inits = new (*this) PerModuleInitializers;
1159 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1160 IDs.begin(), IDs.end());
1161}
1162
1164 auto It = ModuleInitializers.find(M);
1165 if (It == ModuleInitializers.end())
1166 return {};
1167
1168 auto *Inits = It->second;
1169 Inits->resolve(*this);
1170 return Inits->Initializers;
1171}
1172
1174 assert(M->isNamedModule());
1175 assert(!CurrentCXXNamedModule &&
1176 "We should set named module for ASTContext for only once");
1177 CurrentCXXNamedModule = M;
1178}
1179
1180bool ASTContext::isInSameModule(const Module *M1, const Module *M2) const {
1181 if (!M1 != !M2)
1182 return false;
1183
1184 /// Get the representative module for M. The representative module is the
1185 /// first module unit for a specific primary module name. So that the module
1186 /// units have the same representative module belongs to the same module.
1187 ///
1188 /// The process is helpful to reduce the expensive string operations.
1189 auto GetRepresentativeModule = [this](const Module *M) {
1190 auto Iter = SameModuleLookupSet.find(M);
1191 if (Iter != SameModuleLookupSet.end())
1192 return Iter->second;
1193
1194 const Module *RepresentativeModule =
1195 PrimaryModuleNameMap.try_emplace(M->getPrimaryModuleInterfaceName(), M)
1196 .first->second;
1197 SameModuleLookupSet[M] = RepresentativeModule;
1198 return RepresentativeModule;
1199 };
1200
1201 assert(M1 && "Shouldn't call `isInSameModule` if both M1 and M2 are none.");
1202 return GetRepresentativeModule(M1) == GetRepresentativeModule(M2);
1203}
1204
1206 if (!ExternCContext)
1207 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1208
1209 return ExternCContext;
1210}
1211
1222
1223#define BuiltinTemplate(BTName) \
1224 BuiltinTemplateDecl *ASTContext::get##BTName##Decl() const { \
1225 if (!Decl##BTName) \
1226 Decl##BTName = \
1227 buildBuiltinTemplateDecl(BTK##BTName, get##BTName##Name()); \
1228 return Decl##BTName; \
1229 }
1230#include "clang/Basic/BuiltinTemplates.inc"
1231
1233 RecordDecl::TagKind TK) const {
1234 SourceLocation Loc;
1235 RecordDecl *NewDecl;
1236 if (getLangOpts().CPlusPlus)
1237 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1238 Loc, &Idents.get(Name));
1239 else
1240 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1241 &Idents.get(Name));
1242 NewDecl->setImplicit();
1243 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1244 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1245 return NewDecl;
1246}
1247
1249 StringRef Name) const {
1252 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1253 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1254 NewDecl->setImplicit();
1255 return NewDecl;
1256}
1257
1259 if (!Int128Decl)
1260 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1261 return Int128Decl;
1262}
1263
1265 if (!UInt128Decl)
1266 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1267 return UInt128Decl;
1268}
1269
1270void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1271 auto *Ty = new (*this, alignof(BuiltinType)) BuiltinType(K);
1273 Types.push_back(Ty);
1274}
1275
1277 const TargetInfo *AuxTarget) {
1278 assert((!this->Target || this->Target == &Target) &&
1279 "Incorrect target reinitialization");
1280 assert(VoidTy.isNull() && "Context reinitialized?");
1281
1282 this->Target = &Target;
1283 this->AuxTarget = AuxTarget;
1284
1285 ABI.reset(createCXXABI(Target));
1286 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1287
1288 // C99 6.2.5p19.
1289 InitBuiltinType(VoidTy, BuiltinType::Void);
1290
1291 // C99 6.2.5p2.
1292 InitBuiltinType(BoolTy, BuiltinType::Bool);
1293 // C99 6.2.5p3.
1294 if (LangOpts.CharIsSigned)
1295 InitBuiltinType(CharTy, BuiltinType::Char_S);
1296 else
1297 InitBuiltinType(CharTy, BuiltinType::Char_U);
1298 // C99 6.2.5p4.
1299 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1300 InitBuiltinType(ShortTy, BuiltinType::Short);
1301 InitBuiltinType(IntTy, BuiltinType::Int);
1302 InitBuiltinType(LongTy, BuiltinType::Long);
1303 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1304
1305 // C99 6.2.5p6.
1306 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1307 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1308 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1309 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1310 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1311
1312 // C99 6.2.5p10.
1313 InitBuiltinType(FloatTy, BuiltinType::Float);
1314 InitBuiltinType(DoubleTy, BuiltinType::Double);
1315 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1316
1317 // GNU extension, __float128 for IEEE quadruple precision
1318 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1319
1320 // __ibm128 for IBM extended precision
1321 InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128);
1322
1323 // C11 extension ISO/IEC TS 18661-3
1324 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1325
1326 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1327 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1328 InitBuiltinType(AccumTy, BuiltinType::Accum);
1329 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1330 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1331 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1332 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1333 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1334 InitBuiltinType(FractTy, BuiltinType::Fract);
1335 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1336 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1337 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1338 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1339 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1340 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1341 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1342 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1343 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1344 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1345 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1346 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1347 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1348 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1349 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1350 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
1351
1352 // GNU extension, 128-bit integers.
1353 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1354 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1355
1356 // C++ 3.9.1p5
1357 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1358 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1359 else // -fshort-wchar makes wchar_t be unsigned.
1360 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1361 if (LangOpts.CPlusPlus && LangOpts.WChar)
1363 else {
1364 // C99 (or C++ using -fno-wchar).
1365 WideCharTy = getFromTargetType(Target.getWCharType());
1366 }
1367
1368 WIntTy = getFromTargetType(Target.getWIntType());
1369
1370 // C++20 (proposed)
1371 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1372
1373 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1374 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1375 else // C99
1376 Char16Ty = getFromTargetType(Target.getChar16Type());
1377
1378 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1379 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1380 else // C99
1381 Char32Ty = getFromTargetType(Target.getChar32Type());
1382
1383 // Placeholder type for type-dependent expressions whose type is
1384 // completely unknown. No code should ever check a type against
1385 // DependentTy and users should never see it; however, it is here to
1386 // help diagnose failures to properly check for type-dependent
1387 // expressions.
1388 InitBuiltinType(DependentTy, BuiltinType::Dependent);
1389
1390 // Placeholder type for functions.
1391 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1392
1393 // Placeholder type for bound members.
1394 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1395
1396 // Placeholder type for unresolved templates.
1397 InitBuiltinType(UnresolvedTemplateTy, BuiltinType::UnresolvedTemplate);
1398
1399 // Placeholder type for pseudo-objects.
1400 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1401
1402 // "any" type; useful for debugger-like clients.
1403 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1404
1405 // Placeholder type for unbridged ARC casts.
1406 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1407
1408 // Placeholder type for builtin functions.
1409 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1410
1411 // Placeholder type for OMP array sections.
1412 if (LangOpts.OpenMP) {
1413 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1414 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1415 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1416 }
1417 // Placeholder type for OpenACC array sections, if we are ALSO in OMP mode,
1418 // don't bother, as we're just using the same type as OMP.
1419 if (LangOpts.OpenACC && !LangOpts.OpenMP) {
1420 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1421 }
1422 if (LangOpts.MatrixTypes)
1423 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1424
1425 // Builtin types for 'id', 'Class', and 'SEL'.
1426 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1427 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1428 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1429
1430 if (LangOpts.OpenCL) {
1431#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1432 InitBuiltinType(SingletonId, BuiltinType::Id);
1433#include "clang/Basic/OpenCLImageTypes.def"
1434
1435 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1436 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1437 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1438 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1439 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1440
1441#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1442 InitBuiltinType(Id##Ty, BuiltinType::Id);
1443#include "clang/Basic/OpenCLExtensionTypes.def"
1444 }
1445
1446 if (LangOpts.HLSL) {
1447#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
1448 InitBuiltinType(SingletonId, BuiltinType::Id);
1449#include "clang/Basic/HLSLIntangibleTypes.def"
1450 }
1451
1452 if (Target.hasAArch64ACLETypes() ||
1453 (AuxTarget && AuxTarget->hasAArch64ACLETypes())) {
1454#define SVE_TYPE(Name, Id, SingletonId) \
1455 InitBuiltinType(SingletonId, BuiltinType::Id);
1456#include "clang/Basic/AArch64ACLETypes.def"
1457 }
1458
1459 if (Target.getTriple().isPPC64()) {
1460#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1461 InitBuiltinType(Id##Ty, BuiltinType::Id);
1462#include "clang/Basic/PPCTypes.def"
1463#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1464 InitBuiltinType(Id##Ty, BuiltinType::Id);
1465#include "clang/Basic/PPCTypes.def"
1466 }
1467
1468 if (Target.hasRISCVVTypes()) {
1469#define RVV_TYPE(Name, Id, SingletonId) \
1470 InitBuiltinType(SingletonId, BuiltinType::Id);
1471#include "clang/Basic/RISCVVTypes.def"
1472 }
1473
1474 if (Target.getTriple().isWasm() && Target.hasFeature("reference-types")) {
1475#define WASM_TYPE(Name, Id, SingletonId) \
1476 InitBuiltinType(SingletonId, BuiltinType::Id);
1477#include "clang/Basic/WebAssemblyReferenceTypes.def"
1478 }
1479
1480 if (Target.getTriple().isAMDGPU() ||
1481 (AuxTarget && AuxTarget->getTriple().isAMDGPU())) {
1482#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
1483 InitBuiltinType(SingletonId, BuiltinType::Id);
1484#include "clang/Basic/AMDGPUTypes.def"
1485 }
1486
1487 // Builtin type for __objc_yes and __objc_no
1488 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1490
1491 ObjCConstantStringType = QualType();
1492
1493 ObjCSuperType = QualType();
1494
1495 // void * type
1496 if (LangOpts.OpenCLGenericAddressSpace) {
1497 auto Q = VoidTy.getQualifiers();
1498 Q.setAddressSpace(LangAS::opencl_generic);
1500 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1501 } else {
1503 }
1504
1505 // nullptr type (C++0x 2.14.7)
1506 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1507
1508 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1509 InitBuiltinType(HalfTy, BuiltinType::Half);
1510
1511 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1512
1513 // Builtin type used to help define __builtin_va_list.
1514 VaListTagDecl = nullptr;
1515
1516 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1517 if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1520 }
1521}
1522
1524 return SourceMgr.getDiagnostics();
1525}
1526
1528 AttrVec *&Result = DeclAttrs[D];
1529 if (!Result) {
1530 void *Mem = Allocate(sizeof(AttrVec));
1531 Result = new (Mem) AttrVec;
1532 }
1533
1534 return *Result;
1535}
1536
1537/// Erase the attributes corresponding to the given declaration.
1539 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1540 if (Pos != DeclAttrs.end()) {
1541 Pos->second->~AttrVec();
1542 DeclAttrs.erase(Pos);
1543 }
1544}
1545
1546// FIXME: Remove ?
1549 assert(Var->isStaticDataMember() && "Not a static data member");
1551 .dyn_cast<MemberSpecializationInfo *>();
1552}
1553
1556 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1557 TemplateOrInstantiation.find(Var);
1558 if (Pos == TemplateOrInstantiation.end())
1559 return {};
1560
1561 return Pos->second;
1562}
1563
1564void
1567 SourceLocation PointOfInstantiation) {
1568 assert(Inst->isStaticDataMember() && "Not a static data member");
1569 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1571 Tmpl, TSK, PointOfInstantiation));
1572}
1573
1574void
1577 assert(!TemplateOrInstantiation[Inst] &&
1578 "Already noted what the variable was instantiated from");
1579 TemplateOrInstantiation[Inst] = TSI;
1580}
1581
1582NamedDecl *
1584 return InstantiatedFromUsingDecl.lookup(UUD);
1585}
1586
1587void
1589 assert((isa<UsingDecl>(Pattern) ||
1592 "pattern decl is not a using decl");
1593 assert((isa<UsingDecl>(Inst) ||
1596 "instantiation did not produce a using decl");
1597 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1598 InstantiatedFromUsingDecl[Inst] = Pattern;
1599}
1600
1603 return InstantiatedFromUsingEnumDecl.lookup(UUD);
1604}
1605
1607 UsingEnumDecl *Pattern) {
1608 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
1609 InstantiatedFromUsingEnumDecl[Inst] = Pattern;
1610}
1611
1614 return InstantiatedFromUsingShadowDecl.lookup(Inst);
1615}
1616
1617void
1619 UsingShadowDecl *Pattern) {
1620 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1621 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1622}
1623
1624FieldDecl *
1626 return InstantiatedFromUnnamedFieldDecl.lookup(Field);
1627}
1628
1630 FieldDecl *Tmpl) {
1631 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1632 "Instantiated field decl is not unnamed");
1633 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1634 "Template field decl is not unnamed");
1635 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1636 "Already noted what unnamed field was instantiated from");
1637
1638 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1639}
1640
1645
1650
1651unsigned
1653 auto Range = overridden_methods(Method);
1654 return Range.end() - Range.begin();
1655}
1656
1659 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1660 OverriddenMethods.find(Method->getCanonicalDecl());
1661 if (Pos == OverriddenMethods.end())
1662 return overridden_method_range(nullptr, nullptr);
1663 return overridden_method_range(Pos->second.begin(), Pos->second.end());
1664}
1665
1667 const CXXMethodDecl *Overridden) {
1668 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1669 OverriddenMethods[Method].push_back(Overridden);
1670}
1671
1673 const NamedDecl *D,
1674 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1675 assert(D);
1676
1677 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1678 Overridden.append(overridden_methods_begin(CXXMethod),
1679 overridden_methods_end(CXXMethod));
1680 return;
1681 }
1682
1683 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1684 if (!Method)
1685 return;
1686
1688 Method->getOverriddenMethods(OverDecls);
1689 Overridden.append(OverDecls.begin(), OverDecls.end());
1690}
1691
1692std::optional<ASTContext::CXXRecordDeclRelocationInfo>
1694 assert(RD);
1695 CXXRecordDecl *D = RD->getDefinition();
1696 auto it = RelocatableClasses.find(D);
1697 if (it != RelocatableClasses.end())
1698 return it->getSecond();
1699 return std::nullopt;
1700}
1701
1704 assert(RD);
1705 CXXRecordDecl *D = RD->getDefinition();
1706 assert(RelocatableClasses.find(D) == RelocatableClasses.end());
1707 RelocatableClasses.insert({D, Info});
1708}
1709
1711 const ASTContext &Context, const CXXRecordDecl *Class) {
1712 if (!Class->isPolymorphic())
1713 return false;
1714 const CXXRecordDecl *BaseType = Context.baseForVTableAuthentication(Class);
1715 using AuthAttr = VTablePointerAuthenticationAttr;
1716 const AuthAttr *ExplicitAuth = BaseType->getAttr<AuthAttr>();
1717 if (!ExplicitAuth)
1718 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1719 AuthAttr::AddressDiscriminationMode AddressDiscrimination =
1720 ExplicitAuth->getAddressDiscrimination();
1721 if (AddressDiscrimination == AuthAttr::DefaultAddressDiscrimination)
1722 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1723 return AddressDiscrimination == AuthAttr::AddressDiscrimination;
1724}
1725
1726ASTContext::PointerAuthContent
1727ASTContext::findPointerAuthContent(QualType T) const {
1728 assert(isPointerAuthenticationAvailable());
1729
1730 T = T.getCanonicalType();
1731 if (T.hasAddressDiscriminatedPointerAuth())
1732 return PointerAuthContent::AddressDiscriminatedData;
1733 const RecordDecl *RD = T->getAsRecordDecl();
1734 if (!RD)
1735 return PointerAuthContent::None;
1736
1737 if (auto Existing = RecordContainsAddressDiscriminatedPointerAuth.find(RD);
1738 Existing != RecordContainsAddressDiscriminatedPointerAuth.end())
1739 return Existing->second;
1740
1741 PointerAuthContent Result = PointerAuthContent::None;
1742
1743 auto SaveResultAndReturn = [&]() -> PointerAuthContent {
1744 auto [ResultIter, DidAdd] =
1745 RecordContainsAddressDiscriminatedPointerAuth.try_emplace(RD, Result);
1746 (void)ResultIter;
1747 (void)DidAdd;
1748 assert(DidAdd);
1749 return Result;
1750 };
1751 auto ShouldContinueAfterUpdate = [&](PointerAuthContent NewResult) {
1752 static_assert(PointerAuthContent::None <
1753 PointerAuthContent::AddressDiscriminatedVTable);
1754 static_assert(PointerAuthContent::AddressDiscriminatedVTable <
1755 PointerAuthContent::AddressDiscriminatedData);
1756 if (NewResult > Result)
1757 Result = NewResult;
1758 return Result != PointerAuthContent::AddressDiscriminatedData;
1759 };
1760 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1762 !ShouldContinueAfterUpdate(
1763 PointerAuthContent::AddressDiscriminatedVTable))
1764 return SaveResultAndReturn();
1765 for (auto Base : CXXRD->bases()) {
1766 if (!ShouldContinueAfterUpdate(findPointerAuthContent(Base.getType())))
1767 return SaveResultAndReturn();
1768 }
1769 }
1770 for (auto *FieldDecl : RD->fields()) {
1771 if (!ShouldContinueAfterUpdate(
1772 findPointerAuthContent(FieldDecl->getType())))
1773 return SaveResultAndReturn();
1774 }
1775 return SaveResultAndReturn();
1776}
1777
1779 assert(!Import->getNextLocalImport() &&
1780 "Import declaration already in the chain");
1781 assert(!Import->isFromASTFile() && "Non-local import declaration");
1782 if (!FirstLocalImport) {
1783 FirstLocalImport = Import;
1784 LastLocalImport = Import;
1785 return;
1786 }
1787
1788 LastLocalImport->setNextLocalImport(Import);
1789 LastLocalImport = Import;
1790}
1791
1792//===----------------------------------------------------------------------===//
1793// Type Sizing and Analysis
1794//===----------------------------------------------------------------------===//
1795
1796/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1797/// scalar floating point type.
1798const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1799 switch (T->castAs<BuiltinType>()->getKind()) {
1800 default:
1801 llvm_unreachable("Not a floating point type!");
1802 case BuiltinType::BFloat16:
1803 return Target->getBFloat16Format();
1804 case BuiltinType::Float16:
1805 return Target->getHalfFormat();
1806 case BuiltinType::Half:
1807 return Target->getHalfFormat();
1808 case BuiltinType::Float: return Target->getFloatFormat();
1809 case BuiltinType::Double: return Target->getDoubleFormat();
1810 case BuiltinType::Ibm128:
1811 return Target->getIbm128Format();
1812 case BuiltinType::LongDouble:
1813 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1814 return AuxTarget->getLongDoubleFormat();
1815 return Target->getLongDoubleFormat();
1816 case BuiltinType::Float128:
1817 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1818 return AuxTarget->getFloat128Format();
1819 return Target->getFloat128Format();
1820 }
1821}
1822
1823CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1824 unsigned Align = Target->getCharWidth();
1825
1826 const unsigned AlignFromAttr = D->getMaxAlignment();
1827 if (AlignFromAttr)
1828 Align = AlignFromAttr;
1829
1830 // __attribute__((aligned)) can increase or decrease alignment
1831 // *except* on a struct or struct member, where it only increases
1832 // alignment unless 'packed' is also specified.
1833 //
1834 // It is an error for alignas to decrease alignment, so we can
1835 // ignore that possibility; Sema should diagnose it.
1836 bool UseAlignAttrOnly;
1837 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D))
1838 UseAlignAttrOnly =
1839 FD->hasAttr<PackedAttr>() || FD->getParent()->hasAttr<PackedAttr>();
1840 else
1841 UseAlignAttrOnly = AlignFromAttr != 0;
1842 // If we're using the align attribute only, just ignore everything
1843 // else about the declaration and its type.
1844 if (UseAlignAttrOnly) {
1845 // do nothing
1846 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1847 QualType T = VD->getType();
1848 if (const auto *RT = T->getAs<ReferenceType>()) {
1849 if (ForAlignof)
1850 T = RT->getPointeeType();
1851 else
1852 T = getPointerType(RT->getPointeeType());
1853 }
1854 QualType BaseT = getBaseElementType(T);
1855 if (T->isFunctionType())
1856 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1857 else if (!BaseT->isIncompleteType()) {
1858 // Adjust alignments of declarations with array type by the
1859 // large-array alignment on the target.
1860 if (const ArrayType *arrayType = getAsArrayType(T)) {
1861 unsigned MinWidth = Target->getLargeArrayMinWidth();
1862 if (!ForAlignof && MinWidth) {
1864 Align = std::max(Align, Target->getLargeArrayAlign());
1867 Align = std::max(Align, Target->getLargeArrayAlign());
1868 }
1869 }
1870 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1871 if (BaseT.getQualifiers().hasUnaligned())
1872 Align = Target->getCharWidth();
1873 }
1874
1875 // Ensure minimum alignment for global variables.
1876 if (const auto *VD = dyn_cast<VarDecl>(D))
1877 if (VD->hasGlobalStorage() && !ForAlignof) {
1878 uint64_t TypeSize =
1879 !BaseT->isIncompleteType() ? getTypeSize(T.getTypePtr()) : 0;
1880 Align = std::max(Align, getMinGlobalAlignOfVar(TypeSize, VD));
1881 }
1882
1883 // Fields can be subject to extra alignment constraints, like if
1884 // the field is packed, the struct is packed, or the struct has a
1885 // a max-field-alignment constraint (#pragma pack). So calculate
1886 // the actual alignment of the field within the struct, and then
1887 // (as we're expected to) constrain that by the alignment of the type.
1888 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1889 const RecordDecl *Parent = Field->getParent();
1890 // We can only produce a sensible answer if the record is valid.
1891 if (!Parent->isInvalidDecl()) {
1892 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1893
1894 // Start with the record's overall alignment.
1895 unsigned FieldAlign = toBits(Layout.getAlignment());
1896
1897 // Use the GCD of that and the offset within the record.
1898 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1899 if (Offset > 0) {
1900 // Alignment is always a power of 2, so the GCD will be a power of 2,
1901 // which means we get to do this crazy thing instead of Euclid's.
1902 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1903 if (LowBitOfOffset < FieldAlign)
1904 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1905 }
1906
1907 Align = std::min(Align, FieldAlign);
1908 }
1909 }
1910 }
1911
1912 // Some targets have hard limitation on the maximum requestable alignment in
1913 // aligned attribute for static variables.
1914 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1915 const auto *VD = dyn_cast<VarDecl>(D);
1916 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1917 Align = std::min(Align, MaxAlignedAttr);
1918
1919 return toCharUnitsFromBits(Align);
1920}
1921
1923 return toCharUnitsFromBits(Target->getExnObjectAlignment());
1924}
1925
1926// getTypeInfoDataSizeInChars - Return the size of a type, in
1927// chars. If the type is a record, its data size is returned. This is
1928// the size of the memcpy that's performed when assigning this type
1929// using a trivial copy/move assignment operator.
1932
1933 // In C++, objects can sometimes be allocated into the tail padding
1934 // of a base-class subobject. We decide whether that's possible
1935 // during class layout, so here we can just trust the layout results.
1936 if (getLangOpts().CPlusPlus) {
1937 if (const auto *RD = T->getAsCXXRecordDecl(); RD && !RD->isInvalidDecl()) {
1938 const ASTRecordLayout &layout = getASTRecordLayout(RD);
1939 Info.Width = layout.getDataSize();
1940 }
1941 }
1942
1943 return Info;
1944}
1945
1946/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1947/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1950 const ConstantArrayType *CAT) {
1951 TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
1952 uint64_t Size = CAT->getZExtSize();
1953 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1954 (uint64_t)(-1)/Size) &&
1955 "Overflow in array type char size evaluation");
1956 uint64_t Width = EltInfo.Width.getQuantity() * Size;
1957 unsigned Align = EltInfo.Align.getQuantity();
1958 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1959 Context.getTargetInfo().getPointerWidth(LangAS::Default) == 64)
1960 Width = llvm::alignTo(Width, Align);
1963 EltInfo.AlignRequirement);
1964}
1965
1967 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1968 return getConstantArrayInfoInChars(*this, CAT);
1969 TypeInfo Info = getTypeInfo(T);
1972}
1973
1977
1979 // HLSL doesn't promote all small integer types to int, it
1980 // just uses the rank-based promotion rules for all types.
1981 if (getLangOpts().HLSL)
1982 return false;
1983
1984 if (const auto *BT = T->getAs<BuiltinType>())
1985 switch (BT->getKind()) {
1986 case BuiltinType::Bool:
1987 case BuiltinType::Char_S:
1988 case BuiltinType::Char_U:
1989 case BuiltinType::SChar:
1990 case BuiltinType::UChar:
1991 case BuiltinType::Short:
1992 case BuiltinType::UShort:
1993 case BuiltinType::WChar_S:
1994 case BuiltinType::WChar_U:
1995 case BuiltinType::Char8:
1996 case BuiltinType::Char16:
1997 case BuiltinType::Char32:
1998 return true;
1999 default:
2000 return false;
2001 }
2002
2003 // Enumerated types are promotable to their compatible integer types
2004 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
2005 if (const auto *ED = T->getAsEnumDecl()) {
2006 if (T->isDependentType() || ED->getPromotionType().isNull() ||
2007 ED->isScoped())
2008 return false;
2009
2010 return true;
2011 }
2012
2013 return false;
2014}
2015
2019
2021 return isAlignmentRequired(T.getTypePtr());
2022}
2023
2025 bool NeedsPreferredAlignment) const {
2026 // An alignment on a typedef overrides anything else.
2027 if (const auto *TT = T->getAs<TypedefType>())
2028 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2029 return Align;
2030
2031 // If we have an (array of) complete type, we're done.
2033 if (!T->isIncompleteType())
2034 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
2035
2036 // If we had an array type, its element type might be a typedef
2037 // type with an alignment attribute.
2038 if (const auto *TT = T->getAs<TypedefType>())
2039 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2040 return Align;
2041
2042 // Otherwise, see if the declaration of the type had an attribute.
2043 if (const auto *TD = T->getAsTagDecl())
2044 return TD->getMaxAlignment();
2045
2046 return 0;
2047}
2048
2050 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
2051 if (I != MemoizedTypeInfo.end())
2052 return I->second;
2053
2054 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
2055 TypeInfo TI = getTypeInfoImpl(T);
2056 MemoizedTypeInfo[T] = TI;
2057 return TI;
2058}
2059
2060/// getTypeInfoImpl - Return the size of the specified type, in bits. This
2061/// method does not work on incomplete types.
2062///
2063/// FIXME: Pointers into different addr spaces could have different sizes and
2064/// alignment requirements: getPointerInfo should take an AddrSpace, this
2065/// should take a QualType, &c.
2066TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
2067 uint64_t Width = 0;
2068 unsigned Align = 8;
2071 switch (T->getTypeClass()) {
2072#define TYPE(Class, Base)
2073#define ABSTRACT_TYPE(Class, Base)
2074#define NON_CANONICAL_TYPE(Class, Base)
2075#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2076#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
2077 case Type::Class: \
2078 assert(!T->isDependentType() && "should not see dependent types here"); \
2079 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
2080#include "clang/AST/TypeNodes.inc"
2081 llvm_unreachable("Should not see dependent types");
2082
2083 case Type::FunctionNoProto:
2084 case Type::FunctionProto:
2085 // GCC extension: alignof(function) = 32 bits
2086 Width = 0;
2087 Align = 32;
2088 break;
2089
2090 case Type::IncompleteArray:
2091 case Type::VariableArray:
2092 case Type::ConstantArray:
2093 case Type::ArrayParameter: {
2094 // Model non-constant sized arrays as size zero, but track the alignment.
2095 uint64_t Size = 0;
2096 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
2097 Size = CAT->getZExtSize();
2098
2099 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
2100 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
2101 "Overflow in array type bit size evaluation");
2102 Width = EltInfo.Width * Size;
2103 Align = EltInfo.Align;
2104 AlignRequirement = EltInfo.AlignRequirement;
2105 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
2106 getTargetInfo().getPointerWidth(LangAS::Default) == 64)
2107 Width = llvm::alignTo(Width, Align);
2108 break;
2109 }
2110
2111 case Type::ExtVector:
2112 case Type::Vector: {
2113 const auto *VT = cast<VectorType>(T);
2114 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
2115 Width = VT->isPackedVectorBoolType(*this)
2116 ? VT->getNumElements()
2117 : EltInfo.Width * VT->getNumElements();
2118 // Enforce at least byte size and alignment.
2119 Width = std::max<unsigned>(8, Width);
2120 Align = std::max<unsigned>(8, Width);
2121
2122 // If the alignment is not a power of 2, round up to the next power of 2.
2123 // This happens for non-power-of-2 length vectors.
2124 if (Align & (Align-1)) {
2125 Align = llvm::bit_ceil(Align);
2126 Width = llvm::alignTo(Width, Align);
2127 }
2128 // Adjust the alignment based on the target max.
2129 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
2130 if (TargetVectorAlign && TargetVectorAlign < Align)
2131 Align = TargetVectorAlign;
2132 if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
2133 // Adjust the alignment for fixed-length SVE vectors. This is important
2134 // for non-power-of-2 vector lengths.
2135 Align = 128;
2136 else if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
2137 // Adjust the alignment for fixed-length SVE predicates.
2138 Align = 16;
2139 else if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
2140 VT->getVectorKind() == VectorKind::RVVFixedLengthMask ||
2141 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
2142 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
2143 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4)
2144 // Adjust the alignment for fixed-length RVV vectors.
2145 Align = std::min<unsigned>(64, Width);
2146 break;
2147 }
2148
2149 case Type::ConstantMatrix: {
2150 const auto *MT = cast<ConstantMatrixType>(T);
2151 TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
2152 // The internal layout of a matrix value is implementation defined.
2153 // Initially be ABI compatible with arrays with respect to alignment and
2154 // size.
2155 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
2156 Align = ElementInfo.Align;
2157 break;
2158 }
2159
2160 case Type::Builtin:
2161 switch (cast<BuiltinType>(T)->getKind()) {
2162 default: llvm_unreachable("Unknown builtin type!");
2163 case BuiltinType::Void:
2164 // GCC extension: alignof(void) = 8 bits.
2165 Width = 0;
2166 Align = 8;
2167 break;
2168 case BuiltinType::Bool:
2169 Width = Target->getBoolWidth();
2170 Align = Target->getBoolAlign();
2171 break;
2172 case BuiltinType::Char_S:
2173 case BuiltinType::Char_U:
2174 case BuiltinType::UChar:
2175 case BuiltinType::SChar:
2176 case BuiltinType::Char8:
2177 Width = Target->getCharWidth();
2178 Align = Target->getCharAlign();
2179 break;
2180 case BuiltinType::WChar_S:
2181 case BuiltinType::WChar_U:
2182 Width = Target->getWCharWidth();
2183 Align = Target->getWCharAlign();
2184 break;
2185 case BuiltinType::Char16:
2186 Width = Target->getChar16Width();
2187 Align = Target->getChar16Align();
2188 break;
2189 case BuiltinType::Char32:
2190 Width = Target->getChar32Width();
2191 Align = Target->getChar32Align();
2192 break;
2193 case BuiltinType::UShort:
2194 case BuiltinType::Short:
2195 Width = Target->getShortWidth();
2196 Align = Target->getShortAlign();
2197 break;
2198 case BuiltinType::UInt:
2199 case BuiltinType::Int:
2200 Width = Target->getIntWidth();
2201 Align = Target->getIntAlign();
2202 break;
2203 case BuiltinType::ULong:
2204 case BuiltinType::Long:
2205 Width = Target->getLongWidth();
2206 Align = Target->getLongAlign();
2207 break;
2208 case BuiltinType::ULongLong:
2209 case BuiltinType::LongLong:
2210 Width = Target->getLongLongWidth();
2211 Align = Target->getLongLongAlign();
2212 break;
2213 case BuiltinType::Int128:
2214 case BuiltinType::UInt128:
2215 Width = 128;
2216 Align = Target->getInt128Align();
2217 break;
2218 case BuiltinType::ShortAccum:
2219 case BuiltinType::UShortAccum:
2220 case BuiltinType::SatShortAccum:
2221 case BuiltinType::SatUShortAccum:
2222 Width = Target->getShortAccumWidth();
2223 Align = Target->getShortAccumAlign();
2224 break;
2225 case BuiltinType::Accum:
2226 case BuiltinType::UAccum:
2227 case BuiltinType::SatAccum:
2228 case BuiltinType::SatUAccum:
2229 Width = Target->getAccumWidth();
2230 Align = Target->getAccumAlign();
2231 break;
2232 case BuiltinType::LongAccum:
2233 case BuiltinType::ULongAccum:
2234 case BuiltinType::SatLongAccum:
2235 case BuiltinType::SatULongAccum:
2236 Width = Target->getLongAccumWidth();
2237 Align = Target->getLongAccumAlign();
2238 break;
2239 case BuiltinType::ShortFract:
2240 case BuiltinType::UShortFract:
2241 case BuiltinType::SatShortFract:
2242 case BuiltinType::SatUShortFract:
2243 Width = Target->getShortFractWidth();
2244 Align = Target->getShortFractAlign();
2245 break;
2246 case BuiltinType::Fract:
2247 case BuiltinType::UFract:
2248 case BuiltinType::SatFract:
2249 case BuiltinType::SatUFract:
2250 Width = Target->getFractWidth();
2251 Align = Target->getFractAlign();
2252 break;
2253 case BuiltinType::LongFract:
2254 case BuiltinType::ULongFract:
2255 case BuiltinType::SatLongFract:
2256 case BuiltinType::SatULongFract:
2257 Width = Target->getLongFractWidth();
2258 Align = Target->getLongFractAlign();
2259 break;
2260 case BuiltinType::BFloat16:
2261 if (Target->hasBFloat16Type()) {
2262 Width = Target->getBFloat16Width();
2263 Align = Target->getBFloat16Align();
2264 } else if ((getLangOpts().SYCLIsDevice ||
2265 (getLangOpts().OpenMP &&
2266 getLangOpts().OpenMPIsTargetDevice)) &&
2267 AuxTarget->hasBFloat16Type()) {
2268 Width = AuxTarget->getBFloat16Width();
2269 Align = AuxTarget->getBFloat16Align();
2270 }
2271 break;
2272 case BuiltinType::Float16:
2273 case BuiltinType::Half:
2274 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2275 !getLangOpts().OpenMPIsTargetDevice) {
2276 Width = Target->getHalfWidth();
2277 Align = Target->getHalfAlign();
2278 } else {
2279 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2280 "Expected OpenMP device compilation.");
2281 Width = AuxTarget->getHalfWidth();
2282 Align = AuxTarget->getHalfAlign();
2283 }
2284 break;
2285 case BuiltinType::Float:
2286 Width = Target->getFloatWidth();
2287 Align = Target->getFloatAlign();
2288 break;
2289 case BuiltinType::Double:
2290 Width = Target->getDoubleWidth();
2291 Align = Target->getDoubleAlign();
2292 break;
2293 case BuiltinType::Ibm128:
2294 Width = Target->getIbm128Width();
2295 Align = Target->getIbm128Align();
2296 break;
2297 case BuiltinType::LongDouble:
2298 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2299 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2300 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2301 Width = AuxTarget->getLongDoubleWidth();
2302 Align = AuxTarget->getLongDoubleAlign();
2303 } else {
2304 Width = Target->getLongDoubleWidth();
2305 Align = Target->getLongDoubleAlign();
2306 }
2307 break;
2308 case BuiltinType::Float128:
2309 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2310 !getLangOpts().OpenMPIsTargetDevice) {
2311 Width = Target->getFloat128Width();
2312 Align = Target->getFloat128Align();
2313 } else {
2314 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2315 "Expected OpenMP device compilation.");
2316 Width = AuxTarget->getFloat128Width();
2317 Align = AuxTarget->getFloat128Align();
2318 }
2319 break;
2320 case BuiltinType::NullPtr:
2321 // C++ 3.9.1p11: sizeof(nullptr_t) == sizeof(void*)
2322 Width = Target->getPointerWidth(LangAS::Default);
2323 Align = Target->getPointerAlign(LangAS::Default);
2324 break;
2325 case BuiltinType::ObjCId:
2326 case BuiltinType::ObjCClass:
2327 case BuiltinType::ObjCSel:
2328 Width = Target->getPointerWidth(LangAS::Default);
2329 Align = Target->getPointerAlign(LangAS::Default);
2330 break;
2331 case BuiltinType::OCLSampler:
2332 case BuiltinType::OCLEvent:
2333 case BuiltinType::OCLClkEvent:
2334 case BuiltinType::OCLQueue:
2335 case BuiltinType::OCLReserveID:
2336#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2337 case BuiltinType::Id:
2338#include "clang/Basic/OpenCLImageTypes.def"
2339#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2340 case BuiltinType::Id:
2341#include "clang/Basic/OpenCLExtensionTypes.def"
2342 AS = Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
2343 Width = Target->getPointerWidth(AS);
2344 Align = Target->getPointerAlign(AS);
2345 break;
2346 // The SVE types are effectively target-specific. The length of an
2347 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2348 // of 128 bits. There is one predicate bit for each vector byte, so the
2349 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2350 //
2351 // Because the length is only known at runtime, we use a dummy value
2352 // of 0 for the static length. The alignment values are those defined
2353 // by the Procedure Call Standard for the Arm Architecture.
2354#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
2355 case BuiltinType::Id: \
2356 Width = 0; \
2357 Align = 128; \
2358 break;
2359#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
2360 case BuiltinType::Id: \
2361 Width = 0; \
2362 Align = 16; \
2363 break;
2364#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId) \
2365 case BuiltinType::Id: \
2366 Width = 0; \
2367 Align = 16; \
2368 break;
2369#define SVE_SCALAR_TYPE(Name, MangledName, Id, SingletonId, Bits) \
2370 case BuiltinType::Id: \
2371 Width = Bits; \
2372 Align = Bits; \
2373 break;
2374#include "clang/Basic/AArch64ACLETypes.def"
2375#define PPC_VECTOR_TYPE(Name, Id, Size) \
2376 case BuiltinType::Id: \
2377 Width = Size; \
2378 Align = Size; \
2379 break;
2380#include "clang/Basic/PPCTypes.def"
2381#define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \
2382 IsFP, IsBF) \
2383 case BuiltinType::Id: \
2384 Width = 0; \
2385 Align = ElBits; \
2386 break;
2387#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2388 case BuiltinType::Id: \
2389 Width = 0; \
2390 Align = 8; \
2391 break;
2392#include "clang/Basic/RISCVVTypes.def"
2393#define WASM_TYPE(Name, Id, SingletonId) \
2394 case BuiltinType::Id: \
2395 Width = 0; \
2396 Align = 8; \
2397 break;
2398#include "clang/Basic/WebAssemblyReferenceTypes.def"
2399#define AMDGPU_TYPE(NAME, ID, SINGLETONID, WIDTH, ALIGN) \
2400 case BuiltinType::ID: \
2401 Width = WIDTH; \
2402 Align = ALIGN; \
2403 break;
2404#include "clang/Basic/AMDGPUTypes.def"
2405#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2406#include "clang/Basic/HLSLIntangibleTypes.def"
2407 Width = Target->getPointerWidth(LangAS::Default);
2408 Align = Target->getPointerAlign(LangAS::Default);
2409 break;
2410 }
2411 break;
2412 case Type::ObjCObjectPointer:
2413 Width = Target->getPointerWidth(LangAS::Default);
2414 Align = Target->getPointerAlign(LangAS::Default);
2415 break;
2416 case Type::BlockPointer:
2417 AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
2418 Width = Target->getPointerWidth(AS);
2419 Align = Target->getPointerAlign(AS);
2420 break;
2421 case Type::LValueReference:
2422 case Type::RValueReference:
2423 // alignof and sizeof should never enter this code path here, so we go
2424 // the pointer route.
2425 AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
2426 Width = Target->getPointerWidth(AS);
2427 Align = Target->getPointerAlign(AS);
2428 break;
2429 case Type::Pointer:
2430 AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
2431 Width = Target->getPointerWidth(AS);
2432 Align = Target->getPointerAlign(AS);
2433 break;
2434 case Type::MemberPointer: {
2435 const auto *MPT = cast<MemberPointerType>(T);
2436 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2437 Width = MPI.Width;
2438 Align = MPI.Align;
2439 break;
2440 }
2441 case Type::Complex: {
2442 // Complex types have the same alignment as their elements, but twice the
2443 // size.
2444 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2445 Width = EltInfo.Width * 2;
2446 Align = EltInfo.Align;
2447 break;
2448 }
2449 case Type::ObjCObject:
2450 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2451 case Type::Adjusted:
2452 case Type::Decayed:
2453 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2454 case Type::ObjCInterface: {
2455 const auto *ObjCI = cast<ObjCInterfaceType>(T);
2456 if (ObjCI->getDecl()->isInvalidDecl()) {
2457 Width = 8;
2458 Align = 8;
2459 break;
2460 }
2461 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2462 Width = toBits(Layout.getSize());
2463 Align = toBits(Layout.getAlignment());
2464 break;
2465 }
2466 case Type::BitInt: {
2467 const auto *EIT = cast<BitIntType>(T);
2468 Align = Target->getBitIntAlign(EIT->getNumBits());
2469 Width = Target->getBitIntWidth(EIT->getNumBits());
2470 break;
2471 }
2472 case Type::Record:
2473 case Type::Enum: {
2474 const auto *TT = cast<TagType>(T);
2475 const TagDecl *TD = TT->getOriginalDecl()->getDefinitionOrSelf();
2476
2477 if (TD->isInvalidDecl()) {
2478 Width = 8;
2479 Align = 8;
2480 break;
2481 }
2482
2483 if (isa<EnumType>(TT)) {
2484 const EnumDecl *ED = cast<EnumDecl>(TD);
2485 TypeInfo Info =
2487 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2488 Info.Align = AttrAlign;
2490 }
2491 return Info;
2492 }
2493
2494 const auto *RD = cast<RecordDecl>(TD);
2495 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2496 Width = toBits(Layout.getSize());
2497 Align = toBits(Layout.getAlignment());
2498 AlignRequirement = RD->hasAttr<AlignedAttr>()
2500 : AlignRequirementKind::None;
2501 break;
2502 }
2503
2504 case Type::SubstTemplateTypeParm:
2506 getReplacementType().getTypePtr());
2507
2508 case Type::Auto:
2509 case Type::DeducedTemplateSpecialization: {
2510 const auto *A = cast<DeducedType>(T);
2511 assert(!A->getDeducedType().isNull() &&
2512 "cannot request the size of an undeduced or dependent auto type");
2513 return getTypeInfo(A->getDeducedType().getTypePtr());
2514 }
2515
2516 case Type::Paren:
2517 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2518
2519 case Type::MacroQualified:
2520 return getTypeInfo(
2522
2523 case Type::ObjCTypeParam:
2524 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2525
2526 case Type::Using:
2527 return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr());
2528
2529 case Type::Typedef: {
2530 const auto *TT = cast<TypedefType>(T);
2531 TypeInfo Info = getTypeInfo(TT->desugar().getTypePtr());
2532 // If the typedef has an aligned attribute on it, it overrides any computed
2533 // alignment we have. This violates the GCC documentation (which says that
2534 // attribute(aligned) can only round up) but matches its implementation.
2535 if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) {
2536 Align = AttrAlign;
2537 AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2538 } else {
2539 Align = Info.Align;
2540 AlignRequirement = Info.AlignRequirement;
2541 }
2542 Width = Info.Width;
2543 break;
2544 }
2545
2546 case Type::Attributed:
2547 return getTypeInfo(
2548 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2549
2550 case Type::CountAttributed:
2551 return getTypeInfo(cast<CountAttributedType>(T)->desugar().getTypePtr());
2552
2553 case Type::BTFTagAttributed:
2554 return getTypeInfo(
2555 cast<BTFTagAttributedType>(T)->getWrappedType().getTypePtr());
2556
2557 case Type::HLSLAttributedResource:
2558 return getTypeInfo(
2559 cast<HLSLAttributedResourceType>(T)->getWrappedType().getTypePtr());
2560
2561 case Type::HLSLInlineSpirv: {
2562 const auto *ST = cast<HLSLInlineSpirvType>(T);
2563 // Size is specified in bytes, convert to bits
2564 Width = ST->getSize() * 8;
2565 Align = ST->getAlignment();
2566 if (Width == 0 && Align == 0) {
2567 // We are defaulting to laying out opaque SPIR-V types as 32-bit ints.
2568 Width = 32;
2569 Align = 32;
2570 }
2571 break;
2572 }
2573
2574 case Type::Atomic: {
2575 // Start with the base type information.
2576 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2577 Width = Info.Width;
2578 Align = Info.Align;
2579
2580 if (!Width) {
2581 // An otherwise zero-sized type should still generate an
2582 // atomic operation.
2583 Width = Target->getCharWidth();
2584 assert(Align);
2585 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2586 // If the size of the type doesn't exceed the platform's max
2587 // atomic promotion width, make the size and alignment more
2588 // favorable to atomic operations:
2589
2590 // Round the size up to a power of 2.
2591 Width = llvm::bit_ceil(Width);
2592
2593 // Set the alignment equal to the size.
2594 Align = static_cast<unsigned>(Width);
2595 }
2596 }
2597 break;
2598
2599 case Type::PredefinedSugar:
2600 return getTypeInfo(cast<PredefinedSugarType>(T)->desugar().getTypePtr());
2601
2602 case Type::Pipe:
2603 Width = Target->getPointerWidth(LangAS::opencl_global);
2604 Align = Target->getPointerAlign(LangAS::opencl_global);
2605 break;
2606 }
2607
2608 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2609 return TypeInfo(Width, Align, AlignRequirement);
2610}
2611
2613 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2614 if (I != MemoizedUnadjustedAlign.end())
2615 return I->second;
2616
2617 unsigned UnadjustedAlign;
2618 if (const auto *RT = T->getAsCanonical<RecordType>()) {
2619 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getOriginalDecl());
2620 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2621 } else if (const auto *ObjCI = T->getAsCanonical<ObjCInterfaceType>()) {
2622 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2623 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2624 } else {
2625 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2626 }
2627
2628 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2629 return UnadjustedAlign;
2630}
2631
2633 unsigned SimdAlign = llvm::OpenMPIRBuilder::getOpenMPDefaultSimdAlign(
2634 getTargetInfo().getTriple(), Target->getTargetOpts().FeatureMap);
2635 return SimdAlign;
2636}
2637
2638/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2640 return CharUnits::fromQuantity(BitSize / getCharWidth());
2641}
2642
2643/// toBits - Convert a size in characters to a size in characters.
2644int64_t ASTContext::toBits(CharUnits CharSize) const {
2645 return CharSize.getQuantity() * getCharWidth();
2646}
2647
2648/// getTypeSizeInChars - Return the size of the specified type, in characters.
2649/// This method does not work on incomplete types.
2656
2657/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2658/// characters. This method does not work on incomplete types.
2665
2666/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2667/// type, in characters, before alignment adjustments. This method does
2668/// not work on incomplete types.
2675
2676/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2677/// type for the current target in bits. This can be different than the ABI
2678/// alignment in cases where it is beneficial for performance or backwards
2679/// compatibility preserving to overalign a data type. (Note: despite the name,
2680/// the preferred alignment is ABI-impacting, and not an optimization.)
2682 TypeInfo TI = getTypeInfo(T);
2683 unsigned ABIAlign = TI.Align;
2684
2685 T = T->getBaseElementTypeUnsafe();
2686
2687 // The preferred alignment of member pointers is that of a pointer.
2688 if (T->isMemberPointerType())
2689 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2690
2691 if (!Target->allowsLargerPreferedTypeAlignment())
2692 return ABIAlign;
2693
2694 if (const auto *RD = T->getAsRecordDecl()) {
2695 // When used as part of a typedef, or together with a 'packed' attribute,
2696 // the 'aligned' attribute can be used to decrease alignment. Note that the
2697 // 'packed' case is already taken into consideration when computing the
2698 // alignment, we only need to handle the typedef case here.
2700 RD->isInvalidDecl())
2701 return ABIAlign;
2702
2703 unsigned PreferredAlign = static_cast<unsigned>(
2704 toBits(getASTRecordLayout(RD).PreferredAlignment));
2705 assert(PreferredAlign >= ABIAlign &&
2706 "PreferredAlign should be at least as large as ABIAlign.");
2707 return PreferredAlign;
2708 }
2709
2710 // Double (and, for targets supporting AIX `power` alignment, long double) and
2711 // long long should be naturally aligned (despite requiring less alignment) if
2712 // possible.
2713 if (const auto *CT = T->getAs<ComplexType>())
2714 T = CT->getElementType().getTypePtr();
2715 if (const auto *ED = T->getAsEnumDecl())
2716 T = ED->getIntegerType().getTypePtr();
2717 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2718 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2719 T->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2720 (T->isSpecificBuiltinType(BuiltinType::LongDouble) &&
2721 Target->defaultsToAIXPowerAlignment()))
2722 // Don't increase the alignment if an alignment attribute was specified on a
2723 // typedef declaration.
2724 if (!TI.isAlignRequired())
2725 return std::max(ABIAlign, (unsigned)getTypeSize(T));
2726
2727 return ABIAlign;
2728}
2729
2730/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2731/// for __attribute__((aligned)) on this target, to be used if no alignment
2732/// value is specified.
2736
2737/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2738/// to a global variable of the specified type.
2740 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2741 return std::max(getPreferredTypeAlign(T),
2742 getMinGlobalAlignOfVar(TypeSize, VD));
2743}
2744
2745/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2746/// should be given to a global variable of the specified type.
2751
2753 const VarDecl *VD) const {
2754 // Make the default handling as that of a non-weak definition in the
2755 // current translation unit.
2756 bool HasNonWeakDef = !VD || (VD->hasDefinition() && !VD->isWeak());
2757 return getTargetInfo().getMinGlobalAlign(Size, HasNonWeakDef);
2758}
2759
2761 CharUnits Offset = CharUnits::Zero();
2762 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2763 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2764 Offset += Layout->getBaseClassOffset(Base);
2765 Layout = &getASTRecordLayout(Base);
2766 }
2767 return Offset;
2768}
2769
2771 const ValueDecl *MPD = MP.getMemberPointerDecl();
2774 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2776 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2777 const CXXRecordDecl *Base = RD;
2778 const CXXRecordDecl *Derived = Path[I];
2779 if (DerivedMember)
2780 std::swap(Base, Derived);
2782 RD = Path[I];
2783 }
2784 if (DerivedMember)
2786 return ThisAdjustment;
2787}
2788
2789/// DeepCollectObjCIvars -
2790/// This routine first collects all declared, but not synthesized, ivars in
2791/// super class and then collects all ivars, including those synthesized for
2792/// current class. This routine is used for implementation of current class
2793/// when all ivars, declared and synthesized are known.
2795 bool leafClass,
2797 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2798 DeepCollectObjCIvars(SuperClass, false, Ivars);
2799 if (!leafClass) {
2800 llvm::append_range(Ivars, OI->ivars());
2801 } else {
2802 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2803 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2804 Iv= Iv->getNextIvar())
2805 Ivars.push_back(Iv);
2806 }
2807}
2808
2809/// CollectInheritedProtocols - Collect all protocols in current class and
2810/// those inherited by it.
2813 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2814 // We can use protocol_iterator here instead of
2815 // all_referenced_protocol_iterator since we are walking all categories.
2816 for (auto *Proto : OI->all_referenced_protocols()) {
2817 CollectInheritedProtocols(Proto, Protocols);
2818 }
2819
2820 // Categories of this Interface.
2821 for (const auto *Cat : OI->visible_categories())
2822 CollectInheritedProtocols(Cat, Protocols);
2823
2824 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2825 while (SD) {
2826 CollectInheritedProtocols(SD, Protocols);
2827 SD = SD->getSuperClass();
2828 }
2829 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2830 for (auto *Proto : OC->protocols()) {
2831 CollectInheritedProtocols(Proto, Protocols);
2832 }
2833 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2834 // Insert the protocol.
2835 if (!Protocols.insert(
2836 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2837 return;
2838
2839 for (auto *Proto : OP->protocols())
2840 CollectInheritedProtocols(Proto, Protocols);
2841 }
2842}
2843
2845 const RecordDecl *RD,
2846 bool CheckIfTriviallyCopyable) {
2847 assert(RD->isUnion() && "Must be union type");
2848 CharUnits UnionSize =
2849 Context.getTypeSizeInChars(Context.getCanonicalTagType(RD));
2850
2851 for (const auto *Field : RD->fields()) {
2852 if (!Context.hasUniqueObjectRepresentations(Field->getType(),
2853 CheckIfTriviallyCopyable))
2854 return false;
2855 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2856 if (FieldSize != UnionSize)
2857 return false;
2858 }
2859 return !RD->field_empty();
2860}
2861
2862static int64_t getSubobjectOffset(const FieldDecl *Field,
2863 const ASTContext &Context,
2864 const clang::ASTRecordLayout & /*Layout*/) {
2865 return Context.getFieldOffset(Field);
2866}
2867
2868static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
2869 const ASTContext &Context,
2870 const clang::ASTRecordLayout &Layout) {
2871 return Context.toBits(Layout.getBaseClassOffset(RD));
2872}
2873
2874static std::optional<int64_t>
2876 const RecordDecl *RD,
2877 bool CheckIfTriviallyCopyable);
2878
2879static std::optional<int64_t>
2880getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context,
2881 bool CheckIfTriviallyCopyable) {
2882 if (const auto *RD = Field->getType()->getAsRecordDecl();
2883 RD && !RD->isUnion())
2884 return structHasUniqueObjectRepresentations(Context, RD,
2885 CheckIfTriviallyCopyable);
2886
2887 // A _BitInt type may not be unique if it has padding bits
2888 // but if it is a bitfield the padding bits are not used.
2889 bool IsBitIntType = Field->getType()->isBitIntType();
2890 if (!Field->getType()->isReferenceType() && !IsBitIntType &&
2891 !Context.hasUniqueObjectRepresentations(Field->getType(),
2892 CheckIfTriviallyCopyable))
2893 return std::nullopt;
2894
2895 int64_t FieldSizeInBits =
2896 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2897 if (Field->isBitField()) {
2898 // If we have explicit padding bits, they don't contribute bits
2899 // to the actual object representation, so return 0.
2900 if (Field->isUnnamedBitField())
2901 return 0;
2902
2903 int64_t BitfieldSize = Field->getBitWidthValue();
2904 if (IsBitIntType) {
2905 if ((unsigned)BitfieldSize >
2906 cast<BitIntType>(Field->getType())->getNumBits())
2907 return std::nullopt;
2908 } else if (BitfieldSize > FieldSizeInBits) {
2909 return std::nullopt;
2910 }
2911 FieldSizeInBits = BitfieldSize;
2912 } else if (IsBitIntType && !Context.hasUniqueObjectRepresentations(
2913 Field->getType(), CheckIfTriviallyCopyable)) {
2914 return std::nullopt;
2915 }
2916 return FieldSizeInBits;
2917}
2918
2919static std::optional<int64_t>
2921 bool CheckIfTriviallyCopyable) {
2922 return structHasUniqueObjectRepresentations(Context, RD,
2923 CheckIfTriviallyCopyable);
2924}
2925
2926template <typename RangeT>
2928 const RangeT &Subobjects, int64_t CurOffsetInBits,
2929 const ASTContext &Context, const clang::ASTRecordLayout &Layout,
2930 bool CheckIfTriviallyCopyable) {
2931 for (const auto *Subobject : Subobjects) {
2932 std::optional<int64_t> SizeInBits =
2933 getSubobjectSizeInBits(Subobject, Context, CheckIfTriviallyCopyable);
2934 if (!SizeInBits)
2935 return std::nullopt;
2936 if (*SizeInBits != 0) {
2937 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
2938 if (Offset != CurOffsetInBits)
2939 return std::nullopt;
2940 CurOffsetInBits += *SizeInBits;
2941 }
2942 }
2943 return CurOffsetInBits;
2944}
2945
2946static std::optional<int64_t>
2948 const RecordDecl *RD,
2949 bool CheckIfTriviallyCopyable) {
2950 assert(!RD->isUnion() && "Must be struct/class type");
2951 const auto &Layout = Context.getASTRecordLayout(RD);
2952
2953 int64_t CurOffsetInBits = 0;
2954 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2955 if (ClassDecl->isDynamicClass())
2956 return std::nullopt;
2957
2959 for (const auto &Base : ClassDecl->bases()) {
2960 // Empty types can be inherited from, and non-empty types can potentially
2961 // have tail padding, so just make sure there isn't an error.
2962 Bases.emplace_back(Base.getType()->getAsCXXRecordDecl());
2963 }
2964
2965 llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
2966 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
2967 });
2968
2969 std::optional<int64_t> OffsetAfterBases =
2971 Bases, CurOffsetInBits, Context, Layout, CheckIfTriviallyCopyable);
2972 if (!OffsetAfterBases)
2973 return std::nullopt;
2974 CurOffsetInBits = *OffsetAfterBases;
2975 }
2976
2977 std::optional<int64_t> OffsetAfterFields =
2979 RD->fields(), CurOffsetInBits, Context, Layout,
2980 CheckIfTriviallyCopyable);
2981 if (!OffsetAfterFields)
2982 return std::nullopt;
2983 CurOffsetInBits = *OffsetAfterFields;
2984
2985 return CurOffsetInBits;
2986}
2987
2989 QualType Ty, bool CheckIfTriviallyCopyable) const {
2990 // C++17 [meta.unary.prop]:
2991 // The predicate condition for a template specialization
2992 // has_unique_object_representations<T> shall be satisfied if and only if:
2993 // (9.1) - T is trivially copyable, and
2994 // (9.2) - any two objects of type T with the same value have the same
2995 // object representation, where:
2996 // - two objects of array or non-union class type are considered to have
2997 // the same value if their respective sequences of direct subobjects
2998 // have the same values, and
2999 // - two objects of union type are considered to have the same value if
3000 // they have the same active member and the corresponding members have
3001 // the same value.
3002 // The set of scalar types for which this condition holds is
3003 // implementation-defined. [ Note: If a type has padding bits, the condition
3004 // does not hold; otherwise, the condition holds true for unsigned integral
3005 // types. -- end note ]
3006 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
3007
3008 // Arrays are unique only if their element type is unique.
3009 if (Ty->isArrayType())
3011 CheckIfTriviallyCopyable);
3012
3013 assert((Ty->isVoidType() || !Ty->isIncompleteType()) &&
3014 "hasUniqueObjectRepresentations should not be called with an "
3015 "incomplete type");
3016
3017 // (9.1) - T is trivially copyable...
3018 if (CheckIfTriviallyCopyable && !Ty.isTriviallyCopyableType(*this))
3019 return false;
3020
3021 // All integrals and enums are unique.
3022 if (Ty->isIntegralOrEnumerationType()) {
3023 // Address discriminated integer types are not unique.
3025 return false;
3026 // Except _BitInt types that have padding bits.
3027 if (const auto *BIT = Ty->getAs<BitIntType>())
3028 return getTypeSize(BIT) == BIT->getNumBits();
3029
3030 return true;
3031 }
3032
3033 // All other pointers are unique.
3034 if (Ty->isPointerType())
3036
3037 if (const auto *MPT = Ty->getAs<MemberPointerType>())
3038 return !ABI->getMemberPointerInfo(MPT).HasPadding;
3039
3040 if (const auto *Record = Ty->getAsRecordDecl()) {
3041 if (Record->isInvalidDecl())
3042 return false;
3043
3044 if (Record->isUnion())
3046 CheckIfTriviallyCopyable);
3047
3048 std::optional<int64_t> StructSize = structHasUniqueObjectRepresentations(
3049 *this, Record, CheckIfTriviallyCopyable);
3050
3051 return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(Ty));
3052 }
3053
3054 // FIXME: More cases to handle here (list by rsmith):
3055 // vectors (careful about, eg, vector of 3 foo)
3056 // _Complex int and friends
3057 // _Atomic T
3058 // Obj-C block pointers
3059 // Obj-C object pointers
3060 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
3061 // clk_event_t, queue_t, reserve_id_t)
3062 // There're also Obj-C class types and the Obj-C selector type, but I think it
3063 // makes sense for those to return false here.
3064
3065 return false;
3066}
3067
3069 unsigned count = 0;
3070 // Count ivars declared in class extension.
3071 for (const auto *Ext : OI->known_extensions())
3072 count += Ext->ivar_size();
3073
3074 // Count ivar defined in this class's implementation. This
3075 // includes synthesized ivars.
3076 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
3077 count += ImplDecl->ivar_size();
3078
3079 return count;
3080}
3081
3083 if (!E)
3084 return false;
3085
3086 // nullptr_t is always treated as null.
3087 if (E->getType()->isNullPtrType()) return true;
3088
3089 if (E->getType()->isAnyPointerType() &&
3092 return true;
3093
3094 // Unfortunately, __null has type 'int'.
3095 if (isa<GNUNullExpr>(E)) return true;
3096
3097 return false;
3098}
3099
3100/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
3101/// exists.
3103 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3104 I = ObjCImpls.find(D);
3105 if (I != ObjCImpls.end())
3106 return cast<ObjCImplementationDecl>(I->second);
3107 return nullptr;
3108}
3109
3110/// Get the implementation of ObjCCategoryDecl, or nullptr if none
3111/// exists.
3113 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3114 I = ObjCImpls.find(D);
3115 if (I != ObjCImpls.end())
3116 return cast<ObjCCategoryImplDecl>(I->second);
3117 return nullptr;
3118}
3119
3120/// Set the implementation of ObjCInterfaceDecl.
3122 ObjCImplementationDecl *ImplD) {
3123 assert(IFaceD && ImplD && "Passed null params");
3124 ObjCImpls[IFaceD] = ImplD;
3125}
3126
3127/// Set the implementation of ObjCCategoryDecl.
3129 ObjCCategoryImplDecl *ImplD) {
3130 assert(CatD && ImplD && "Passed null params");
3131 ObjCImpls[CatD] = ImplD;
3132}
3133
3134const ObjCMethodDecl *
3136 return ObjCMethodRedecls.lookup(MD);
3137}
3138
3140 const ObjCMethodDecl *Redecl) {
3141 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
3142 ObjCMethodRedecls[MD] = Redecl;
3143}
3144
3146 const NamedDecl *ND) const {
3147 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
3148 return ID;
3149 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
3150 return CD->getClassInterface();
3151 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
3152 return IMD->getClassInterface();
3153
3154 return nullptr;
3155}
3156
3157/// Get the copy initialization expression of VarDecl, or nullptr if
3158/// none exists.
3160 assert(VD && "Passed null params");
3161 assert(VD->hasAttr<BlocksAttr>() &&
3162 "getBlockVarCopyInits - not __block var");
3163 auto I = BlockVarCopyInits.find(VD);
3164 if (I != BlockVarCopyInits.end())
3165 return I->second;
3166 return {nullptr, false};
3167}
3168
3169/// Set the copy initialization expression of a block var decl.
3171 bool CanThrow) {
3172 assert(VD && CopyExpr && "Passed null params");
3173 assert(VD->hasAttr<BlocksAttr>() &&
3174 "setBlockVarCopyInits - not __block var");
3175 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
3176}
3177
3179 unsigned DataSize) const {
3180 if (!DataSize)
3182 else
3183 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
3184 "incorrect data size provided to CreateTypeSourceInfo!");
3185
3186 auto *TInfo =
3187 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
3188 new (TInfo) TypeSourceInfo(T, DataSize);
3189 return TInfo;
3190}
3191
3193 SourceLocation L) const {
3195 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
3196 return DI;
3197}
3198
3199const ASTRecordLayout &
3201 return getObjCLayout(D);
3202}
3203
3206 bool &AnyNonCanonArgs) {
3207 SmallVector<TemplateArgument, 16> CanonArgs(Args);
3208 AnyNonCanonArgs |= C.canonicalizeTemplateArguments(CanonArgs);
3209 return CanonArgs;
3210}
3211
3214 bool AnyNonCanonArgs = false;
3215 for (auto &Arg : Args) {
3216 TemplateArgument OrigArg = Arg;
3218 AnyNonCanonArgs |= !Arg.structurallyEquals(OrigArg);
3219 }
3220 return AnyNonCanonArgs;
3221}
3222
3223//===----------------------------------------------------------------------===//
3224// Type creation/memoization methods
3225//===----------------------------------------------------------------------===//
3226
3228ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
3229 unsigned fastQuals = quals.getFastQualifiers();
3230 quals.removeFastQualifiers();
3231
3232 // Check if we've already instantiated this type.
3233 llvm::FoldingSetNodeID ID;
3234 ExtQuals::Profile(ID, baseType, quals);
3235 void *insertPos = nullptr;
3236 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
3237 assert(eq->getQualifiers() == quals);
3238 return QualType(eq, fastQuals);
3239 }
3240
3241 // If the base type is not canonical, make the appropriate canonical type.
3242 QualType canon;
3243 if (!baseType->isCanonicalUnqualified()) {
3244 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
3245 canonSplit.Quals.addConsistentQualifiers(quals);
3246 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
3247
3248 // Re-find the insert position.
3249 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
3250 }
3251
3252 auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
3253 ExtQualNodes.InsertNode(eq, insertPos);
3254 return QualType(eq, fastQuals);
3255}
3256
3258 LangAS AddressSpace) const {
3259 QualType CanT = getCanonicalType(T);
3260 if (CanT.getAddressSpace() == AddressSpace)
3261 return T;
3262
3263 // If we are composing extended qualifiers together, merge together
3264 // into one ExtQuals node.
3265 QualifierCollector Quals;
3266 const Type *TypeNode = Quals.strip(T);
3267
3268 // If this type already has an address space specified, it cannot get
3269 // another one.
3270 assert(!Quals.hasAddressSpace() &&
3271 "Type cannot be in multiple addr spaces!");
3272 Quals.addAddressSpace(AddressSpace);
3273
3274 return getExtQualType(TypeNode, Quals);
3275}
3276
3278 // If the type is not qualified with an address space, just return it
3279 // immediately.
3280 if (!T.hasAddressSpace())
3281 return T;
3282
3283 QualifierCollector Quals;
3284 const Type *TypeNode;
3285 // For arrays, strip the qualifier off the element type, then reconstruct the
3286 // array type
3287 if (T.getTypePtr()->isArrayType()) {
3288 T = getUnqualifiedArrayType(T, Quals);
3289 TypeNode = T.getTypePtr();
3290 } else {
3291 // If we are composing extended qualifiers together, merge together
3292 // into one ExtQuals node.
3293 while (T.hasAddressSpace()) {
3294 TypeNode = Quals.strip(T);
3295
3296 // If the type no longer has an address space after stripping qualifiers,
3297 // jump out.
3298 if (!QualType(TypeNode, 0).hasAddressSpace())
3299 break;
3300
3301 // There might be sugar in the way. Strip it and try again.
3302 T = T.getSingleStepDesugaredType(*this);
3303 }
3304 }
3305
3306 Quals.removeAddressSpace();
3307
3308 // Removal of the address space can mean there are no longer any
3309 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3310 // or required.
3311 if (Quals.hasNonFastQualifiers())
3312 return getExtQualType(TypeNode, Quals);
3313 else
3314 return QualType(TypeNode, Quals.getFastQualifiers());
3315}
3316
3317uint16_t
3319 assert(RD->isPolymorphic() &&
3320 "Attempted to get vtable pointer discriminator on a monomorphic type");
3321 std::unique_ptr<MangleContext> MC(createMangleContext());
3322 SmallString<256> Str;
3323 llvm::raw_svector_ostream Out(Str);
3324 MC->mangleCXXVTable(RD, Out);
3325 return llvm::getPointerAuthStableSipHash(Str);
3326}
3327
3328/// Encode a function type for use in the discriminator of a function pointer
3329/// type. We can't use the itanium scheme for this since C has quite permissive
3330/// rules for type compatibility that we need to be compatible with.
3331///
3332/// Formally, this function associates every function pointer type T with an
3333/// encoded string E(T). Let the equivalence relation T1 ~ T2 be defined as
3334/// E(T1) == E(T2). E(T) is part of the ABI of values of type T. C type
3335/// compatibility requires equivalent treatment under the ABI, so
3336/// CCompatible(T1, T2) must imply E(T1) == E(T2), that is, CCompatible must be
3337/// a subset of ~. Crucially, however, it must be a proper subset because
3338/// CCompatible is not an equivalence relation: for example, int[] is compatible
3339/// with both int[1] and int[2], but the latter are not compatible with each
3340/// other. Therefore this encoding function must be careful to only distinguish
3341/// types if there is no third type with which they are both required to be
3342/// compatible.
3344 raw_ostream &OS, QualType QT) {
3345 // FIXME: Consider address space qualifiers.
3346 const Type *T = QT.getCanonicalType().getTypePtr();
3347
3348 // FIXME: Consider using the C++ type mangling when we encounter a construct
3349 // that is incompatible with C.
3350
3351 switch (T->getTypeClass()) {
3352 case Type::Atomic:
3354 Ctx, OS, cast<AtomicType>(T)->getValueType());
3355
3356 case Type::LValueReference:
3357 OS << "R";
3360 return;
3361 case Type::RValueReference:
3362 OS << "O";
3365 return;
3366
3367 case Type::Pointer:
3368 // C11 6.7.6.1p2:
3369 // For two pointer types to be compatible, both shall be identically
3370 // qualified and both shall be pointers to compatible types.
3371 // FIXME: we should also consider pointee types.
3372 OS << "P";
3373 return;
3374
3375 case Type::ObjCObjectPointer:
3376 case Type::BlockPointer:
3377 OS << "P";
3378 return;
3379
3380 case Type::Complex:
3381 OS << "C";
3383 Ctx, OS, cast<ComplexType>(T)->getElementType());
3384
3385 case Type::VariableArray:
3386 case Type::ConstantArray:
3387 case Type::IncompleteArray:
3388 case Type::ArrayParameter:
3389 // C11 6.7.6.2p6:
3390 // For two array types to be compatible, both shall have compatible
3391 // element types, and if both size specifiers are present, and are integer
3392 // constant expressions, then both size specifiers shall have the same
3393 // constant value [...]
3394 //
3395 // So since ElemType[N] has to be compatible ElemType[], we can't encode the
3396 // width of the array.
3397 OS << "A";
3399 Ctx, OS, cast<ArrayType>(T)->getElementType());
3400
3401 case Type::ObjCInterface:
3402 case Type::ObjCObject:
3403 OS << "<objc_object>";
3404 return;
3405
3406 case Type::Enum: {
3407 // C11 6.7.2.2p4:
3408 // Each enumerated type shall be compatible with char, a signed integer
3409 // type, or an unsigned integer type.
3410 //
3411 // So we have to treat enum types as integers.
3412 QualType UnderlyingType = T->castAsEnumDecl()->getIntegerType();
3414 Ctx, OS, UnderlyingType.isNull() ? Ctx.IntTy : UnderlyingType);
3415 }
3416
3417 case Type::FunctionNoProto:
3418 case Type::FunctionProto: {
3419 // C11 6.7.6.3p15:
3420 // For two function types to be compatible, both shall specify compatible
3421 // return types. Moreover, the parameter type lists, if both are present,
3422 // shall agree in the number of parameters and in the use of the ellipsis
3423 // terminator; corresponding parameters shall have compatible types.
3424 //
3425 // That paragraph goes on to describe how unprototyped functions are to be
3426 // handled, which we ignore here. Unprototyped function pointers are hashed
3427 // as though they were prototyped nullary functions since thats probably
3428 // what the user meant. This behavior is non-conforming.
3429 // FIXME: If we add a "custom discriminator" function type attribute we
3430 // should encode functions as their discriminators.
3431 OS << "F";
3432 const auto *FuncType = cast<FunctionType>(T);
3433 encodeTypeForFunctionPointerAuth(Ctx, OS, FuncType->getReturnType());
3434 if (const auto *FPT = dyn_cast<FunctionProtoType>(FuncType)) {
3435 for (QualType Param : FPT->param_types()) {
3436 Param = Ctx.getSignatureParameterType(Param);
3437 encodeTypeForFunctionPointerAuth(Ctx, OS, Param);
3438 }
3439 if (FPT->isVariadic())
3440 OS << "z";
3441 }
3442 OS << "E";
3443 return;
3444 }
3445
3446 case Type::MemberPointer: {
3447 OS << "M";
3448 const auto *MPT = T->castAs<MemberPointerType>();
3450 Ctx, OS, QualType(MPT->getQualifier().getAsType(), 0));
3451 encodeTypeForFunctionPointerAuth(Ctx, OS, MPT->getPointeeType());
3452 return;
3453 }
3454 case Type::ExtVector:
3455 case Type::Vector:
3456 OS << "Dv" << Ctx.getTypeSizeInChars(T).getQuantity();
3457 break;
3458
3459 // Don't bother discriminating based on these types.
3460 case Type::Pipe:
3461 case Type::BitInt:
3462 case Type::ConstantMatrix:
3463 OS << "?";
3464 return;
3465
3466 case Type::Builtin: {
3467 const auto *BTy = T->castAs<BuiltinType>();
3468 switch (BTy->getKind()) {
3469#define SIGNED_TYPE(Id, SingletonId) \
3470 case BuiltinType::Id: \
3471 OS << "i"; \
3472 return;
3473#define UNSIGNED_TYPE(Id, SingletonId) \
3474 case BuiltinType::Id: \
3475 OS << "i"; \
3476 return;
3477#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
3478#define BUILTIN_TYPE(Id, SingletonId)
3479#include "clang/AST/BuiltinTypes.def"
3480 llvm_unreachable("placeholder types should not appear here.");
3481
3482 case BuiltinType::Half:
3483 OS << "Dh";
3484 return;
3485 case BuiltinType::Float:
3486 OS << "f";
3487 return;
3488 case BuiltinType::Double:
3489 OS << "d";
3490 return;
3491 case BuiltinType::LongDouble:
3492 OS << "e";
3493 return;
3494 case BuiltinType::Float16:
3495 OS << "DF16_";
3496 return;
3497 case BuiltinType::Float128:
3498 OS << "g";
3499 return;
3500
3501 case BuiltinType::Void:
3502 OS << "v";
3503 return;
3504
3505 case BuiltinType::ObjCId:
3506 case BuiltinType::ObjCClass:
3507 case BuiltinType::ObjCSel:
3508 case BuiltinType::NullPtr:
3509 OS << "P";
3510 return;
3511
3512 // Don't bother discriminating based on OpenCL types.
3513 case BuiltinType::OCLSampler:
3514 case BuiltinType::OCLEvent:
3515 case BuiltinType::OCLClkEvent:
3516 case BuiltinType::OCLQueue:
3517 case BuiltinType::OCLReserveID:
3518 case BuiltinType::BFloat16:
3519 case BuiltinType::VectorQuad:
3520 case BuiltinType::VectorPair:
3521 case BuiltinType::DMR1024:
3522 OS << "?";
3523 return;
3524
3525 // Don't bother discriminating based on these seldom-used types.
3526 case BuiltinType::Ibm128:
3527 return;
3528#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3529 case BuiltinType::Id: \
3530 return;
3531#include "clang/Basic/OpenCLImageTypes.def"
3532#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3533 case BuiltinType::Id: \
3534 return;
3535#include "clang/Basic/OpenCLExtensionTypes.def"
3536#define SVE_TYPE(Name, Id, SingletonId) \
3537 case BuiltinType::Id: \
3538 return;
3539#include "clang/Basic/AArch64ACLETypes.def"
3540#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3541 case BuiltinType::Id: \
3542 return;
3543#include "clang/Basic/HLSLIntangibleTypes.def"
3544 case BuiltinType::Dependent:
3545 llvm_unreachable("should never get here");
3546#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
3547#include "clang/Basic/AMDGPUTypes.def"
3548 case BuiltinType::WasmExternRef:
3549#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3550#include "clang/Basic/RISCVVTypes.def"
3551 llvm_unreachable("not yet implemented");
3552 }
3553 llvm_unreachable("should never get here");
3554 }
3555 case Type::Record: {
3556 const RecordDecl *RD = T->castAsCanonical<RecordType>()->getOriginalDecl();
3557 const IdentifierInfo *II = RD->getIdentifier();
3558
3559 // In C++, an immediate typedef of an anonymous struct or union
3560 // is considered to name it for ODR purposes, but C's specification
3561 // of type compatibility does not have a similar rule. Using the typedef
3562 // name in function type discriminators anyway, as we do here,
3563 // therefore technically violates the C standard: two function pointer
3564 // types defined in terms of two typedef'd anonymous structs with
3565 // different names are formally still compatible, but we are assigning
3566 // them different discriminators and therefore incompatible ABIs.
3567 //
3568 // This is a relatively minor violation that significantly improves
3569 // discrimination in some cases and has not caused problems in
3570 // practice. Regardless, it is now part of the ABI in places where
3571 // function type discrimination is used, and it can no longer be
3572 // changed except on new platforms.
3573
3574 if (!II)
3575 if (const TypedefNameDecl *Typedef = RD->getTypedefNameForAnonDecl())
3576 II = Typedef->getDeclName().getAsIdentifierInfo();
3577
3578 if (!II) {
3579 OS << "<anonymous_record>";
3580 return;
3581 }
3582 OS << II->getLength() << II->getName();
3583 return;
3584 }
3585 case Type::HLSLAttributedResource:
3586 case Type::HLSLInlineSpirv:
3587 llvm_unreachable("should never get here");
3588 break;
3589 case Type::DeducedTemplateSpecialization:
3590 case Type::Auto:
3591#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3592#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3593#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3594#define ABSTRACT_TYPE(Class, Base)
3595#define TYPE(Class, Base)
3596#include "clang/AST/TypeNodes.inc"
3597 llvm_unreachable("unexpected non-canonical or dependent type!");
3598 return;
3599 }
3600}
3601
3603 assert(!T->isDependentType() &&
3604 "cannot compute type discriminator of a dependent type");
3605
3606 SmallString<256> Str;
3607 llvm::raw_svector_ostream Out(Str);
3608
3609 if (T->isFunctionPointerType() || T->isFunctionReferenceType())
3610 T = T->getPointeeType();
3611
3612 if (T->isFunctionType()) {
3614 } else {
3615 T = T.getUnqualifiedType();
3616 // Calls to member function pointers don't need to worry about
3617 // language interop or the laxness of the C type compatibility rules.
3618 // We just mangle the member pointer type directly, which is
3619 // implicitly much stricter about type matching. However, we do
3620 // strip any top-level exception specification before this mangling.
3621 // C++23 requires calls to work when the function type is convertible
3622 // to the pointer type by a function pointer conversion, which can
3623 // change the exception specification. This does not technically
3624 // require the exception specification to not affect representation,
3625 // because the function pointer conversion is still always a direct
3626 // value conversion and therefore an opportunity to resign the
3627 // pointer. (This is in contrast to e.g. qualification conversions,
3628 // which can be applied in nested pointer positions, effectively
3629 // requiring qualified and unqualified representations to match.)
3630 // However, it is pragmatic to ignore exception specifications
3631 // because it allows a certain amount of `noexcept` mismatching
3632 // to not become a visible ODR problem. This also leaves some
3633 // room for the committee to add laxness to function pointer
3634 // conversions in future standards.
3635 if (auto *MPT = T->getAs<MemberPointerType>())
3636 if (MPT->isMemberFunctionPointer()) {
3637 QualType PointeeType = MPT->getPointeeType();
3638 if (PointeeType->castAs<FunctionProtoType>()->getExceptionSpecType() !=
3639 EST_None) {
3641 T = getMemberPointerType(FT, MPT->getQualifier(),
3642 MPT->getMostRecentCXXRecordDecl());
3643 }
3644 }
3645 std::unique_ptr<MangleContext> MC(createMangleContext());
3646 MC->mangleCanonicalTypeName(T, Out);
3647 }
3648
3649 return llvm::getPointerAuthStableSipHash(Str);
3650}
3651
3653 Qualifiers::GC GCAttr) const {
3654 QualType CanT = getCanonicalType(T);
3655 if (CanT.getObjCGCAttr() == GCAttr)
3656 return T;
3657
3658 if (const auto *ptr = T->getAs<PointerType>()) {
3659 QualType Pointee = ptr->getPointeeType();
3660 if (Pointee->isAnyPointerType()) {
3661 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
3662 return getPointerType(ResultType);
3663 }
3664 }
3665
3666 // If we are composing extended qualifiers together, merge together
3667 // into one ExtQuals node.
3668 QualifierCollector Quals;
3669 const Type *TypeNode = Quals.strip(T);
3670
3671 // If this type already has an ObjCGC specified, it cannot get
3672 // another one.
3673 assert(!Quals.hasObjCGCAttr() &&
3674 "Type cannot have multiple ObjCGCs!");
3675 Quals.addObjCGCAttr(GCAttr);
3676
3677 return getExtQualType(TypeNode, Quals);
3678}
3679
3681 if (const PointerType *Ptr = T->getAs<PointerType>()) {
3682 QualType Pointee = Ptr->getPointeeType();
3683 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
3684 return getPointerType(removeAddrSpaceQualType(Pointee));
3685 }
3686 }
3687 return T;
3688}
3689
3691 QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull,
3692 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3693 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3694
3695 llvm::FoldingSetNodeID ID;
3696 CountAttributedType::Profile(ID, WrappedTy, CountExpr, CountInBytes, OrNull);
3697
3698 void *InsertPos = nullptr;
3699 CountAttributedType *CATy =
3700 CountAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
3701 if (CATy)
3702 return QualType(CATy, 0);
3703
3704 QualType CanonTy = getCanonicalType(WrappedTy);
3705 size_t Size = CountAttributedType::totalSizeToAlloc<TypeCoupledDeclRefInfo>(
3706 DependentDecls.size());
3708 new (CATy) CountAttributedType(WrappedTy, CanonTy, CountExpr, CountInBytes,
3709 OrNull, DependentDecls);
3710 Types.push_back(CATy);
3711 CountAttributedTypes.InsertNode(CATy, InsertPos);
3712
3713 return QualType(CATy, 0);
3714}
3715
3718 llvm::function_ref<QualType(QualType)> Adjust) const {
3719 switch (Orig->getTypeClass()) {
3720 case Type::Attributed: {
3721 const auto *AT = cast<AttributedType>(Orig);
3722 return getAttributedType(AT->getAttrKind(),
3723 adjustType(AT->getModifiedType(), Adjust),
3724 adjustType(AT->getEquivalentType(), Adjust),
3725 AT->getAttr());
3726 }
3727
3728 case Type::BTFTagAttributed: {
3729 const auto *BTFT = dyn_cast<BTFTagAttributedType>(Orig);
3730 return getBTFTagAttributedType(BTFT->getAttr(),
3731 adjustType(BTFT->getWrappedType(), Adjust));
3732 }
3733
3734 case Type::Paren:
3735 return getParenType(
3736 adjustType(cast<ParenType>(Orig)->getInnerType(), Adjust));
3737
3738 case Type::Adjusted: {
3739 const auto *AT = cast<AdjustedType>(Orig);
3740 return getAdjustedType(AT->getOriginalType(),
3741 adjustType(AT->getAdjustedType(), Adjust));
3742 }
3743
3744 case Type::MacroQualified: {
3745 const auto *MQT = cast<MacroQualifiedType>(Orig);
3746 return getMacroQualifiedType(adjustType(MQT->getUnderlyingType(), Adjust),
3747 MQT->getMacroIdentifier());
3748 }
3749
3750 default:
3751 return Adjust(Orig);
3752 }
3753}
3754
3756 FunctionType::ExtInfo Info) {
3757 if (T->getExtInfo() == Info)
3758 return T;
3759
3761 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
3762 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
3763 } else {
3764 const auto *FPT = cast<FunctionProtoType>(T);
3765 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3766 EPI.ExtInfo = Info;
3767 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
3768 }
3769
3770 return cast<FunctionType>(Result.getTypePtr());
3771}
3772
3774 QualType ResultType) {
3775 return adjustType(FunctionType, [&](QualType Orig) {
3776 if (const auto *FNPT = Orig->getAs<FunctionNoProtoType>())
3777 return getFunctionNoProtoType(ResultType, FNPT->getExtInfo());
3778
3779 const auto *FPT = Orig->castAs<FunctionProtoType>();
3780 return getFunctionType(ResultType, FPT->getParamTypes(),
3781 FPT->getExtProtoInfo());
3782 });
3783}
3784
3786 QualType ResultType) {
3787 FD = FD->getMostRecentDecl();
3788 while (true) {
3789 FD->setType(adjustFunctionResultType(FD->getType(), ResultType));
3790 if (FunctionDecl *Next = FD->getPreviousDecl())
3791 FD = Next;
3792 else
3793 break;
3794 }
3796 L->DeducedReturnType(FD, ResultType);
3797}
3798
3799/// Get a function type and produce the equivalent function type with the
3800/// specified exception specification. Type sugar that can be present on a
3801/// declaration of a function with an exception specification is permitted
3802/// and preserved. Other type sugar (for instance, typedefs) is not.
3804 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
3805 return adjustType(Orig, [&](QualType Ty) {
3806 const auto *Proto = Ty->castAs<FunctionProtoType>();
3807 return getFunctionType(Proto->getReturnType(), Proto->getParamTypes(),
3808 Proto->getExtProtoInfo().withExceptionSpec(ESI));
3809 });
3810}
3811
3819
3821 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3822 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3823 SmallVector<QualType, 16> Args(Proto->param_types().size());
3824 for (unsigned i = 0, n = Args.size(); i != n; ++i)
3825 Args[i] = removePtrSizeAddrSpace(Proto->param_types()[i]);
3826 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3827 }
3828
3829 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3830 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3831 return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3832 }
3833
3834 return T;
3835}
3836
3842
3844 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3845 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3846 EPI.ExtParameterInfos = nullptr;
3847 return getFunctionType(Proto->getReturnType(), Proto->param_types(), EPI);
3848 }
3849 return T;
3850}
3851
3857
3860 bool AsWritten) {
3861 // Update the type.
3862 QualType Updated =
3864 FD->setType(Updated);
3865
3866 if (!AsWritten)
3867 return;
3868
3869 // Update the type in the type source information too.
3870 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3871 // If the type and the type-as-written differ, we may need to update
3872 // the type-as-written too.
3873 if (TSInfo->getType() != FD->getType())
3874 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
3875
3876 // FIXME: When we get proper type location information for exceptions,
3877 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3878 // up the TypeSourceInfo;
3879 assert(TypeLoc::getFullDataSizeForType(Updated) ==
3880 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3881 "TypeLoc size mismatch from updating exception specification");
3882 TSInfo->overrideType(Updated);
3883 }
3884}
3885
3886/// getComplexType - Return the uniqued reference to the type for a complex
3887/// number with the specified element type.
3889 // Unique pointers, to guarantee there is only one pointer of a particular
3890 // structure.
3891 llvm::FoldingSetNodeID ID;
3893
3894 void *InsertPos = nullptr;
3895 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3896 return QualType(CT, 0);
3897
3898 // If the pointee type isn't canonical, this won't be a canonical type either,
3899 // so fill in the canonical type field.
3900 QualType Canonical;
3901 if (!T.isCanonical()) {
3902 Canonical = getComplexType(getCanonicalType(T));
3903
3904 // Get the new insert position for the node we care about.
3905 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3906 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3907 }
3908 auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
3909 Types.push_back(New);
3910 ComplexTypes.InsertNode(New, InsertPos);
3911 return QualType(New, 0);
3912}
3913
3914/// getPointerType - Return the uniqued reference to the type for a pointer to
3915/// the specified type.
3917 // Unique pointers, to guarantee there is only one pointer of a particular
3918 // structure.
3919 llvm::FoldingSetNodeID ID;
3921
3922 void *InsertPos = nullptr;
3923 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3924 return QualType(PT, 0);
3925
3926 // If the pointee type isn't canonical, this won't be a canonical type either,
3927 // so fill in the canonical type field.
3928 QualType Canonical;
3929 if (!T.isCanonical()) {
3930 Canonical = getPointerType(getCanonicalType(T));
3931
3932 // Get the new insert position for the node we care about.
3933 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3934 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3935 }
3936 auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
3937 Types.push_back(New);
3938 PointerTypes.InsertNode(New, InsertPos);
3939 return QualType(New, 0);
3940}
3941
3943 llvm::FoldingSetNodeID ID;
3944 AdjustedType::Profile(ID, Orig, New);
3945 void *InsertPos = nullptr;
3946 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3947 if (AT)
3948 return QualType(AT, 0);
3949
3950 QualType Canonical = getCanonicalType(New);
3951
3952 // Get the new insert position for the node we care about.
3953 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3954 assert(!AT && "Shouldn't be in the map!");
3955
3956 AT = new (*this, alignof(AdjustedType))
3957 AdjustedType(Type::Adjusted, Orig, New, Canonical);
3958 Types.push_back(AT);
3959 AdjustedTypes.InsertNode(AT, InsertPos);
3960 return QualType(AT, 0);
3961}
3962
3964 llvm::FoldingSetNodeID ID;
3965 AdjustedType::Profile(ID, Orig, Decayed);
3966 void *InsertPos = nullptr;
3967 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3968 if (AT)
3969 return QualType(AT, 0);
3970
3971 QualType Canonical = getCanonicalType(Decayed);
3972
3973 // Get the new insert position for the node we care about.
3974 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3975 assert(!AT && "Shouldn't be in the map!");
3976
3977 AT = new (*this, alignof(DecayedType)) DecayedType(Orig, Decayed, Canonical);
3978 Types.push_back(AT);
3979 AdjustedTypes.InsertNode(AT, InsertPos);
3980 return QualType(AT, 0);
3981}
3982
3984 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
3985
3986 QualType Decayed;
3987
3988 // C99 6.7.5.3p7:
3989 // A declaration of a parameter as "array of type" shall be
3990 // adjusted to "qualified pointer to type", where the type
3991 // qualifiers (if any) are those specified within the [ and ] of
3992 // the array type derivation.
3993 if (T->isArrayType())
3994 Decayed = getArrayDecayedType(T);
3995
3996 // C99 6.7.5.3p8:
3997 // A declaration of a parameter as "function returning type"
3998 // shall be adjusted to "pointer to function returning type", as
3999 // in 6.3.2.1.
4000 if (T->isFunctionType())
4001 Decayed = getPointerType(T);
4002
4003 return getDecayedType(T, Decayed);
4004}
4005
4007 if (Ty->isArrayParameterType())
4008 return Ty;
4009 assert(Ty->isConstantArrayType() && "Ty must be an array type.");
4010 QualType DTy = Ty.getDesugaredType(*this);
4011 const auto *ATy = cast<ConstantArrayType>(DTy);
4012 llvm::FoldingSetNodeID ID;
4013 ATy->Profile(ID, *this, ATy->getElementType(), ATy->getZExtSize(),
4014 ATy->getSizeExpr(), ATy->getSizeModifier(),
4015 ATy->getIndexTypeQualifiers().getAsOpaqueValue());
4016 void *InsertPos = nullptr;
4017 ArrayParameterType *AT =
4018 ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
4019 if (AT)
4020 return QualType(AT, 0);
4021
4022 QualType Canonical;
4023 if (!DTy.isCanonical()) {
4024 Canonical = getArrayParameterType(getCanonicalType(Ty));
4025
4026 // Get the new insert position for the node we care about.
4027 AT = ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
4028 assert(!AT && "Shouldn't be in the map!");
4029 }
4030
4031 AT = new (*this, alignof(ArrayParameterType))
4032 ArrayParameterType(ATy, Canonical);
4033 Types.push_back(AT);
4034 ArrayParameterTypes.InsertNode(AT, InsertPos);
4035 return QualType(AT, 0);
4036}
4037
4038/// getBlockPointerType - Return the uniqued reference to the type for
4039/// a pointer to the specified block.
4041 assert(T->isFunctionType() && "block of function types only");
4042 // Unique pointers, to guarantee there is only one block of a particular
4043 // structure.
4044 llvm::FoldingSetNodeID ID;
4046
4047 void *InsertPos = nullptr;
4048 if (BlockPointerType *PT =
4049 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4050 return QualType(PT, 0);
4051
4052 // If the block pointee type isn't canonical, this won't be a canonical
4053 // type either so fill in the canonical type field.
4054 QualType Canonical;
4055 if (!T.isCanonical()) {
4057
4058 // Get the new insert position for the node we care about.
4059 BlockPointerType *NewIP =
4060 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4061 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4062 }
4063 auto *New =
4064 new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
4065 Types.push_back(New);
4066 BlockPointerTypes.InsertNode(New, InsertPos);
4067 return QualType(New, 0);
4068}
4069
4070/// getLValueReferenceType - Return the uniqued reference to the type for an
4071/// lvalue reference to the specified type.
4073ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
4074 assert((!T->isPlaceholderType() ||
4075 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4076 "Unresolved placeholder type");
4077
4078 // Unique pointers, to guarantee there is only one pointer of a particular
4079 // structure.
4080 llvm::FoldingSetNodeID ID;
4081 ReferenceType::Profile(ID, T, SpelledAsLValue);
4082
4083 void *InsertPos = nullptr;
4084 if (LValueReferenceType *RT =
4085 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
4086 return QualType(RT, 0);
4087
4088 const auto *InnerRef = T->getAs<ReferenceType>();
4089
4090 // If the referencee type isn't canonical, this won't be a canonical type
4091 // either, so fill in the canonical type field.
4092 QualType Canonical;
4093 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
4094 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4095 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
4096
4097 // Get the new insert position for the node we care about.
4098 LValueReferenceType *NewIP =
4099 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4100 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4101 }
4102
4103 auto *New = new (*this, alignof(LValueReferenceType))
4104 LValueReferenceType(T, Canonical, SpelledAsLValue);
4105 Types.push_back(New);
4106 LValueReferenceTypes.InsertNode(New, InsertPos);
4107
4108 return QualType(New, 0);
4109}
4110
4111/// getRValueReferenceType - Return the uniqued reference to the type for an
4112/// rvalue reference to the specified type.
4114 assert((!T->isPlaceholderType() ||
4115 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4116 "Unresolved placeholder type");
4117
4118 // Unique pointers, to guarantee there is only one pointer of a particular
4119 // structure.
4120 llvm::FoldingSetNodeID ID;
4121 ReferenceType::Profile(ID, T, false);
4122
4123 void *InsertPos = nullptr;
4124 if (RValueReferenceType *RT =
4125 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
4126 return QualType(RT, 0);
4127
4128 const auto *InnerRef = T->getAs<ReferenceType>();
4129
4130 // If the referencee type isn't canonical, this won't be a canonical type
4131 // either, so fill in the canonical type field.
4132 QualType Canonical;
4133 if (InnerRef || !T.isCanonical()) {
4134 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4135 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
4136
4137 // Get the new insert position for the node we care about.
4138 RValueReferenceType *NewIP =
4139 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4140 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4141 }
4142
4143 auto *New = new (*this, alignof(RValueReferenceType))
4144 RValueReferenceType(T, Canonical);
4145 Types.push_back(New);
4146 RValueReferenceTypes.InsertNode(New, InsertPos);
4147 return QualType(New, 0);
4148}
4149
4151 NestedNameSpecifier Qualifier,
4152 const CXXRecordDecl *Cls) const {
4153 if (!Qualifier) {
4154 assert(Cls && "At least one of Qualifier or Cls must be provided");
4155 Qualifier = NestedNameSpecifier(getCanonicalTagType(Cls).getTypePtr());
4156 } else if (!Cls) {
4157 Cls = Qualifier.getAsRecordDecl();
4158 }
4159 // Unique pointers, to guarantee there is only one pointer of a particular
4160 // structure.
4161 llvm::FoldingSetNodeID ID;
4162 MemberPointerType::Profile(ID, T, Qualifier, Cls);
4163
4164 void *InsertPos = nullptr;
4165 if (MemberPointerType *PT =
4166 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4167 return QualType(PT, 0);
4168
4169 NestedNameSpecifier CanonicalQualifier = [&] {
4170 if (!Cls)
4171 return Qualifier.getCanonical();
4172 NestedNameSpecifier R(getCanonicalTagType(Cls).getTypePtr());
4173 assert(R.isCanonical());
4174 return R;
4175 }();
4176 // If the pointee or class type isn't canonical, this won't be a canonical
4177 // type either, so fill in the canonical type field.
4178 QualType Canonical;
4179 if (!T.isCanonical() || Qualifier != CanonicalQualifier) {
4180 Canonical =
4181 getMemberPointerType(getCanonicalType(T), CanonicalQualifier, Cls);
4182 assert(!cast<MemberPointerType>(Canonical)->isSugared());
4183 // Get the new insert position for the node we care about.
4184 [[maybe_unused]] MemberPointerType *NewIP =
4185 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4186 assert(!NewIP && "Shouldn't be in the map!");
4187 }
4188 auto *New = new (*this, alignof(MemberPointerType))
4189 MemberPointerType(T, Qualifier, Canonical);
4190 Types.push_back(New);
4191 MemberPointerTypes.InsertNode(New, InsertPos);
4192 return QualType(New, 0);
4193}
4194
4195/// getConstantArrayType - Return the unique reference to the type for an
4196/// array of the specified element type.
4198 const llvm::APInt &ArySizeIn,
4199 const Expr *SizeExpr,
4201 unsigned IndexTypeQuals) const {
4202 assert((EltTy->isDependentType() ||
4203 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
4204 "Constant array of VLAs is illegal!");
4205
4206 // We only need the size as part of the type if it's instantiation-dependent.
4207 if (SizeExpr && !SizeExpr->isInstantiationDependent())
4208 SizeExpr = nullptr;
4209
4210 // Convert the array size into a canonical width matching the pointer size for
4211 // the target.
4212 llvm::APInt ArySize(ArySizeIn);
4213 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
4214
4215 llvm::FoldingSetNodeID ID;
4216 ConstantArrayType::Profile(ID, *this, EltTy, ArySize.getZExtValue(), SizeExpr,
4217 ASM, IndexTypeQuals);
4218
4219 void *InsertPos = nullptr;
4220 if (ConstantArrayType *ATP =
4221 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
4222 return QualType(ATP, 0);
4223
4224 // If the element type isn't canonical or has qualifiers, or the array bound
4225 // is instantiation-dependent, this won't be a canonical type either, so fill
4226 // in the canonical type field.
4227 QualType Canon;
4228 // FIXME: Check below should look for qualifiers behind sugar.
4229 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
4230 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4231 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
4232 ASM, IndexTypeQuals);
4233 Canon = getQualifiedType(Canon, canonSplit.Quals);
4234
4235 // Get the new insert position for the node we care about.
4236 ConstantArrayType *NewIP =
4237 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
4238 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4239 }
4240
4241 auto *New = ConstantArrayType::Create(*this, EltTy, Canon, ArySize, SizeExpr,
4242 ASM, IndexTypeQuals);
4243 ConstantArrayTypes.InsertNode(New, InsertPos);
4244 Types.push_back(New);
4245 return QualType(New, 0);
4246}
4247
4248/// getVariableArrayDecayedType - Turns the given type, which may be
4249/// variably-modified, into the corresponding type with all the known
4250/// sizes replaced with [*].
4252 // Vastly most common case.
4253 if (!type->isVariablyModifiedType()) return type;
4254
4255 QualType result;
4256
4257 SplitQualType split = type.getSplitDesugaredType();
4258 const Type *ty = split.Ty;
4259 switch (ty->getTypeClass()) {
4260#define TYPE(Class, Base)
4261#define ABSTRACT_TYPE(Class, Base)
4262#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4263#include "clang/AST/TypeNodes.inc"
4264 llvm_unreachable("didn't desugar past all non-canonical types?");
4265
4266 // These types should never be variably-modified.
4267 case Type::Builtin:
4268 case Type::Complex:
4269 case Type::Vector:
4270 case Type::DependentVector:
4271 case Type::ExtVector:
4272 case Type::DependentSizedExtVector:
4273 case Type::ConstantMatrix:
4274 case Type::DependentSizedMatrix:
4275 case Type::DependentAddressSpace:
4276 case Type::ObjCObject:
4277 case Type::ObjCInterface:
4278 case Type::ObjCObjectPointer:
4279 case Type::Record:
4280 case Type::Enum:
4281 case Type::UnresolvedUsing:
4282 case Type::TypeOfExpr:
4283 case Type::TypeOf:
4284 case Type::Decltype:
4285 case Type::UnaryTransform:
4286 case Type::DependentName:
4287 case Type::InjectedClassName:
4288 case Type::TemplateSpecialization:
4289 case Type::TemplateTypeParm:
4290 case Type::SubstTemplateTypeParmPack:
4291 case Type::SubstBuiltinTemplatePack:
4292 case Type::Auto:
4293 case Type::DeducedTemplateSpecialization:
4294 case Type::PackExpansion:
4295 case Type::PackIndexing:
4296 case Type::BitInt:
4297 case Type::DependentBitInt:
4298 case Type::ArrayParameter:
4299 case Type::HLSLAttributedResource:
4300 case Type::HLSLInlineSpirv:
4301 llvm_unreachable("type should never be variably-modified");
4302
4303 // These types can be variably-modified but should never need to
4304 // further decay.
4305 case Type::FunctionNoProto:
4306 case Type::FunctionProto:
4307 case Type::BlockPointer:
4308 case Type::MemberPointer:
4309 case Type::Pipe:
4310 return type;
4311
4312 // These types can be variably-modified. All these modifications
4313 // preserve structure except as noted by comments.
4314 // TODO: if we ever care about optimizing VLAs, there are no-op
4315 // optimizations available here.
4316 case Type::Pointer:
4319 break;
4320
4321 case Type::LValueReference: {
4322 const auto *lv = cast<LValueReferenceType>(ty);
4323 result = getLValueReferenceType(
4324 getVariableArrayDecayedType(lv->getPointeeType()),
4325 lv->isSpelledAsLValue());
4326 break;
4327 }
4328
4329 case Type::RValueReference: {
4330 const auto *lv = cast<RValueReferenceType>(ty);
4331 result = getRValueReferenceType(
4332 getVariableArrayDecayedType(lv->getPointeeType()));
4333 break;
4334 }
4335
4336 case Type::Atomic: {
4337 const auto *at = cast<AtomicType>(ty);
4338 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
4339 break;
4340 }
4341
4342 case Type::ConstantArray: {
4343 const auto *cat = cast<ConstantArrayType>(ty);
4344 result = getConstantArrayType(
4345 getVariableArrayDecayedType(cat->getElementType()),
4346 cat->getSize(),
4347 cat->getSizeExpr(),
4348 cat->getSizeModifier(),
4349 cat->getIndexTypeCVRQualifiers());
4350 break;
4351 }
4352
4353 case Type::DependentSizedArray: {
4354 const auto *dat = cast<DependentSizedArrayType>(ty);
4356 getVariableArrayDecayedType(dat->getElementType()), dat->getSizeExpr(),
4357 dat->getSizeModifier(), dat->getIndexTypeCVRQualifiers());
4358 break;
4359 }
4360
4361 // Turn incomplete types into [*] types.
4362 case Type::IncompleteArray: {
4363 const auto *iat = cast<IncompleteArrayType>(ty);
4364 result =
4366 /*size*/ nullptr, ArraySizeModifier::Normal,
4367 iat->getIndexTypeCVRQualifiers());
4368 break;
4369 }
4370
4371 // Turn VLA types into [*] types.
4372 case Type::VariableArray: {
4373 const auto *vat = cast<VariableArrayType>(ty);
4374 result =
4376 /*size*/ nullptr, ArraySizeModifier::Star,
4377 vat->getIndexTypeCVRQualifiers());
4378 break;
4379 }
4380 }
4381
4382 // Apply the top-level qualifiers from the original.
4383 return getQualifiedType(result, split.Quals);
4384}
4385
4386/// getVariableArrayType - Returns a non-unique reference to the type for a
4387/// variable array of the specified element type.
4390 unsigned IndexTypeQuals) const {
4391 // Since we don't unique expressions, it isn't possible to unique VLA's
4392 // that have an expression provided for their size.
4393 QualType Canon;
4394
4395 // Be sure to pull qualifiers off the element type.
4396 // FIXME: Check below should look for qualifiers behind sugar.
4397 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
4398 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4399 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
4400 IndexTypeQuals);
4401 Canon = getQualifiedType(Canon, canonSplit.Quals);
4402 }
4403
4404 auto *New = new (*this, alignof(VariableArrayType))
4405 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals);
4406
4407 VariableArrayTypes.push_back(New);
4408 Types.push_back(New);
4409 return QualType(New, 0);
4410}
4411
4412/// getDependentSizedArrayType - Returns a non-unique reference to
4413/// the type for a dependently-sized array of the specified element
4414/// type.
4418 unsigned elementTypeQuals) const {
4419 assert((!numElements || numElements->isTypeDependent() ||
4420 numElements->isValueDependent()) &&
4421 "Size must be type- or value-dependent!");
4422
4423 SplitQualType canonElementType = getCanonicalType(elementType).split();
4424
4425 void *insertPos = nullptr;
4426 llvm::FoldingSetNodeID ID;
4428 ID, *this, numElements ? QualType(canonElementType.Ty, 0) : elementType,
4429 ASM, elementTypeQuals, numElements);
4430
4431 // Look for an existing type with these properties.
4432 DependentSizedArrayType *canonTy =
4433 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4434
4435 // Dependently-sized array types that do not have a specified number
4436 // of elements will have their sizes deduced from a dependent
4437 // initializer.
4438 if (!numElements) {
4439 if (canonTy)
4440 return QualType(canonTy, 0);
4441
4442 auto *newType = new (*this, alignof(DependentSizedArrayType))
4443 DependentSizedArrayType(elementType, QualType(), numElements, ASM,
4444 elementTypeQuals);
4445 DependentSizedArrayTypes.InsertNode(newType, insertPos);
4446 Types.push_back(newType);
4447 return QualType(newType, 0);
4448 }
4449
4450 // If we don't have one, build one.
4451 if (!canonTy) {
4452 canonTy = new (*this, alignof(DependentSizedArrayType))
4453 DependentSizedArrayType(QualType(canonElementType.Ty, 0), QualType(),
4454 numElements, ASM, elementTypeQuals);
4455 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
4456 Types.push_back(canonTy);
4457 }
4458
4459 // Apply qualifiers from the element type to the array.
4460 QualType canon = getQualifiedType(QualType(canonTy,0),
4461 canonElementType.Quals);
4462
4463 // If we didn't need extra canonicalization for the element type or the size
4464 // expression, then just use that as our result.
4465 if (QualType(canonElementType.Ty, 0) == elementType &&
4466 canonTy->getSizeExpr() == numElements)
4467 return canon;
4468
4469 // Otherwise, we need to build a type which follows the spelling
4470 // of the element type.
4471 auto *sugaredType = new (*this, alignof(DependentSizedArrayType))
4472 DependentSizedArrayType(elementType, canon, numElements, ASM,
4473 elementTypeQuals);
4474 Types.push_back(sugaredType);
4475 return QualType(sugaredType, 0);
4476}
4477
4480 unsigned elementTypeQuals) const {
4481 llvm::FoldingSetNodeID ID;
4482 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
4483
4484 void *insertPos = nullptr;
4485 if (IncompleteArrayType *iat =
4486 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
4487 return QualType(iat, 0);
4488
4489 // If the element type isn't canonical, this won't be a canonical type
4490 // either, so fill in the canonical type field. We also have to pull
4491 // qualifiers off the element type.
4492 QualType canon;
4493
4494 // FIXME: Check below should look for qualifiers behind sugar.
4495 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
4496 SplitQualType canonSplit = getCanonicalType(elementType).split();
4497 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
4498 ASM, elementTypeQuals);
4499 canon = getQualifiedType(canon, canonSplit.Quals);
4500
4501 // Get the new insert position for the node we care about.
4502 IncompleteArrayType *existing =
4503 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4504 assert(!existing && "Shouldn't be in the map!"); (void) existing;
4505 }
4506
4507 auto *newType = new (*this, alignof(IncompleteArrayType))
4508 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
4509
4510 IncompleteArrayTypes.InsertNode(newType, insertPos);
4511 Types.push_back(newType);
4512 return QualType(newType, 0);
4513}
4514
4517#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
4518 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
4519 NUMVECTORS};
4520
4521#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
4522 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
4523
4524 switch (Ty->getKind()) {
4525 default:
4526 llvm_unreachable("Unsupported builtin vector type");
4527
4528#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4529 ElBits, NF, IsSigned) \
4530 case BuiltinType::Id: \
4531 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4532 llvm::ElementCount::getScalable(NumEls), NF};
4533#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4534 ElBits, NF) \
4535 case BuiltinType::Id: \
4536 return {ElBits == 16 ? HalfTy : (ElBits == 32 ? FloatTy : DoubleTy), \
4537 llvm::ElementCount::getScalable(NumEls), NF};
4538#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4539 ElBits, NF) \
4540 case BuiltinType::Id: \
4541 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4542#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4543 ElBits, NF) \
4544 case BuiltinType::Id: \
4545 return {MFloat8Ty, llvm::ElementCount::getScalable(NumEls), NF};
4546#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4547 case BuiltinType::Id: \
4548 return {BoolTy, llvm::ElementCount::getScalable(NumEls), NF};
4549#include "clang/Basic/AArch64ACLETypes.def"
4550
4551#define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
4552 IsSigned) \
4553 case BuiltinType::Id: \
4554 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4555 llvm::ElementCount::getScalable(NumEls), NF};
4556#define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4557 case BuiltinType::Id: \
4558 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
4559 llvm::ElementCount::getScalable(NumEls), NF};
4560#define RVV_VECTOR_TYPE_BFLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4561 case BuiltinType::Id: \
4562 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4563#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4564 case BuiltinType::Id: \
4565 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
4566#include "clang/Basic/RISCVVTypes.def"
4567 }
4568}
4569
4570/// getExternrefType - Return a WebAssembly externref type, which represents an
4571/// opaque reference to a host value.
4573 if (Target->getTriple().isWasm() && Target->hasFeature("reference-types")) {
4574#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
4575 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
4576 return SingletonId;
4577#include "clang/Basic/WebAssemblyReferenceTypes.def"
4578 }
4579 llvm_unreachable(
4580 "shouldn't try to generate type externref outside WebAssembly target");
4581}
4582
4583/// getScalableVectorType - Return the unique reference to a scalable vector
4584/// type of the specified element type and size. VectorType must be a built-in
4585/// type.
4587 unsigned NumFields) const {
4588 if (Target->hasAArch64ACLETypes()) {
4589 uint64_t EltTySize = getTypeSize(EltTy);
4590
4591#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4592 ElBits, NF, IsSigned) \
4593 if (EltTy->hasIntegerRepresentation() && !EltTy->isBooleanType() && \
4594 EltTy->hasSignedIntegerRepresentation() == IsSigned && \
4595 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4596 return SingletonId; \
4597 }
4598#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4599 ElBits, NF) \
4600 if (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4601 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4602 return SingletonId; \
4603 }
4604#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4605 ElBits, NF) \
4606 if (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4607 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4608 return SingletonId; \
4609 }
4610#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4611 ElBits, NF) \
4612 if (EltTy->isMFloat8Type() && EltTySize == ElBits && \
4613 NumElts == (NumEls * NF) && NumFields == 1) { \
4614 return SingletonId; \
4615 }
4616#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4617 if (EltTy->isBooleanType() && NumElts == (NumEls * NF) && NumFields == 1) \
4618 return SingletonId;
4619#include "clang/Basic/AArch64ACLETypes.def"
4620 } else if (Target->hasRISCVVTypes()) {
4621 uint64_t EltTySize = getTypeSize(EltTy);
4622#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
4623 IsFP, IsBF) \
4624 if (!EltTy->isBooleanType() && \
4625 ((EltTy->hasIntegerRepresentation() && \
4626 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4627 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4628 IsFP && !IsBF) || \
4629 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4630 IsBF && !IsFP)) && \
4631 EltTySize == ElBits && NumElts == NumEls && NumFields == NF) \
4632 return SingletonId;
4633#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4634 if (EltTy->isBooleanType() && NumElts == NumEls) \
4635 return SingletonId;
4636#include "clang/Basic/RISCVVTypes.def"
4637 }
4638 return QualType();
4639}
4640
4641/// getVectorType - Return the unique reference to a vector type of
4642/// the specified element type and size. VectorType must be a built-in type.
4644 VectorKind VecKind) const {
4645 assert(vecType->isBuiltinType() ||
4646 (vecType->isBitIntType() &&
4647 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4648 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4649
4650 // Check if we've already instantiated a vector of this type.
4651 llvm::FoldingSetNodeID ID;
4652 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
4653
4654 void *InsertPos = nullptr;
4655 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4656 return QualType(VTP, 0);
4657
4658 // If the element type isn't canonical, this won't be a canonical type either,
4659 // so fill in the canonical type field.
4660 QualType Canonical;
4661 if (!vecType.isCanonical()) {
4662 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
4663
4664 // Get the new insert position for the node we care about.
4665 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4666 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4667 }
4668 auto *New = new (*this, alignof(VectorType))
4669 VectorType(vecType, NumElts, Canonical, VecKind);
4670 VectorTypes.InsertNode(New, InsertPos);
4671 Types.push_back(New);
4672 return QualType(New, 0);
4673}
4674
4676 SourceLocation AttrLoc,
4677 VectorKind VecKind) const {
4678 llvm::FoldingSetNodeID ID;
4679 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
4680 VecKind);
4681 void *InsertPos = nullptr;
4682 DependentVectorType *Canon =
4683 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4685
4686 if (Canon) {
4687 New = new (*this, alignof(DependentVectorType)) DependentVectorType(
4688 VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4689 } else {
4690 QualType CanonVecTy = getCanonicalType(VecType);
4691 if (CanonVecTy == VecType) {
4692 New = new (*this, alignof(DependentVectorType))
4693 DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4694
4695 DependentVectorType *CanonCheck =
4696 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4697 assert(!CanonCheck &&
4698 "Dependent-sized vector_size canonical type broken");
4699 (void)CanonCheck;
4700 DependentVectorTypes.InsertNode(New, InsertPos);
4701 } else {
4702 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
4703 SourceLocation(), VecKind);
4704 New = new (*this, alignof(DependentVectorType))
4705 DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4706 }
4707 }
4708
4709 Types.push_back(New);
4710 return QualType(New, 0);
4711}
4712
4713/// getExtVectorType - Return the unique reference to an extended vector type of
4714/// the specified element type and size. VectorType must be a built-in type.
4716 unsigned NumElts) const {
4717 assert(vecType->isBuiltinType() || vecType->isDependentType() ||
4718 (vecType->isBitIntType() &&
4719 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4720 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4721
4722 // Check if we've already instantiated a vector of this type.
4723 llvm::FoldingSetNodeID ID;
4724 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
4726 void *InsertPos = nullptr;
4727 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4728 return QualType(VTP, 0);
4729
4730 // If the element type isn't canonical, this won't be a canonical type either,
4731 // so fill in the canonical type field.
4732 QualType Canonical;
4733 if (!vecType.isCanonical()) {
4734 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
4735
4736 // Get the new insert position for the node we care about.
4737 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4738 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4739 }
4740 auto *New = new (*this, alignof(ExtVectorType))
4741 ExtVectorType(vecType, NumElts, Canonical);
4742 VectorTypes.InsertNode(New, InsertPos);
4743 Types.push_back(New);
4744 return QualType(New, 0);
4745}
4746
4749 Expr *SizeExpr,
4750 SourceLocation AttrLoc) const {
4751 llvm::FoldingSetNodeID ID;
4753 SizeExpr);
4754
4755 void *InsertPos = nullptr;
4757 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4759 if (Canon) {
4760 // We already have a canonical version of this array type; use it as
4761 // the canonical type for a newly-built type.
4762 New = new (*this, alignof(DependentSizedExtVectorType))
4763 DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr,
4764 AttrLoc);
4765 } else {
4766 QualType CanonVecTy = getCanonicalType(vecType);
4767 if (CanonVecTy == vecType) {
4768 New = new (*this, alignof(DependentSizedExtVectorType))
4769 DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
4770
4771 DependentSizedExtVectorType *CanonCheck
4772 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4773 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4774 (void)CanonCheck;
4775 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
4776 } else {
4777 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4778 SourceLocation());
4779 New = new (*this, alignof(DependentSizedExtVectorType))
4780 DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc);
4781 }
4782 }
4783
4784 Types.push_back(New);
4785 return QualType(New, 0);
4786}
4787
4789 unsigned NumColumns) const {
4790 llvm::FoldingSetNodeID ID;
4791 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
4792 Type::ConstantMatrix);
4793
4794 assert(MatrixType::isValidElementType(ElementTy) &&
4795 "need a valid element type");
4796 assert(ConstantMatrixType::isDimensionValid(NumRows) &&
4798 "need valid matrix dimensions");
4799 void *InsertPos = nullptr;
4800 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
4801 return QualType(MTP, 0);
4802
4803 QualType Canonical;
4804 if (!ElementTy.isCanonical()) {
4805 Canonical =
4806 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
4807
4808 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4809 assert(!NewIP && "Matrix type shouldn't already exist in the map");
4810 (void)NewIP;
4811 }
4812
4813 auto *New = new (*this, alignof(ConstantMatrixType))
4814 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4815 MatrixTypes.InsertNode(New, InsertPos);
4816 Types.push_back(New);
4817 return QualType(New, 0);
4818}
4819
4821 Expr *RowExpr,
4822 Expr *ColumnExpr,
4823 SourceLocation AttrLoc) const {
4824 QualType CanonElementTy = getCanonicalType(ElementTy);
4825 llvm::FoldingSetNodeID ID;
4826 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4827 ColumnExpr);
4828
4829 void *InsertPos = nullptr;
4831 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4832
4833 if (!Canon) {
4834 Canon = new (*this, alignof(DependentSizedMatrixType))
4835 DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr,
4836 ColumnExpr, AttrLoc);
4837#ifndef NDEBUG
4838 DependentSizedMatrixType *CanonCheck =
4839 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4840 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4841#endif
4842 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
4843 Types.push_back(Canon);
4844 }
4845
4846 // Already have a canonical version of the matrix type
4847 //
4848 // If it exactly matches the requested type, use it directly.
4849 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4850 Canon->getRowExpr() == ColumnExpr)
4851 return QualType(Canon, 0);
4852
4853 // Use Canon as the canonical type for newly-built type.
4855 DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr,
4856 ColumnExpr, AttrLoc);
4857 Types.push_back(New);
4858 return QualType(New, 0);
4859}
4860
4862 Expr *AddrSpaceExpr,
4863 SourceLocation AttrLoc) const {
4864 assert(AddrSpaceExpr->isInstantiationDependent());
4865
4866 QualType canonPointeeType = getCanonicalType(PointeeType);
4867
4868 void *insertPos = nullptr;
4869 llvm::FoldingSetNodeID ID;
4870 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4871 AddrSpaceExpr);
4872
4873 DependentAddressSpaceType *canonTy =
4874 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
4875
4876 if (!canonTy) {
4877 canonTy = new (*this, alignof(DependentAddressSpaceType))
4878 DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr,
4879 AttrLoc);
4880 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
4881 Types.push_back(canonTy);
4882 }
4883
4884 if (canonPointeeType == PointeeType &&
4885 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4886 return QualType(canonTy, 0);
4887
4888 auto *sugaredType = new (*this, alignof(DependentAddressSpaceType))
4889 DependentAddressSpaceType(PointeeType, QualType(canonTy, 0),
4890 AddrSpaceExpr, AttrLoc);
4891 Types.push_back(sugaredType);
4892 return QualType(sugaredType, 0);
4893}
4894
4895/// Determine whether \p T is canonical as the result type of a function.
4897 return T.isCanonical() &&
4898 (T.getObjCLifetime() == Qualifiers::OCL_None ||
4899 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4900}
4901
4902/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4903QualType
4905 const FunctionType::ExtInfo &Info) const {
4906 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
4907 // functionality creates a function without a prototype regardless of
4908 // language mode (so it makes them even in C++). Once the rewriter has been
4909 // fixed, this assertion can be enabled again.
4910 //assert(!LangOpts.requiresStrictPrototypes() &&
4911 // "strict prototypes are disabled");
4912
4913 // Unique functions, to guarantee there is only one function of a particular
4914 // structure.
4915 llvm::FoldingSetNodeID ID;
4916 FunctionNoProtoType::Profile(ID, ResultTy, Info);
4917
4918 void *InsertPos = nullptr;
4919 if (FunctionNoProtoType *FT =
4920 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
4921 return QualType(FT, 0);
4922
4923 QualType Canonical;
4924 if (!isCanonicalResultType(ResultTy)) {
4925 Canonical =
4927
4928 // Get the new insert position for the node we care about.
4929 FunctionNoProtoType *NewIP =
4930 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4931 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4932 }
4933
4934 auto *New = new (*this, alignof(FunctionNoProtoType))
4935 FunctionNoProtoType(ResultTy, Canonical, Info);
4936 Types.push_back(New);
4937 FunctionNoProtoTypes.InsertNode(New, InsertPos);
4938 return QualType(New, 0);
4939}
4940
4943 CanQualType CanResultType = getCanonicalType(ResultType);
4944
4945 // Canonical result types do not have ARC lifetime qualifiers.
4946 if (CanResultType.getQualifiers().hasObjCLifetime()) {
4947 Qualifiers Qs = CanResultType.getQualifiers();
4948 Qs.removeObjCLifetime();
4950 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
4951 }
4952
4953 return CanResultType;
4954}
4955
4957 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
4958 if (ESI.Type == EST_None)
4959 return true;
4960 if (!NoexceptInType)
4961 return false;
4962
4963 // C++17 onwards: exception specification is part of the type, as a simple
4964 // boolean "can this function type throw".
4965 if (ESI.Type == EST_BasicNoexcept)
4966 return true;
4967
4968 // A noexcept(expr) specification is (possibly) canonical if expr is
4969 // value-dependent.
4970 if (ESI.Type == EST_DependentNoexcept)
4971 return true;
4972
4973 // A dynamic exception specification is canonical if it only contains pack
4974 // expansions (so we can't tell whether it's non-throwing) and all its
4975 // contained types are canonical.
4976 if (ESI.Type == EST_Dynamic) {
4977 bool AnyPackExpansions = false;
4978 for (QualType ET : ESI.Exceptions) {
4979 if (!ET.isCanonical())
4980 return false;
4981 if (ET->getAs<PackExpansionType>())
4982 AnyPackExpansions = true;
4983 }
4984 return AnyPackExpansions;
4985 }
4986
4987 return false;
4988}
4989
4990QualType ASTContext::getFunctionTypeInternal(
4991 QualType ResultTy, ArrayRef<QualType> ArgArray,
4992 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
4993 size_t NumArgs = ArgArray.size();
4994
4995 // Unique functions, to guarantee there is only one function of a particular
4996 // structure.
4997 llvm::FoldingSetNodeID ID;
4998 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
4999 *this, true);
5000
5001 QualType Canonical;
5002 bool Unique = false;
5003
5004 void *InsertPos = nullptr;
5005 if (FunctionProtoType *FPT =
5006 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
5007 QualType Existing = QualType(FPT, 0);
5008
5009 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
5010 // it so long as our exception specification doesn't contain a dependent
5011 // noexcept expression, or we're just looking for a canonical type.
5012 // Otherwise, we're going to need to create a type
5013 // sugar node to hold the concrete expression.
5014 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
5015 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
5016 return Existing;
5017
5018 // We need a new type sugar node for this one, to hold the new noexcept
5019 // expression. We do no canonicalization here, but that's OK since we don't
5020 // expect to see the same noexcept expression much more than once.
5021 Canonical = getCanonicalType(Existing);
5022 Unique = true;
5023 }
5024
5025 bool NoexceptInType = getLangOpts().CPlusPlus17;
5026 bool IsCanonicalExceptionSpec =
5028
5029 // Determine whether the type being created is already canonical or not.
5030 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
5031 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
5032 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
5033 if (!ArgArray[i].isCanonicalAsParam())
5034 isCanonical = false;
5035
5036 if (OnlyWantCanonical)
5037 assert(isCanonical &&
5038 "given non-canonical parameters constructing canonical type");
5039
5040 // If this type isn't canonical, get the canonical version of it if we don't
5041 // already have it. The exception spec is only partially part of the
5042 // canonical type, and only in C++17 onwards.
5043 if (!isCanonical && Canonical.isNull()) {
5044 SmallVector<QualType, 16> CanonicalArgs;
5045 CanonicalArgs.reserve(NumArgs);
5046 for (unsigned i = 0; i != NumArgs; ++i)
5047 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
5048
5049 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
5050 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
5051 CanonicalEPI.HasTrailingReturn = false;
5052
5053 if (IsCanonicalExceptionSpec) {
5054 // Exception spec is already OK.
5055 } else if (NoexceptInType) {
5056 switch (EPI.ExceptionSpec.Type) {
5058 // We don't know yet. It shouldn't matter what we pick here; no-one
5059 // should ever look at this.
5060 [[fallthrough]];
5061 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
5062 CanonicalEPI.ExceptionSpec.Type = EST_None;
5063 break;
5064
5065 // A dynamic exception specification is almost always "not noexcept",
5066 // with the exception that a pack expansion might expand to no types.
5067 case EST_Dynamic: {
5068 bool AnyPacks = false;
5069 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
5070 if (ET->getAs<PackExpansionType>())
5071 AnyPacks = true;
5072 ExceptionTypeStorage.push_back(getCanonicalType(ET));
5073 }
5074 if (!AnyPacks)
5075 CanonicalEPI.ExceptionSpec.Type = EST_None;
5076 else {
5077 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
5078 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
5079 }
5080 break;
5081 }
5082
5083 case EST_DynamicNone:
5084 case EST_BasicNoexcept:
5085 case EST_NoexceptTrue:
5086 case EST_NoThrow:
5087 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
5088 break;
5089
5091 llvm_unreachable("dependent noexcept is already canonical");
5092 }
5093 } else {
5094 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
5095 }
5096
5097 // Adjust the canonical function result type.
5098 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
5099 Canonical =
5100 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
5101
5102 // Get the new insert position for the node we care about.
5103 FunctionProtoType *NewIP =
5104 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
5105 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5106 }
5107
5108 // Compute the needed size to hold this FunctionProtoType and the
5109 // various trailing objects.
5110 auto ESH = FunctionProtoType::getExceptionSpecSize(
5111 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
5112 size_t Size = FunctionProtoType::totalSizeToAlloc<
5113 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
5114 FunctionType::FunctionTypeExtraAttributeInfo,
5115 FunctionType::FunctionTypeArmAttributes, FunctionType::ExceptionType,
5116 Expr *, FunctionDecl *, FunctionProtoType::ExtParameterInfo, Qualifiers,
5117 FunctionEffect, EffectConditionExpr>(
5120 EPI.requiresFunctionProtoTypeArmAttributes(), ESH.NumExceptionType,
5121 ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
5122 EPI.ExtParameterInfos ? NumArgs : 0,
5124 EPI.FunctionEffects.conditions().size());
5125
5126 auto *FTP = (FunctionProtoType *)Allocate(Size, alignof(FunctionProtoType));
5127 FunctionProtoType::ExtProtoInfo newEPI = EPI;
5128 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
5129 Types.push_back(FTP);
5130 if (!Unique)
5131 FunctionProtoTypes.InsertNode(FTP, InsertPos);
5132 if (!EPI.FunctionEffects.empty())
5133 AnyFunctionEffects = true;
5134 return QualType(FTP, 0);
5135}
5136
5137QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
5138 llvm::FoldingSetNodeID ID;
5139 PipeType::Profile(ID, T, ReadOnly);
5140
5141 void *InsertPos = nullptr;
5142 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
5143 return QualType(PT, 0);
5144
5145 // If the pipe element type isn't canonical, this won't be a canonical type
5146 // either, so fill in the canonical type field.
5147 QualType Canonical;
5148 if (!T.isCanonical()) {
5149 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
5150
5151 // Get the new insert position for the node we care about.
5152 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
5153 assert(!NewIP && "Shouldn't be in the map!");
5154 (void)NewIP;
5155 }
5156 auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly);
5157 Types.push_back(New);
5158 PipeTypes.InsertNode(New, InsertPos);
5159 return QualType(New, 0);
5160}
5161
5163 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
5164 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
5165 : Ty;
5166}
5167
5169 return getPipeType(T, true);
5170}
5171
5173 return getPipeType(T, false);
5174}
5175
5176QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
5177 llvm::FoldingSetNodeID ID;
5178 BitIntType::Profile(ID, IsUnsigned, NumBits);
5179
5180 void *InsertPos = nullptr;
5181 if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5182 return QualType(EIT, 0);
5183
5184 auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits);
5185 BitIntTypes.InsertNode(New, InsertPos);
5186 Types.push_back(New);
5187 return QualType(New, 0);
5188}
5189
5191 Expr *NumBitsExpr) const {
5192 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
5193 llvm::FoldingSetNodeID ID;
5194 DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
5195
5196 void *InsertPos = nullptr;
5197 if (DependentBitIntType *Existing =
5198 DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5199 return QualType(Existing, 0);
5200
5201 auto *New = new (*this, alignof(DependentBitIntType))
5202 DependentBitIntType(IsUnsigned, NumBitsExpr);
5203 DependentBitIntTypes.InsertNode(New, InsertPos);
5204
5205 Types.push_back(New);
5206 return QualType(New, 0);
5207}
5208
5211 using Kind = PredefinedSugarType::Kind;
5212
5213 if (auto *Target = PredefinedSugarTypes[llvm::to_underlying(KD)];
5214 Target != nullptr)
5215 return QualType(Target, 0);
5216
5217 auto getCanonicalType = [](const ASTContext &Ctx, Kind KDI) -> QualType {
5218 switch (KDI) {
5219 // size_t (C99TC3 6.5.3.4), signed size_t (C++23 5.13.2) and
5220 // ptrdiff_t (C99TC3 6.5.6) Although these types are not built-in, they
5221 // are part of the core language and are widely used. Using
5222 // PredefinedSugarType makes these types as named sugar types rather than
5223 // standard integer types, enabling better hints and diagnostics.
5224 case Kind::SizeT:
5225 return Ctx.getFromTargetType(Ctx.Target->getSizeType());
5226 case Kind::SignedSizeT:
5227 return Ctx.getFromTargetType(Ctx.Target->getSignedSizeType());
5228 case Kind::PtrdiffT:
5229 return Ctx.getFromTargetType(Ctx.Target->getPtrDiffType(LangAS::Default));
5230 }
5231 llvm_unreachable("unexpected kind");
5232 };
5233 auto *New = new (*this, alignof(PredefinedSugarType))
5234 PredefinedSugarType(KD, &Idents.get(PredefinedSugarType::getName(KD)),
5235 getCanonicalType(*this, static_cast<Kind>(KD)));
5236 Types.push_back(New);
5237 PredefinedSugarTypes[llvm::to_underlying(KD)] = New;
5238 return QualType(New, 0);
5239}
5240
5242 NestedNameSpecifier Qualifier,
5243 const TypeDecl *Decl) const {
5244 if (auto *Tag = dyn_cast<TagDecl>(Decl))
5245 return getTagType(Keyword, Qualifier, Tag,
5246 /*OwnsTag=*/false);
5247 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
5248 return getTypedefType(Keyword, Qualifier, Typedef);
5249 if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5250 return getUnresolvedUsingType(Keyword, Qualifier, UD);
5251
5253 assert(!Qualifier);
5254 return QualType(Decl->TypeForDecl, 0);
5255}
5256
5258 if (auto *Tag = dyn_cast<TagDecl>(TD))
5259 return getCanonicalTagType(Tag);
5260 if (auto *TN = dyn_cast<TypedefNameDecl>(TD))
5261 return getCanonicalType(TN->getUnderlyingType());
5262 if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TD))
5264 assert(TD->TypeForDecl);
5265 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5266}
5267
5269 if (const auto *TD = dyn_cast<TagDecl>(Decl))
5270 return getCanonicalTagType(TD);
5271 if (const auto *TD = dyn_cast<TypedefNameDecl>(Decl);
5272 isa_and_nonnull<TypedefDecl, TypeAliasDecl>(TD))
5274 /*Qualifier=*/std::nullopt, TD);
5275 if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5276 return getCanonicalUnresolvedUsingType(Using);
5277
5278 assert(Decl->TypeForDecl);
5279 return QualType(Decl->TypeForDecl, 0);
5280}
5281
5282/// getTypedefType - Return the unique reference to the type for the
5283/// specified typedef name decl.
5286 NestedNameSpecifier Qualifier,
5287 const TypedefNameDecl *Decl, QualType UnderlyingType,
5288 std::optional<bool> TypeMatchesDeclOrNone) const {
5289 if (!TypeMatchesDeclOrNone) {
5290 QualType DeclUnderlyingType = Decl->getUnderlyingType();
5291 assert(!DeclUnderlyingType.isNull());
5292 if (UnderlyingType.isNull())
5293 UnderlyingType = DeclUnderlyingType;
5294 else
5295 assert(hasSameType(UnderlyingType, DeclUnderlyingType));
5296 TypeMatchesDeclOrNone = UnderlyingType == DeclUnderlyingType;
5297 } else {
5298 // FIXME: This is a workaround for a serialization cycle: assume the decl
5299 // underlying type is not available; don't touch it.
5300 assert(!UnderlyingType.isNull());
5301 }
5302
5303 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier &&
5304 *TypeMatchesDeclOrNone) {
5305 if (Decl->TypeForDecl)
5306 return QualType(Decl->TypeForDecl, 0);
5307
5308 auto *NewType = new (*this, alignof(TypedefType))
5309 TypedefType(Type::Typedef, Keyword, Qualifier, Decl, UnderlyingType,
5310 !*TypeMatchesDeclOrNone);
5311
5312 Types.push_back(NewType);
5313 Decl->TypeForDecl = NewType;
5314 return QualType(NewType, 0);
5315 }
5316
5317 llvm::FoldingSetNodeID ID;
5318 TypedefType::Profile(ID, Keyword, Qualifier, Decl,
5319 *TypeMatchesDeclOrNone ? QualType() : UnderlyingType);
5320
5321 void *InsertPos = nullptr;
5322 if (FoldingSetPlaceholder<TypedefType> *Placeholder =
5323 TypedefTypes.FindNodeOrInsertPos(ID, InsertPos))
5324 return QualType(Placeholder->getType(), 0);
5325
5326 void *Mem =
5327 Allocate(TypedefType::totalSizeToAlloc<FoldingSetPlaceholder<TypedefType>,
5329 1, !!Qualifier, !*TypeMatchesDeclOrNone),
5330 alignof(TypedefType));
5331 auto *NewType =
5332 new (Mem) TypedefType(Type::Typedef, Keyword, Qualifier, Decl,
5333 UnderlyingType, !*TypeMatchesDeclOrNone);
5334 auto *Placeholder = new (NewType->getFoldingSetPlaceholder())
5336 TypedefTypes.InsertNode(Placeholder, InsertPos);
5337 Types.push_back(NewType);
5338 return QualType(NewType, 0);
5339}
5340
5342 NestedNameSpecifier Qualifier,
5343 const UsingShadowDecl *D,
5344 QualType UnderlyingType) const {
5345 // FIXME: This is expensive to compute every time!
5346 if (UnderlyingType.isNull()) {
5347 const auto *UD = cast<UsingDecl>(D->getIntroducer());
5348 UnderlyingType =
5351 UD->getQualifier(), cast<TypeDecl>(D->getTargetDecl()));
5352 }
5353
5354 llvm::FoldingSetNodeID ID;
5355 UsingType::Profile(ID, Keyword, Qualifier, D, UnderlyingType);
5356
5357 void *InsertPos = nullptr;
5358 if (const UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5359 return QualType(T, 0);
5360
5361 assert(!UnderlyingType.hasLocalQualifiers());
5362
5363 assert(
5365 UnderlyingType));
5366
5367 void *Mem =
5368 Allocate(UsingType::totalSizeToAlloc<NestedNameSpecifier>(!!Qualifier),
5369 alignof(UsingType));
5370 UsingType *T = new (Mem) UsingType(Keyword, Qualifier, D, UnderlyingType);
5371 Types.push_back(T);
5372 UsingTypes.InsertNode(T, InsertPos);
5373 return QualType(T, 0);
5374}
5375
5376TagType *ASTContext::getTagTypeInternal(ElaboratedTypeKeyword Keyword,
5377 NestedNameSpecifier Qualifier,
5378 const TagDecl *TD, bool OwnsTag,
5379 bool IsInjected,
5380 const Type *CanonicalType,
5381 bool WithFoldingSetNode) const {
5382 auto [TC, Size] = [&] {
5383 switch (TD->getDeclKind()) {
5384 case Decl::Enum:
5385 static_assert(alignof(EnumType) == alignof(TagType));
5386 return std::make_tuple(Type::Enum, sizeof(EnumType));
5387 case Decl::ClassTemplatePartialSpecialization:
5388 case Decl::ClassTemplateSpecialization:
5389 case Decl::CXXRecord:
5390 static_assert(alignof(RecordType) == alignof(TagType));
5391 static_assert(alignof(InjectedClassNameType) == alignof(TagType));
5392 if (cast<CXXRecordDecl>(TD)->hasInjectedClassType())
5393 return std::make_tuple(Type::InjectedClassName,
5394 sizeof(InjectedClassNameType));
5395 [[fallthrough]];
5396 case Decl::Record:
5397 return std::make_tuple(Type::Record, sizeof(RecordType));
5398 default:
5399 llvm_unreachable("unexpected decl kind");
5400 }
5401 }();
5402
5403 if (Qualifier) {
5404 static_assert(alignof(NestedNameSpecifier) <= alignof(TagType));
5405 Size = llvm::alignTo(Size, alignof(NestedNameSpecifier)) +
5406 sizeof(NestedNameSpecifier);
5407 }
5408 void *Mem;
5409 if (WithFoldingSetNode) {
5410 // FIXME: It would be more profitable to tail allocate the folding set node
5411 // from the type, instead of the other way around, due to the greater
5412 // alignment requirements of the type. But this makes it harder to deal with
5413 // the different type node sizes. This would require either uniquing from
5414 // different folding sets, or having the folding setaccept a
5415 // contextual parameter which is not fixed at construction.
5416 Mem = Allocate(
5417 sizeof(TagTypeFoldingSetPlaceholder) +
5418 TagTypeFoldingSetPlaceholder::getOffset() + Size,
5419 std::max(alignof(TagTypeFoldingSetPlaceholder), alignof(TagType)));
5420 auto *T = new (Mem) TagTypeFoldingSetPlaceholder();
5421 Mem = T->getTagType();
5422 } else {
5423 Mem = Allocate(Size, alignof(TagType));
5424 }
5425
5426 auto *T = [&, TC = TC]() -> TagType * {
5427 switch (TC) {
5428 case Type::Enum: {
5429 assert(isa<EnumDecl>(TD));
5430 auto *T = new (Mem) EnumType(TC, Keyword, Qualifier, TD, OwnsTag,
5431 IsInjected, CanonicalType);
5432 assert(reinterpret_cast<void *>(T) ==
5433 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5434 "TagType must be the first base of EnumType");
5435 return T;
5436 }
5437 case Type::Record: {
5438 assert(isa<RecordDecl>(TD));
5439 auto *T = new (Mem) RecordType(TC, Keyword, Qualifier, TD, OwnsTag,
5440 IsInjected, CanonicalType);
5441 assert(reinterpret_cast<void *>(T) ==
5442 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5443 "TagType must be the first base of RecordType");
5444 return T;
5445 }
5446 case Type::InjectedClassName: {
5447 auto *T = new (Mem) InjectedClassNameType(Keyword, Qualifier, TD,
5448 IsInjected, CanonicalType);
5449 assert(reinterpret_cast<void *>(T) ==
5450 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5451 "TagType must be the first base of InjectedClassNameType");
5452 return T;
5453 }
5454 default:
5455 llvm_unreachable("unexpected type class");
5456 }
5457 }();
5458 assert(T->getKeyword() == Keyword);
5459 assert(T->getQualifier() == Qualifier);
5460 assert(T->getOriginalDecl() == TD);
5461 assert(T->isInjected() == IsInjected);
5462 assert(T->isTagOwned() == OwnsTag);
5463 assert((T->isCanonicalUnqualified()
5464 ? QualType()
5465 : T->getCanonicalTypeInternal()) == QualType(CanonicalType, 0));
5466 Types.push_back(T);
5467 return T;
5468}
5469
5470static const TagDecl *getNonInjectedClassName(const TagDecl *TD) {
5471 if (const auto *RD = dyn_cast<CXXRecordDecl>(TD);
5472 RD && RD->isInjectedClassName())
5473 return cast<TagDecl>(RD->getDeclContext());
5474 return TD;
5475}
5476
5479 if (TD->TypeForDecl)
5480 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5481
5482 const Type *CanonicalType = getTagTypeInternal(
5484 /*Qualifier=*/std::nullopt, TD,
5485 /*OwnsTag=*/false, /*IsInjected=*/false, /*CanonicalType=*/nullptr,
5486 /*WithFoldingSetNode=*/false);
5487 TD->TypeForDecl = CanonicalType;
5488 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5489}
5490
5492 NestedNameSpecifier Qualifier,
5493 const TagDecl *TD, bool OwnsTag) const {
5494
5495 const TagDecl *NonInjectedTD = ::getNonInjectedClassName(TD);
5496 bool IsInjected = TD != NonInjectedTD;
5497
5498 ElaboratedTypeKeyword PreferredKeyword =
5501 NonInjectedTD->getTagKind());
5502
5503 if (Keyword == PreferredKeyword && !Qualifier && !OwnsTag) {
5504 if (const Type *T = TD->TypeForDecl; T && !T->isCanonicalUnqualified())
5505 return QualType(T, 0);
5506
5507 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5508 const Type *T =
5509 getTagTypeInternal(Keyword,
5510 /*Qualifier=*/std::nullopt, NonInjectedTD,
5511 /*OwnsTag=*/false, IsInjected, CanonicalType,
5512 /*WithFoldingSetNode=*/false);
5513 TD->TypeForDecl = T;
5514 return QualType(T, 0);
5515 }
5516
5517 llvm::FoldingSetNodeID ID;
5518 TagTypeFoldingSetPlaceholder::Profile(ID, Keyword, Qualifier, NonInjectedTD,
5519 OwnsTag, IsInjected);
5520
5521 void *InsertPos = nullptr;
5522 if (TagTypeFoldingSetPlaceholder *T =
5523 TagTypes.FindNodeOrInsertPos(ID, InsertPos))
5524 return QualType(T->getTagType(), 0);
5525
5526 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5527 TagType *T =
5528 getTagTypeInternal(Keyword, Qualifier, NonInjectedTD, OwnsTag, IsInjected,
5529 CanonicalType, /*WithFoldingSetNode=*/true);
5530 TagTypes.InsertNode(TagTypeFoldingSetPlaceholder::fromTagType(T), InsertPos);
5531 return QualType(T, 0);
5532}
5533
5534bool ASTContext::computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits,
5535 unsigned NumPositiveBits,
5536 QualType &BestType,
5537 QualType &BestPromotionType) {
5538 unsigned IntWidth = Target->getIntWidth();
5539 unsigned CharWidth = Target->getCharWidth();
5540 unsigned ShortWidth = Target->getShortWidth();
5541 bool EnumTooLarge = false;
5542 unsigned BestWidth;
5543 if (NumNegativeBits) {
5544 // If there is a negative value, figure out the smallest integer type (of
5545 // int/long/longlong) that fits.
5546 // If it's packed, check also if it fits a char or a short.
5547 if (IsPacked && NumNegativeBits <= CharWidth &&
5548 NumPositiveBits < CharWidth) {
5549 BestType = SignedCharTy;
5550 BestWidth = CharWidth;
5551 } else if (IsPacked && NumNegativeBits <= ShortWidth &&
5552 NumPositiveBits < ShortWidth) {
5553 BestType = ShortTy;
5554 BestWidth = ShortWidth;
5555 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
5556 BestType = IntTy;
5557 BestWidth = IntWidth;
5558 } else {
5559 BestWidth = Target->getLongWidth();
5560
5561 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
5562 BestType = LongTy;
5563 } else {
5564 BestWidth = Target->getLongLongWidth();
5565
5566 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
5567 EnumTooLarge = true;
5568 BestType = LongLongTy;
5569 }
5570 }
5571 BestPromotionType = (BestWidth <= IntWidth ? IntTy : BestType);
5572 } else {
5573 // If there is no negative value, figure out the smallest type that fits
5574 // all of the enumerator values.
5575 // If it's packed, check also if it fits a char or a short.
5576 if (IsPacked && NumPositiveBits <= CharWidth) {
5577 BestType = UnsignedCharTy;
5578 BestPromotionType = IntTy;
5579 BestWidth = CharWidth;
5580 } else if (IsPacked && NumPositiveBits <= ShortWidth) {
5581 BestType = UnsignedShortTy;
5582 BestPromotionType = IntTy;
5583 BestWidth = ShortWidth;
5584 } else if (NumPositiveBits <= IntWidth) {
5585 BestType = UnsignedIntTy;
5586 BestWidth = IntWidth;
5587 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5589 : IntTy;
5590 } else if (NumPositiveBits <= (BestWidth = Target->getLongWidth())) {
5591 BestType = UnsignedLongTy;
5592 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5594 : LongTy;
5595 } else {
5596 BestWidth = Target->getLongLongWidth();
5597 if (NumPositiveBits > BestWidth) {
5598 // This can happen with bit-precise integer types, but those are not
5599 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
5600 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
5601 // a 128-bit integer, we should consider doing the same.
5602 EnumTooLarge = true;
5603 }
5604 BestType = UnsignedLongLongTy;
5605 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5607 : LongLongTy;
5608 }
5609 }
5610 return EnumTooLarge;
5611}
5612
5614 assert((T->isIntegralType(*this) || T->isEnumeralType()) &&
5615 "Integral type required!");
5616 unsigned BitWidth = getIntWidth(T);
5617
5618 if (Value.isUnsigned() || Value.isNonNegative()) {
5619 if (T->isSignedIntegerOrEnumerationType())
5620 --BitWidth;
5621 return Value.getActiveBits() <= BitWidth;
5622 }
5623 return Value.getSignificantBits() <= BitWidth;
5624}
5625
5626UnresolvedUsingType *ASTContext::getUnresolvedUsingTypeInternal(
5628 const UnresolvedUsingTypenameDecl *D, void *InsertPos,
5629 const Type *CanonicalType) const {
5630 void *Mem = Allocate(
5631 UnresolvedUsingType::totalSizeToAlloc<
5633 !!InsertPos, !!Qualifier),
5634 alignof(UnresolvedUsingType));
5635 auto *T = new (Mem) UnresolvedUsingType(Keyword, Qualifier, D, CanonicalType);
5636 if (InsertPos) {
5637 auto *Placeholder = new (T->getFoldingSetPlaceholder())
5639 TypedefTypes.InsertNode(Placeholder, InsertPos);
5640 }
5641 Types.push_back(T);
5642 return T;
5643}
5644
5646 const UnresolvedUsingTypenameDecl *D) const {
5647 D = D->getCanonicalDecl();
5648 if (D->TypeForDecl)
5649 return D->TypeForDecl->getCanonicalTypeUnqualified();
5650
5651 const Type *CanonicalType = getUnresolvedUsingTypeInternal(
5653 /*Qualifier=*/std::nullopt, D,
5654 /*InsertPos=*/nullptr, /*CanonicalType=*/nullptr);
5655 D->TypeForDecl = CanonicalType;
5656 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5657}
5658
5661 NestedNameSpecifier Qualifier,
5662 const UnresolvedUsingTypenameDecl *D) const {
5663 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier) {
5664 if (const Type *T = D->TypeForDecl; T && !T->isCanonicalUnqualified())
5665 return QualType(T, 0);
5666
5667 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5668 const Type *T =
5669 getUnresolvedUsingTypeInternal(ElaboratedTypeKeyword::None,
5670 /*Qualifier=*/std::nullopt, D,
5671 /*InsertPos=*/nullptr, CanonicalType);
5672 D->TypeForDecl = T;
5673 return QualType(T, 0);
5674 }
5675
5676 llvm::FoldingSetNodeID ID;
5677 UnresolvedUsingType::Profile(ID, Keyword, Qualifier, D);
5678
5679 void *InsertPos = nullptr;
5681 UnresolvedUsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5682 return QualType(Placeholder->getType(), 0);
5683 assert(InsertPos);
5684
5685 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5686 const Type *T = getUnresolvedUsingTypeInternal(Keyword, Qualifier, D,
5687 InsertPos, CanonicalType);
5688 return QualType(T, 0);
5689}
5690
5692 QualType modifiedType,
5693 QualType equivalentType,
5694 const Attr *attr) const {
5695 llvm::FoldingSetNodeID id;
5696 AttributedType::Profile(id, attrKind, modifiedType, equivalentType, attr);
5697
5698 void *insertPos = nullptr;
5699 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
5700 if (type) return QualType(type, 0);
5701
5702 assert(!attr || attr->getKind() == attrKind);
5703
5704 QualType canon = getCanonicalType(equivalentType);
5705 type = new (*this, alignof(AttributedType))
5706 AttributedType(canon, attrKind, attr, modifiedType, equivalentType);
5707
5708 Types.push_back(type);
5709 AttributedTypes.InsertNode(type, insertPos);
5710
5711 return QualType(type, 0);
5712}
5713
5715 QualType equivalentType) const {
5716 return getAttributedType(attr->getKind(), modifiedType, equivalentType, attr);
5717}
5718
5720 QualType modifiedType,
5721 QualType equivalentType) {
5722 switch (nullability) {
5724 return getAttributedType(attr::TypeNonNull, modifiedType, equivalentType);
5725
5727 return getAttributedType(attr::TypeNullable, modifiedType, equivalentType);
5728
5730 return getAttributedType(attr::TypeNullableResult, modifiedType,
5731 equivalentType);
5732
5734 return getAttributedType(attr::TypeNullUnspecified, modifiedType,
5735 equivalentType);
5736 }
5737
5738 llvm_unreachable("Unknown nullability kind");
5739}
5740
5741QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
5742 QualType Wrapped) const {
5743 llvm::FoldingSetNodeID ID;
5744 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
5745
5746 void *InsertPos = nullptr;
5747 BTFTagAttributedType *Ty =
5748 BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
5749 if (Ty)
5750 return QualType(Ty, 0);
5751
5752 QualType Canon = getCanonicalType(Wrapped);
5753 Ty = new (*this, alignof(BTFTagAttributedType))
5754 BTFTagAttributedType(Canon, Wrapped, BTFAttr);
5755
5756 Types.push_back(Ty);
5757 BTFTagAttributedTypes.InsertNode(Ty, InsertPos);
5758
5759 return QualType(Ty, 0);
5760}
5761
5763 QualType Wrapped, QualType Contained,
5764 const HLSLAttributedResourceType::Attributes &Attrs) {
5765
5766 llvm::FoldingSetNodeID ID;
5767 HLSLAttributedResourceType::Profile(ID, Wrapped, Contained, Attrs);
5768
5769 void *InsertPos = nullptr;
5770 HLSLAttributedResourceType *Ty =
5771 HLSLAttributedResourceTypes.FindNodeOrInsertPos(ID, InsertPos);
5772 if (Ty)
5773 return QualType(Ty, 0);
5774
5775 Ty = new (*this, alignof(HLSLAttributedResourceType))
5776 HLSLAttributedResourceType(Wrapped, Contained, Attrs);
5777
5778 Types.push_back(Ty);
5779 HLSLAttributedResourceTypes.InsertNode(Ty, InsertPos);
5780
5781 return QualType(Ty, 0);
5782}
5783
5784QualType ASTContext::getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size,
5785 uint32_t Alignment,
5786 ArrayRef<SpirvOperand> Operands) {
5787 llvm::FoldingSetNodeID ID;
5788 HLSLInlineSpirvType::Profile(ID, Opcode, Size, Alignment, Operands);
5789
5790 void *InsertPos = nullptr;
5791 HLSLInlineSpirvType *Ty =
5792 HLSLInlineSpirvTypes.FindNodeOrInsertPos(ID, InsertPos);
5793 if (Ty)
5794 return QualType(Ty, 0);
5795
5796 void *Mem = Allocate(
5797 HLSLInlineSpirvType::totalSizeToAlloc<SpirvOperand>(Operands.size()),
5798 alignof(HLSLInlineSpirvType));
5799
5800 Ty = new (Mem) HLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
5801
5802 Types.push_back(Ty);
5803 HLSLInlineSpirvTypes.InsertNode(Ty, InsertPos);
5804
5805 return QualType(Ty, 0);
5806}
5807
5808/// Retrieve a substitution-result type.
5810 Decl *AssociatedDecl,
5811 unsigned Index,
5812 UnsignedOrNone PackIndex,
5813 bool Final) const {
5814 llvm::FoldingSetNodeID ID;
5815 SubstTemplateTypeParmType::Profile(ID, Replacement, AssociatedDecl, Index,
5816 PackIndex, Final);
5817 void *InsertPos = nullptr;
5818 SubstTemplateTypeParmType *SubstParm =
5819 SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5820
5821 if (!SubstParm) {
5822 void *Mem = Allocate(SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
5823 !Replacement.isCanonical()),
5824 alignof(SubstTemplateTypeParmType));
5825 SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
5826 Index, PackIndex, Final);
5827 Types.push_back(SubstParm);
5828 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
5829 }
5830
5831 return QualType(SubstParm, 0);
5832}
5833
5836 unsigned Index, bool Final,
5837 const TemplateArgument &ArgPack) {
5838#ifndef NDEBUG
5839 for (const auto &P : ArgPack.pack_elements())
5840 assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type");
5841#endif
5842
5843 llvm::FoldingSetNodeID ID;
5844 SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
5845 ArgPack);
5846 void *InsertPos = nullptr;
5847 if (SubstTemplateTypeParmPackType *SubstParm =
5848 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
5849 return QualType(SubstParm, 0);
5850
5851 QualType Canon;
5852 {
5853 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
5854 if (!AssociatedDecl->isCanonicalDecl() ||
5855 !CanonArgPack.structurallyEquals(ArgPack)) {
5857 AssociatedDecl->getCanonicalDecl(), Index, Final, CanonArgPack);
5858 [[maybe_unused]] const auto *Nothing =
5859 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
5860 assert(!Nothing);
5861 }
5862 }
5863
5864 auto *SubstParm = new (*this, alignof(SubstTemplateTypeParmPackType))
5865 SubstTemplateTypeParmPackType(Canon, AssociatedDecl, Index, Final,
5866 ArgPack);
5867 Types.push_back(SubstParm);
5868 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
5869 return QualType(SubstParm, 0);
5870}
5871
5874 assert(llvm::all_of(ArgPack.pack_elements(),
5875 [](const auto &P) {
5876 return P.getKind() == TemplateArgument::Type;
5877 }) &&
5878 "Pack contains a non-type");
5879
5880 llvm::FoldingSetNodeID ID;
5881 SubstBuiltinTemplatePackType::Profile(ID, ArgPack);
5882
5883 void *InsertPos = nullptr;
5884 if (auto *T =
5885 SubstBuiltinTemplatePackTypes.FindNodeOrInsertPos(ID, InsertPos))
5886 return QualType(T, 0);
5887
5888 QualType Canon;
5889 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
5890 if (!CanonArgPack.structurallyEquals(ArgPack))
5891 Canon = getSubstBuiltinTemplatePack(CanonArgPack);
5892
5893 auto *PackType = new (*this, alignof(SubstBuiltinTemplatePackType))
5894 SubstBuiltinTemplatePackType(Canon, ArgPack);
5895 Types.push_back(PackType);
5896 SubstBuiltinTemplatePackTypes.InsertNode(PackType, InsertPos);
5897 return QualType(PackType, 0);
5898}
5899
5900/// Retrieve the template type parameter type for a template
5901/// parameter or parameter pack with the given depth, index, and (optionally)
5902/// name.
5903QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
5904 bool ParameterPack,
5905 TemplateTypeParmDecl *TTPDecl) const {
5906 llvm::FoldingSetNodeID ID;
5907 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
5908 void *InsertPos = nullptr;
5909 TemplateTypeParmType *TypeParm
5910 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5911
5912 if (TypeParm)
5913 return QualType(TypeParm, 0);
5914
5915 if (TTPDecl) {
5916 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
5917 TypeParm = new (*this, alignof(TemplateTypeParmType))
5918 TemplateTypeParmType(Depth, Index, ParameterPack, TTPDecl, Canon);
5919
5920 TemplateTypeParmType *TypeCheck
5921 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5922 assert(!TypeCheck && "Template type parameter canonical type broken");
5923 (void)TypeCheck;
5924 } else
5925 TypeParm = new (*this, alignof(TemplateTypeParmType)) TemplateTypeParmType(
5926 Depth, Index, ParameterPack, /*TTPDecl=*/nullptr, /*Canon=*/QualType());
5927
5928 Types.push_back(TypeParm);
5929 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
5930
5931 return QualType(TypeParm, 0);
5932}
5933
5936 switch (Keyword) {
5937 // These are just themselves.
5943 return Keyword;
5944
5945 // These are equivalent.
5948
5949 // These are functionally equivalent, so relying on their equivalence is
5950 // IFNDR. By making them equivalent, we disallow overloading, which at least
5951 // can produce a diagnostic.
5954 }
5955 llvm_unreachable("unexpected keyword kind");
5956}
5957
5959 ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc,
5960 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc,
5961 TemplateName Name, SourceLocation NameLoc,
5962 const TemplateArgumentListInfo &SpecifiedArgs,
5963 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
5965 Keyword, Name, SpecifiedArgs.arguments(), CanonicalArgs, Underlying);
5966
5969 ElaboratedKeywordLoc, QualifierLoc, TemplateKeywordLoc, NameLoc,
5970 SpecifiedArgs);
5971 return DI;
5972}
5973
5976 ArrayRef<TemplateArgumentLoc> SpecifiedArgs,
5977 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
5978 SmallVector<TemplateArgument, 4> SpecifiedArgVec;
5979 SpecifiedArgVec.reserve(SpecifiedArgs.size());
5980 for (const TemplateArgumentLoc &Arg : SpecifiedArgs)
5981 SpecifiedArgVec.push_back(Arg.getArgument());
5982
5983 return getTemplateSpecializationType(Keyword, Template, SpecifiedArgVec,
5984 CanonicalArgs, Underlying);
5985}
5986
5987[[maybe_unused]] static bool
5989 for (const TemplateArgument &Arg : Args)
5990 if (Arg.isPackExpansion())
5991 return true;
5992 return false;
5993}
5994
5997 ArrayRef<TemplateArgument> Args) const {
5998 assert(Template ==
5999 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true));
6001 Template.getAsDependentTemplateName()));
6002#ifndef NDEBUG
6003 for (const auto &Arg : Args)
6004 assert(Arg.structurallyEquals(getCanonicalTemplateArgument(Arg)));
6005#endif
6006
6007 llvm::FoldingSetNodeID ID;
6008 TemplateSpecializationType::Profile(ID, Keyword, Template, Args, QualType(),
6009 *this);
6010 void *InsertPos = nullptr;
6011 if (auto *T = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6012 return QualType(T, 0);
6013
6014 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
6015 sizeof(TemplateArgument) * Args.size(),
6016 alignof(TemplateSpecializationType));
6017 auto *Spec =
6018 new (Mem) TemplateSpecializationType(Keyword, Template,
6019 /*IsAlias=*/false, Args, QualType());
6020 assert(Spec->isDependentType() &&
6021 "canonical template specialization must be dependent");
6022 Types.push_back(Spec);
6023 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
6024 return QualType(Spec, 0);
6025}
6026
6029 ArrayRef<TemplateArgument> SpecifiedArgs,
6030 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6031 const auto *TD = Template.getAsTemplateDecl(/*IgnoreDeduced=*/true);
6032 bool IsTypeAlias = TD && TD->isTypeAlias();
6033 if (Underlying.isNull()) {
6034 TemplateName CanonTemplate =
6035 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true);
6036 ElaboratedTypeKeyword CanonKeyword =
6037 CanonTemplate.getAsDependentTemplateName()
6040 bool NonCanonical = Template != CanonTemplate || Keyword != CanonKeyword;
6042 if (CanonicalArgs.empty()) {
6043 CanonArgsVec = SmallVector<TemplateArgument, 4>(SpecifiedArgs);
6044 NonCanonical |= canonicalizeTemplateArguments(CanonArgsVec);
6045 CanonicalArgs = CanonArgsVec;
6046 } else {
6047 NonCanonical |= !llvm::equal(
6048 SpecifiedArgs, CanonicalArgs,
6049 [](const TemplateArgument &A, const TemplateArgument &B) {
6050 return A.structurallyEquals(B);
6051 });
6052 }
6053
6054 // We can get here with an alias template when the specialization
6055 // contains a pack expansion that does not match up with a parameter
6056 // pack, or a builtin template which cannot be resolved due to dependency.
6057 assert((!isa_and_nonnull<TypeAliasTemplateDecl>(TD) ||
6058 hasAnyPackExpansions(CanonicalArgs)) &&
6059 "Caller must compute aliased type");
6060 IsTypeAlias = false;
6061
6063 CanonKeyword, CanonTemplate, CanonicalArgs);
6064 if (!NonCanonical)
6065 return Underlying;
6066 }
6067 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
6068 sizeof(TemplateArgument) * SpecifiedArgs.size() +
6069 (IsTypeAlias ? sizeof(QualType) : 0),
6070 alignof(TemplateSpecializationType));
6071 auto *Spec = new (Mem) TemplateSpecializationType(
6072 Keyword, Template, IsTypeAlias, SpecifiedArgs, Underlying);
6073 Types.push_back(Spec);
6074 return QualType(Spec, 0);
6075}
6076
6079 llvm::FoldingSetNodeID ID;
6080 ParenType::Profile(ID, InnerType);
6081
6082 void *InsertPos = nullptr;
6083 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6084 if (T)
6085 return QualType(T, 0);
6086
6087 QualType Canon = InnerType;
6088 if (!Canon.isCanonical()) {
6089 Canon = getCanonicalType(InnerType);
6090 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6091 assert(!CheckT && "Paren canonical type broken");
6092 (void)CheckT;
6093 }
6094
6095 T = new (*this, alignof(ParenType)) ParenType(InnerType, Canon);
6096 Types.push_back(T);
6097 ParenTypes.InsertNode(T, InsertPos);
6098 return QualType(T, 0);
6099}
6100
6103 const IdentifierInfo *MacroII) const {
6104 QualType Canon = UnderlyingTy;
6105 if (!Canon.isCanonical())
6106 Canon = getCanonicalType(UnderlyingTy);
6107
6108 auto *newType = new (*this, alignof(MacroQualifiedType))
6109 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
6110 Types.push_back(newType);
6111 return QualType(newType, 0);
6112}
6113
6116 const IdentifierInfo *Name) const {
6117 llvm::FoldingSetNodeID ID;
6118 DependentNameType::Profile(ID, Keyword, NNS, Name);
6119
6120 void *InsertPos = nullptr;
6121 if (DependentNameType *T =
6122 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos))
6123 return QualType(T, 0);
6124
6125 ElaboratedTypeKeyword CanonKeyword =
6127 NestedNameSpecifier CanonNNS = NNS.getCanonical();
6128
6129 QualType Canon;
6130 if (CanonKeyword != Keyword || CanonNNS != NNS) {
6131 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
6132 [[maybe_unused]] DependentNameType *T =
6133 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
6134 assert(!T && "broken canonicalization");
6135 assert(Canon.isCanonical());
6136 }
6137
6138 DependentNameType *T = new (*this, alignof(DependentNameType))
6139 DependentNameType(Keyword, NNS, Name, Canon);
6140 Types.push_back(T);
6141 DependentNameTypes.InsertNode(T, InsertPos);
6142 return QualType(T, 0);
6143}
6144
6146 TemplateArgument Arg;
6147 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6149 if (TTP->isParameterPack())
6150 ArgType = getPackExpansionType(ArgType, std::nullopt);
6151
6153 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6154 QualType T =
6155 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
6156 // For class NTTPs, ensure we include the 'const' so the type matches that
6157 // of a real template argument.
6158 // FIXME: It would be more faithful to model this as something like an
6159 // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
6161 if (T->isRecordType()) {
6162 // C++ [temp.param]p8: An id-expression naming a non-type
6163 // template-parameter of class type T denotes a static storage duration
6164 // object of type const T.
6165 T.addConst();
6166 VK = VK_LValue;
6167 } else {
6168 VK = Expr::getValueKindForType(NTTP->getType());
6169 }
6170 Expr *E = new (*this)
6171 DeclRefExpr(*this, NTTP, /*RefersToEnclosingVariableOrCapture=*/false,
6172 T, VK, NTTP->getLocation());
6173
6174 if (NTTP->isParameterPack())
6175 E = new (*this) PackExpansionExpr(E, NTTP->getLocation(), std::nullopt);
6176 Arg = TemplateArgument(E, /*IsCanonical=*/false);
6177 } else {
6178 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
6180 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
6181 TemplateName(TTP));
6182 if (TTP->isParameterPack())
6183 Arg = TemplateArgument(Name, /*NumExpansions=*/std::nullopt);
6184 else
6185 Arg = TemplateArgument(Name);
6186 }
6187
6188 if (Param->isTemplateParameterPack())
6189 Arg =
6190 TemplateArgument::CreatePackCopy(const_cast<ASTContext &>(*this), Arg);
6191
6192 return Arg;
6193}
6194
6196 UnsignedOrNone NumExpansions,
6197 bool ExpectPackInType) const {
6198 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
6199 "Pack expansions must expand one or more parameter packs");
6200
6201 llvm::FoldingSetNodeID ID;
6202 PackExpansionType::Profile(ID, Pattern, NumExpansions);
6203
6204 void *InsertPos = nullptr;
6205 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6206 if (T)
6207 return QualType(T, 0);
6208
6209 QualType Canon;
6210 if (!Pattern.isCanonical()) {
6211 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
6212 /*ExpectPackInType=*/false);
6213
6214 // Find the insert position again, in case we inserted an element into
6215 // PackExpansionTypes and invalidated our insert position.
6216 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6217 }
6218
6219 T = new (*this, alignof(PackExpansionType))
6220 PackExpansionType(Pattern, Canon, NumExpansions);
6221 Types.push_back(T);
6222 PackExpansionTypes.InsertNode(T, InsertPos);
6223 return QualType(T, 0);
6224}
6225
6226/// CmpProtocolNames - Comparison predicate for sorting protocols
6227/// alphabetically.
6228static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
6229 ObjCProtocolDecl *const *RHS) {
6230 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
6231}
6232
6234 if (Protocols.empty()) return true;
6235
6236 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
6237 return false;
6238
6239 for (unsigned i = 1; i != Protocols.size(); ++i)
6240 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
6241 Protocols[i]->getCanonicalDecl() != Protocols[i])
6242 return false;
6243 return true;
6244}
6245
6246static void
6248 // Sort protocols, keyed by name.
6249 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
6250
6251 // Canonicalize.
6252 for (ObjCProtocolDecl *&P : Protocols)
6253 P = P->getCanonicalDecl();
6254
6255 // Remove duplicates.
6256 auto ProtocolsEnd = llvm::unique(Protocols);
6257 Protocols.erase(ProtocolsEnd, Protocols.end());
6258}
6259
6261 ObjCProtocolDecl * const *Protocols,
6262 unsigned NumProtocols) const {
6263 return getObjCObjectType(BaseType, {}, ArrayRef(Protocols, NumProtocols),
6264 /*isKindOf=*/false);
6265}
6266
6268 QualType baseType,
6269 ArrayRef<QualType> typeArgs,
6271 bool isKindOf) const {
6272 // If the base type is an interface and there aren't any protocols or
6273 // type arguments to add, then the interface type will do just fine.
6274 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
6275 isa<ObjCInterfaceType>(baseType))
6276 return baseType;
6277
6278 // Look in the folding set for an existing type.
6279 llvm::FoldingSetNodeID ID;
6280 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
6281 void *InsertPos = nullptr;
6282 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
6283 return QualType(QT, 0);
6284
6285 // Determine the type arguments to be used for canonicalization,
6286 // which may be explicitly specified here or written on the base
6287 // type.
6288 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
6289 if (effectiveTypeArgs.empty()) {
6290 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
6291 effectiveTypeArgs = baseObject->getTypeArgs();
6292 }
6293
6294 // Build the canonical type, which has the canonical base type and a
6295 // sorted-and-uniqued list of protocols and the type arguments
6296 // canonicalized.
6297 QualType canonical;
6298 bool typeArgsAreCanonical = llvm::all_of(
6299 effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); });
6300 bool protocolsSorted = areSortedAndUniqued(protocols);
6301 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
6302 // Determine the canonical type arguments.
6303 ArrayRef<QualType> canonTypeArgs;
6304 SmallVector<QualType, 4> canonTypeArgsVec;
6305 if (!typeArgsAreCanonical) {
6306 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
6307 for (auto typeArg : effectiveTypeArgs)
6308 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
6309 canonTypeArgs = canonTypeArgsVec;
6310 } else {
6311 canonTypeArgs = effectiveTypeArgs;
6312 }
6313
6314 ArrayRef<ObjCProtocolDecl *> canonProtocols;
6315 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
6316 if (!protocolsSorted) {
6317 canonProtocolsVec.append(protocols.begin(), protocols.end());
6318 SortAndUniqueProtocols(canonProtocolsVec);
6319 canonProtocols = canonProtocolsVec;
6320 } else {
6321 canonProtocols = protocols;
6322 }
6323
6324 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
6325 canonProtocols, isKindOf);
6326
6327 // Regenerate InsertPos.
6328 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
6329 }
6330
6331 unsigned size = sizeof(ObjCObjectTypeImpl);
6332 size += typeArgs.size() * sizeof(QualType);
6333 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6334 void *mem = Allocate(size, alignof(ObjCObjectTypeImpl));
6335 auto *T =
6336 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
6337 isKindOf);
6338
6339 Types.push_back(T);
6340 ObjCObjectTypes.InsertNode(T, InsertPos);
6341 return QualType(T, 0);
6342}
6343
6344/// Apply Objective-C protocol qualifiers to the given type.
6345/// If this is for the canonical type of a type parameter, we can apply
6346/// protocol qualifiers on the ObjCObjectPointerType.
6349 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
6350 bool allowOnPointerType) const {
6351 hasError = false;
6352
6353 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
6354 return getObjCTypeParamType(objT->getDecl(), protocols);
6355 }
6356
6357 // Apply protocol qualifiers to ObjCObjectPointerType.
6358 if (allowOnPointerType) {
6359 if (const auto *objPtr =
6360 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
6361 const ObjCObjectType *objT = objPtr->getObjectType();
6362 // Merge protocol lists and construct ObjCObjectType.
6364 protocolsVec.append(objT->qual_begin(),
6365 objT->qual_end());
6366 protocolsVec.append(protocols.begin(), protocols.end());
6367 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
6369 objT->getBaseType(),
6370 objT->getTypeArgsAsWritten(),
6371 protocols,
6372 objT->isKindOfTypeAsWritten());
6374 }
6375 }
6376
6377 // Apply protocol qualifiers to ObjCObjectType.
6378 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
6379 // FIXME: Check for protocols to which the class type is already
6380 // known to conform.
6381
6382 return getObjCObjectType(objT->getBaseType(),
6383 objT->getTypeArgsAsWritten(),
6384 protocols,
6385 objT->isKindOfTypeAsWritten());
6386 }
6387
6388 // If the canonical type is ObjCObjectType, ...
6389 if (type->isObjCObjectType()) {
6390 // Silently overwrite any existing protocol qualifiers.
6391 // TODO: determine whether that's the right thing to do.
6392
6393 // FIXME: Check for protocols to which the class type is already
6394 // known to conform.
6395 return getObjCObjectType(type, {}, protocols, false);
6396 }
6397
6398 // id<protocol-list>
6399 if (type->isObjCIdType()) {
6400 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6401 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
6402 objPtr->isKindOfType());
6404 }
6405
6406 // Class<protocol-list>
6407 if (type->isObjCClassType()) {
6408 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6409 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
6410 objPtr->isKindOfType());
6412 }
6413
6414 hasError = true;
6415 return type;
6416}
6417
6420 ArrayRef<ObjCProtocolDecl *> protocols) const {
6421 // Look in the folding set for an existing type.
6422 llvm::FoldingSetNodeID ID;
6423 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
6424 void *InsertPos = nullptr;
6425 if (ObjCTypeParamType *TypeParam =
6426 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
6427 return QualType(TypeParam, 0);
6428
6429 // We canonicalize to the underlying type.
6430 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
6431 if (!protocols.empty()) {
6432 // Apply the protocol qualifers.
6433 bool hasError;
6435 Canonical, protocols, hasError, true /*allowOnPointerType*/));
6436 assert(!hasError && "Error when apply protocol qualifier to bound type");
6437 }
6438
6439 unsigned size = sizeof(ObjCTypeParamType);
6440 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6441 void *mem = Allocate(size, alignof(ObjCTypeParamType));
6442 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
6443
6444 Types.push_back(newType);
6445 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
6446 return QualType(newType, 0);
6447}
6448
6450 ObjCTypeParamDecl *New) const {
6451 New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType()));
6452 // Update TypeForDecl after updating TypeSourceInfo.
6453 auto *NewTypeParamTy = cast<ObjCTypeParamType>(New->TypeForDecl);
6455 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
6456 QualType UpdatedTy = getObjCTypeParamType(New, protocols);
6457 New->TypeForDecl = UpdatedTy.getTypePtr();
6458}
6459
6460/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
6461/// protocol list adopt all protocols in QT's qualified-id protocol
6462/// list.
6464 ObjCInterfaceDecl *IC) {
6465 if (!QT->isObjCQualifiedIdType())
6466 return false;
6467
6468 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
6469 // If both the right and left sides have qualifiers.
6470 for (auto *Proto : OPT->quals()) {
6471 if (!IC->ClassImplementsProtocol(Proto, false))
6472 return false;
6473 }
6474 return true;
6475 }
6476 return false;
6477}
6478
6479/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
6480/// QT's qualified-id protocol list adopt all protocols in IDecl's list
6481/// of protocols.
6483 ObjCInterfaceDecl *IDecl) {
6484 if (!QT->isObjCQualifiedIdType())
6485 return false;
6486 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
6487 if (!OPT)
6488 return false;
6489 if (!IDecl->hasDefinition())
6490 return false;
6492 CollectInheritedProtocols(IDecl, InheritedProtocols);
6493 if (InheritedProtocols.empty())
6494 return false;
6495 // Check that if every protocol in list of id<plist> conforms to a protocol
6496 // of IDecl's, then bridge casting is ok.
6497 bool Conforms = false;
6498 for (auto *Proto : OPT->quals()) {
6499 Conforms = false;
6500 for (auto *PI : InheritedProtocols) {
6501 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
6502 Conforms = true;
6503 break;
6504 }
6505 }
6506 if (!Conforms)
6507 break;
6508 }
6509 if (Conforms)
6510 return true;
6511
6512 for (auto *PI : InheritedProtocols) {
6513 // If both the right and left sides have qualifiers.
6514 bool Adopts = false;
6515 for (auto *Proto : OPT->quals()) {
6516 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
6517 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
6518 break;
6519 }
6520 if (!Adopts)
6521 return false;
6522 }
6523 return true;
6524}
6525
6526/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
6527/// the given object type.
6529 llvm::FoldingSetNodeID ID;
6530 ObjCObjectPointerType::Profile(ID, ObjectT);
6531
6532 void *InsertPos = nullptr;
6533 if (ObjCObjectPointerType *QT =
6534 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
6535 return QualType(QT, 0);
6536
6537 // Find the canonical object type.
6538 QualType Canonical;
6539 if (!ObjectT.isCanonical()) {
6540 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
6541
6542 // Regenerate InsertPos.
6543 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
6544 }
6545
6546 // No match.
6547 void *Mem =
6549 auto *QType =
6550 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
6551
6552 Types.push_back(QType);
6553 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
6554 return QualType(QType, 0);
6555}
6556
6557/// getObjCInterfaceType - Return the unique reference to the type for the
6558/// specified ObjC interface decl. The list of protocols is optional.
6560 ObjCInterfaceDecl *PrevDecl) const {
6561 if (Decl->TypeForDecl)
6562 return QualType(Decl->TypeForDecl, 0);
6563
6564 if (PrevDecl) {
6565 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
6566 Decl->TypeForDecl = PrevDecl->TypeForDecl;
6567 return QualType(PrevDecl->TypeForDecl, 0);
6568 }
6569
6570 // Prefer the definition, if there is one.
6571 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
6572 Decl = Def;
6573
6574 void *Mem = Allocate(sizeof(ObjCInterfaceType), alignof(ObjCInterfaceType));
6575 auto *T = new (Mem) ObjCInterfaceType(Decl);
6576 Decl->TypeForDecl = T;
6577 Types.push_back(T);
6578 return QualType(T, 0);
6579}
6580
6581/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
6582/// TypeOfExprType AST's (since expression's are never shared). For example,
6583/// multiple declarations that refer to "typeof(x)" all contain different
6584/// DeclRefExpr's. This doesn't effect the type checker, since it operates
6585/// on canonical type's (which are always unique).
6587 TypeOfExprType *toe;
6588 if (tofExpr->isTypeDependent()) {
6589 llvm::FoldingSetNodeID ID;
6590 DependentTypeOfExprType::Profile(ID, *this, tofExpr,
6591 Kind == TypeOfKind::Unqualified);
6592
6593 void *InsertPos = nullptr;
6595 DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
6596 if (Canon) {
6597 // We already have a "canonical" version of an identical, dependent
6598 // typeof(expr) type. Use that as our canonical type.
6599 toe = new (*this, alignof(TypeOfExprType)) TypeOfExprType(
6600 *this, tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
6601 } else {
6602 // Build a new, canonical typeof(expr) type.
6603 Canon = new (*this, alignof(DependentTypeOfExprType))
6604 DependentTypeOfExprType(*this, tofExpr, Kind);
6605 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
6606 toe = Canon;
6607 }
6608 } else {
6609 QualType Canonical = getCanonicalType(tofExpr->getType());
6610 toe = new (*this, alignof(TypeOfExprType))
6611 TypeOfExprType(*this, tofExpr, Kind, Canonical);
6612 }
6613 Types.push_back(toe);
6614 return QualType(toe, 0);
6615}
6616
6617/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
6618/// TypeOfType nodes. The only motivation to unique these nodes would be
6619/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
6620/// an issue. This doesn't affect the type checker, since it operates
6621/// on canonical types (which are always unique).
6623 QualType Canonical = getCanonicalType(tofType);
6624 auto *tot = new (*this, alignof(TypeOfType))
6625 TypeOfType(*this, tofType, Canonical, Kind);
6626 Types.push_back(tot);
6627 return QualType(tot, 0);
6628}
6629
6630/// getReferenceQualifiedType - Given an expr, will return the type for
6631/// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
6632/// and class member access into account.
6634 // C++11 [dcl.type.simple]p4:
6635 // [...]
6636 QualType T = E->getType();
6637 switch (E->getValueKind()) {
6638 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6639 // type of e;
6640 case VK_XValue:
6641 return getRValueReferenceType(T);
6642 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6643 // type of e;
6644 case VK_LValue:
6645 return getLValueReferenceType(T);
6646 // - otherwise, decltype(e) is the type of e.
6647 case VK_PRValue:
6648 return T;
6649 }
6650 llvm_unreachable("Unknown value kind");
6651}
6652
6653/// Unlike many "get<Type>" functions, we don't unique DecltypeType
6654/// nodes. This would never be helpful, since each such type has its own
6655/// expression, and would not give a significant memory saving, since there
6656/// is an Expr tree under each such type.
6658 // C++11 [temp.type]p2:
6659 // If an expression e involves a template parameter, decltype(e) denotes a
6660 // unique dependent type. Two such decltype-specifiers refer to the same
6661 // type only if their expressions are equivalent (14.5.6.1).
6662 QualType CanonType;
6663 if (!E->isInstantiationDependent()) {
6664 CanonType = getCanonicalType(UnderlyingType);
6665 } else if (!UnderlyingType.isNull()) {
6666 CanonType = getDecltypeType(E, QualType());
6667 } else {
6668 llvm::FoldingSetNodeID ID;
6669 DependentDecltypeType::Profile(ID, *this, E);
6670
6671 void *InsertPos = nullptr;
6672 if (DependentDecltypeType *Canon =
6673 DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos))
6674 return QualType(Canon, 0);
6675
6676 // Build a new, canonical decltype(expr) type.
6677 auto *DT =
6678 new (*this, alignof(DependentDecltypeType)) DependentDecltypeType(E);
6679 DependentDecltypeTypes.InsertNode(DT, InsertPos);
6680 Types.push_back(DT);
6681 return QualType(DT, 0);
6682 }
6683 auto *DT = new (*this, alignof(DecltypeType))
6684 DecltypeType(E, UnderlyingType, CanonType);
6685 Types.push_back(DT);
6686 return QualType(DT, 0);
6687}
6688
6690 bool FullySubstituted,
6691 ArrayRef<QualType> Expansions,
6692 UnsignedOrNone Index) const {
6693 QualType Canonical;
6694 if (FullySubstituted && Index) {
6695 Canonical = getCanonicalType(Expansions[*Index]);
6696 } else {
6697 llvm::FoldingSetNodeID ID;
6698 PackIndexingType::Profile(ID, *this, Pattern.getCanonicalType(), IndexExpr,
6699 FullySubstituted, Expansions);
6700 void *InsertPos = nullptr;
6701 PackIndexingType *Canon =
6702 DependentPackIndexingTypes.FindNodeOrInsertPos(ID, InsertPos);
6703 if (!Canon) {
6704 void *Mem = Allocate(
6705 PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6707 Canon =
6708 new (Mem) PackIndexingType(QualType(), Pattern.getCanonicalType(),
6709 IndexExpr, FullySubstituted, Expansions);
6710 DependentPackIndexingTypes.InsertNode(Canon, InsertPos);
6711 }
6712 Canonical = QualType(Canon, 0);
6713 }
6714
6715 void *Mem =
6716 Allocate(PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6718 auto *T = new (Mem) PackIndexingType(Canonical, Pattern, IndexExpr,
6719 FullySubstituted, Expansions);
6720 Types.push_back(T);
6721 return QualType(T, 0);
6722}
6723
6724/// getUnaryTransformationType - We don't unique these, since the memory
6725/// savings are minimal and these are rare.
6728 UnaryTransformType::UTTKind Kind) const {
6729
6730 llvm::FoldingSetNodeID ID;
6731 UnaryTransformType::Profile(ID, BaseType, UnderlyingType, Kind);
6732
6733 void *InsertPos = nullptr;
6734 if (UnaryTransformType *UT =
6735 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos))
6736 return QualType(UT, 0);
6737
6738 QualType CanonType;
6739 if (!BaseType->isDependentType()) {
6740 CanonType = UnderlyingType.getCanonicalType();
6741 } else {
6742 assert(UnderlyingType.isNull() || BaseType == UnderlyingType);
6743 UnderlyingType = QualType();
6744 if (QualType CanonBase = BaseType.getCanonicalType();
6745 BaseType != CanonBase) {
6746 CanonType = getUnaryTransformType(CanonBase, QualType(), Kind);
6747 assert(CanonType.isCanonical());
6748
6749 // Find the insertion position again.
6750 [[maybe_unused]] UnaryTransformType *UT =
6751 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
6752 assert(!UT && "broken canonicalization");
6753 }
6754 }
6755
6756 auto *UT = new (*this, alignof(UnaryTransformType))
6757 UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType);
6758 UnaryTransformTypes.InsertNode(UT, InsertPos);
6759 Types.push_back(UT);
6760 return QualType(UT, 0);
6761}
6762
6763QualType ASTContext::getAutoTypeInternal(
6764 QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent,
6765 bool IsPack, TemplateDecl *TypeConstraintConcept,
6766 ArrayRef<TemplateArgument> TypeConstraintArgs, bool IsCanon) const {
6767 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto &&
6768 !TypeConstraintConcept && !IsDependent)
6769 return getAutoDeductType();
6770
6771 // Look in the folding set for an existing type.
6772 llvm::FoldingSetNodeID ID;
6773 bool IsDeducedDependent =
6774 isa_and_nonnull<TemplateTemplateParmDecl>(TypeConstraintConcept) ||
6775 (!DeducedType.isNull() && DeducedType->isDependentType());
6776 AutoType::Profile(ID, *this, DeducedType, Keyword,
6777 IsDependent || IsDeducedDependent, TypeConstraintConcept,
6778 TypeConstraintArgs);
6779 if (auto const AT_iter = AutoTypes.find(ID); AT_iter != AutoTypes.end())
6780 return QualType(AT_iter->getSecond(), 0);
6781
6782 QualType Canon;
6783 if (!IsCanon) {
6784 if (!DeducedType.isNull()) {
6785 Canon = DeducedType.getCanonicalType();
6786 } else if (TypeConstraintConcept) {
6787 bool AnyNonCanonArgs = false;
6788 auto *CanonicalConcept =
6789 cast<TemplateDecl>(TypeConstraintConcept->getCanonicalDecl());
6790 auto CanonicalConceptArgs = ::getCanonicalTemplateArguments(
6791 *this, TypeConstraintArgs, AnyNonCanonArgs);
6792 if (CanonicalConcept != TypeConstraintConcept || AnyNonCanonArgs) {
6793 Canon = getAutoTypeInternal(QualType(), Keyword, IsDependent, IsPack,
6794 CanonicalConcept, CanonicalConceptArgs,
6795 /*IsCanon=*/true);
6796 }
6797 }
6798 }
6799
6800 void *Mem = Allocate(sizeof(AutoType) +
6801 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
6802 alignof(AutoType));
6803 auto *AT = new (Mem) AutoType(
6804 DeducedType, Keyword,
6805 (IsDependent ? TypeDependence::DependentInstantiation
6806 : TypeDependence::None) |
6807 (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None),
6808 Canon, TypeConstraintConcept, TypeConstraintArgs);
6809#ifndef NDEBUG
6810 llvm::FoldingSetNodeID InsertedID;
6811 AT->Profile(InsertedID, *this);
6812 assert(InsertedID == ID && "ID does not match");
6813#endif
6814 Types.push_back(AT);
6815 AutoTypes.try_emplace(ID, AT);
6816 return QualType(AT, 0);
6817}
6818
6819/// getAutoType - Return the uniqued reference to the 'auto' type which has been
6820/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
6821/// canonical deduced-but-dependent 'auto' type.
6822QualType
6824 bool IsDependent, bool IsPack,
6825 TemplateDecl *TypeConstraintConcept,
6826 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
6827 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
6828 assert((!IsDependent || DeducedType.isNull()) &&
6829 "A dependent auto should be undeduced");
6830 return getAutoTypeInternal(DeducedType, Keyword, IsDependent, IsPack,
6831 TypeConstraintConcept, TypeConstraintArgs);
6832}
6833
6835 QualType CanonT = T.getNonPackExpansionType().getCanonicalType();
6836
6837 // Remove a type-constraint from a top-level auto or decltype(auto).
6838 if (auto *AT = CanonT->getAs<AutoType>()) {
6839 if (!AT->isConstrained())
6840 return T;
6841 return getQualifiedType(getAutoType(QualType(), AT->getKeyword(),
6842 AT->isDependentType(),
6843 AT->containsUnexpandedParameterPack()),
6844 T.getQualifiers());
6845 }
6846
6847 // FIXME: We only support constrained auto at the top level in the type of a
6848 // non-type template parameter at the moment. Once we lift that restriction,
6849 // we'll need to recursively build types containing auto here.
6850 assert(!CanonT->getContainedAutoType() ||
6851 !CanonT->getContainedAutoType()->isConstrained());
6852 return T;
6853}
6854
6855QualType ASTContext::getDeducedTemplateSpecializationTypeInternal(
6857 bool IsDependent, QualType Canon) const {
6858 // Look in the folding set for an existing type.
6859 void *InsertPos = nullptr;
6860 llvm::FoldingSetNodeID ID;
6861 DeducedTemplateSpecializationType::Profile(ID, Keyword, Template, DeducedType,
6862 IsDependent);
6863 if (DeducedTemplateSpecializationType *DTST =
6864 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6865 return QualType(DTST, 0);
6866
6867 auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType))
6868 DeducedTemplateSpecializationType(Keyword, Template, DeducedType,
6869 IsDependent, Canon);
6870
6871#ifndef NDEBUG
6872 llvm::FoldingSetNodeID TempID;
6873 DTST->Profile(TempID);
6874 assert(ID == TempID && "ID does not match");
6875#endif
6876 Types.push_back(DTST);
6877 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
6878 return QualType(DTST, 0);
6879}
6880
6881/// Return the uniqued reference to the deduced template specialization type
6882/// which has been deduced to the given type, or to the canonical undeduced
6883/// such type, or the canonical deduced-but-dependent such type.
6886 bool IsDependent) const {
6887 // FIXME: This could save an extra hash table lookup if it handled all the
6888 // parameters already being canonical.
6889 // FIXME: Can this be formed from a DependentTemplateName, such that the
6890 // keyword should be part of the canonical type?
6891 QualType Canon =
6892 DeducedType.isNull()
6893 ? getDeducedTemplateSpecializationTypeInternal(
6895 QualType(), IsDependent, QualType())
6896 : DeducedType.getCanonicalType();
6897 return getDeducedTemplateSpecializationTypeInternal(
6898 Keyword, Template, DeducedType, IsDependent, Canon);
6899}
6900
6901/// getAtomicType - Return the uniqued reference to the atomic type for
6902/// the given value type.
6904 // Unique pointers, to guarantee there is only one pointer of a particular
6905 // structure.
6906 llvm::FoldingSetNodeID ID;
6908
6909 void *InsertPos = nullptr;
6910 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
6911 return QualType(AT, 0);
6912
6913 // If the atomic value type isn't canonical, this won't be a canonical type
6914 // either, so fill in the canonical type field.
6915 QualType Canonical;
6916 if (!T.isCanonical()) {
6917 Canonical = getAtomicType(getCanonicalType(T));
6918
6919 // Get the new insert position for the node we care about.
6920 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
6921 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
6922 }
6923 auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
6924 Types.push_back(New);
6925 AtomicTypes.InsertNode(New, InsertPos);
6926 return QualType(New, 0);
6927}
6928
6929/// getAutoDeductType - Get type pattern for deducing against 'auto'.
6931 if (AutoDeductTy.isNull())
6932 AutoDeductTy = QualType(new (*this, alignof(AutoType))
6933 AutoType(QualType(), AutoTypeKeyword::Auto,
6934 TypeDependence::None, QualType(),
6935 /*concept*/ nullptr, /*args*/ {}),
6936 0);
6937 return AutoDeductTy;
6938}
6939
6940/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
6942 if (AutoRRefDeductTy.isNull())
6944 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
6945 return AutoRRefDeductTy;
6946}
6947
6948/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
6949/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
6950/// needs to agree with the definition in <stddef.h>.
6954
6956 return getFromTargetType(Target->getSizeType());
6957}
6958
6959/// Return the unique signed counterpart of the integer type
6960/// corresponding to size_t.
6964
6965/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
6966/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
6970
6971/// Return the unique unsigned counterpart of "ptrdiff_t"
6972/// integer type. The standard (C11 7.21.6.1p7) refers to this type
6973/// in the definition of %tu format specifier.
6975 return getFromTargetType(Target->getUnsignedPtrDiffType(LangAS::Default));
6976}
6977
6978/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
6980 return getFromTargetType(Target->getIntMaxType());
6981}
6982
6983/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
6985 return getFromTargetType(Target->getUIntMaxType());
6986}
6987
6988/// getSignedWCharType - Return the type of "signed wchar_t".
6989/// Used when in C++, as a GCC extension.
6991 // FIXME: derive from "Target" ?
6992 return WCharTy;
6993}
6994
6995/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
6996/// Used when in C++, as a GCC extension.
6998 // FIXME: derive from "Target" ?
6999 return UnsignedIntTy;
7000}
7001
7003 return getFromTargetType(Target->getIntPtrType());
7004}
7005
7009
7010/// Return the unique type for "pid_t" defined in
7011/// <sys/types.h>. We need this to compute the correct type for vfork().
7013 return getFromTargetType(Target->getProcessIDType());
7014}
7015
7016//===----------------------------------------------------------------------===//
7017// Type Operators
7018//===----------------------------------------------------------------------===//
7019
7021 // Push qualifiers into arrays, and then discard any remaining
7022 // qualifiers.
7023 T = getCanonicalType(T);
7025 const Type *Ty = T.getTypePtr();
7029 } else if (isa<ArrayType>(Ty)) {
7031 } else if (isa<FunctionType>(Ty)) {
7032 Result = getPointerType(QualType(Ty, 0));
7033 } else {
7034 Result = QualType(Ty, 0);
7035 }
7036
7038}
7039
7041 Qualifiers &quals) const {
7042 SplitQualType splitType = type.getSplitUnqualifiedType();
7043
7044 // FIXME: getSplitUnqualifiedType() actually walks all the way to
7045 // the unqualified desugared type and then drops it on the floor.
7046 // We then have to strip that sugar back off with
7047 // getUnqualifiedDesugaredType(), which is silly.
7048 const auto *AT =
7049 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
7050
7051 // If we don't have an array, just use the results in splitType.
7052 if (!AT) {
7053 quals = splitType.Quals;
7054 return QualType(splitType.Ty, 0);
7055 }
7056
7057 // Otherwise, recurse on the array's element type.
7058 QualType elementType = AT->getElementType();
7059 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
7060
7061 // If that didn't change the element type, AT has no qualifiers, so we
7062 // can just use the results in splitType.
7063 if (elementType == unqualElementType) {
7064 assert(quals.empty()); // from the recursive call
7065 quals = splitType.Quals;
7066 return QualType(splitType.Ty, 0);
7067 }
7068
7069 // Otherwise, add in the qualifiers from the outermost type, then
7070 // build the type back up.
7071 quals.addConsistentQualifiers(splitType.Quals);
7072
7073 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
7074 return getConstantArrayType(unqualElementType, CAT->getSize(),
7075 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
7076 }
7077
7078 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
7079 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
7080 }
7081
7082 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
7083 return getVariableArrayType(unqualElementType, VAT->getSizeExpr(),
7084 VAT->getSizeModifier(),
7085 VAT->getIndexTypeCVRQualifiers());
7086 }
7087
7088 const auto *DSAT = cast<DependentSizedArrayType>(AT);
7089 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
7090 DSAT->getSizeModifier(), 0);
7091}
7092
7093/// Attempt to unwrap two types that may both be array types with the same bound
7094/// (or both be array types of unknown bound) for the purpose of comparing the
7095/// cv-decomposition of two types per C++ [conv.qual].
7096///
7097/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7098/// C++20 [conv.qual], if permitted by the current language mode.
7100 bool AllowPiMismatch) const {
7101 while (true) {
7102 auto *AT1 = getAsArrayType(T1);
7103 if (!AT1)
7104 return;
7105
7106 auto *AT2 = getAsArrayType(T2);
7107 if (!AT2)
7108 return;
7109
7110 // If we don't have two array types with the same constant bound nor two
7111 // incomplete array types, we've unwrapped everything we can.
7112 // C++20 also permits one type to be a constant array type and the other
7113 // to be an incomplete array type.
7114 // FIXME: Consider also unwrapping array of unknown bound and VLA.
7115 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
7116 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
7117 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
7118 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7120 return;
7121 } else if (isa<IncompleteArrayType>(AT1)) {
7122 if (!(isa<IncompleteArrayType>(AT2) ||
7123 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7125 return;
7126 } else {
7127 return;
7128 }
7129
7130 T1 = AT1->getElementType();
7131 T2 = AT2->getElementType();
7132 }
7133}
7134
7135/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
7136///
7137/// If T1 and T2 are both pointer types of the same kind, or both array types
7138/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
7139/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
7140///
7141/// This function will typically be called in a loop that successively
7142/// "unwraps" pointer and pointer-to-member types to compare them at each
7143/// level.
7144///
7145/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7146/// C++20 [conv.qual], if permitted by the current language mode.
7147///
7148/// \return \c true if a pointer type was unwrapped, \c false if we reached a
7149/// pair of types that can't be unwrapped further.
7151 bool AllowPiMismatch) const {
7152 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
7153
7154 const auto *T1PtrType = T1->getAs<PointerType>();
7155 const auto *T2PtrType = T2->getAs<PointerType>();
7156 if (T1PtrType && T2PtrType) {
7157 T1 = T1PtrType->getPointeeType();
7158 T2 = T2PtrType->getPointeeType();
7159 return true;
7160 }
7161
7162 if (const auto *T1MPType = T1->getAs<MemberPointerType>(),
7163 *T2MPType = T2->getAs<MemberPointerType>();
7164 T1MPType && T2MPType) {
7165 if (auto *RD1 = T1MPType->getMostRecentCXXRecordDecl(),
7166 *RD2 = T2MPType->getMostRecentCXXRecordDecl();
7167 RD1 != RD2 && RD1->getCanonicalDecl() != RD2->getCanonicalDecl())
7168 return false;
7169 if (T1MPType->getQualifier().getCanonical() !=
7170 T2MPType->getQualifier().getCanonical())
7171 return false;
7172 T1 = T1MPType->getPointeeType();
7173 T2 = T2MPType->getPointeeType();
7174 return true;
7175 }
7176
7177 if (getLangOpts().ObjC) {
7178 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
7179 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
7180 if (T1OPType && T2OPType) {
7181 T1 = T1OPType->getPointeeType();
7182 T2 = T2OPType->getPointeeType();
7183 return true;
7184 }
7185 }
7186
7187 // FIXME: Block pointers, too?
7188
7189 return false;
7190}
7191
7193 while (true) {
7194 Qualifiers Quals;
7195 T1 = getUnqualifiedArrayType(T1, Quals);
7196 T2 = getUnqualifiedArrayType(T2, Quals);
7197 if (hasSameType(T1, T2))
7198 return true;
7199 if (!UnwrapSimilarTypes(T1, T2))
7200 return false;
7201 }
7202}
7203
7205 while (true) {
7206 Qualifiers Quals1, Quals2;
7207 T1 = getUnqualifiedArrayType(T1, Quals1);
7208 T2 = getUnqualifiedArrayType(T2, Quals2);
7209
7210 Quals1.removeCVRQualifiers();
7211 Quals2.removeCVRQualifiers();
7212 if (Quals1 != Quals2)
7213 return false;
7214
7215 if (hasSameType(T1, T2))
7216 return true;
7217
7218 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
7219 return false;
7220 }
7221}
7222
7225 SourceLocation NameLoc) const {
7226 switch (Name.getKind()) {
7229 // DNInfo work in progress: CHECKME: what about DNLoc?
7231 NameLoc);
7232
7235 // DNInfo work in progress: CHECKME: what about DNLoc?
7236 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
7237 }
7238
7241 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
7242 }
7243
7247 DeclarationName DName;
7248 if (const IdentifierInfo *II = TN.getIdentifier()) {
7249 DName = DeclarationNames.getIdentifier(II);
7250 return DeclarationNameInfo(DName, NameLoc);
7251 } else {
7252 DName = DeclarationNames.getCXXOperatorName(TN.getOperator());
7253 // DNInfo work in progress: FIXME: source locations?
7254 DeclarationNameLoc DNLoc =
7256 return DeclarationNameInfo(DName, NameLoc, DNLoc);
7257 }
7258 }
7259
7263 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
7264 NameLoc);
7265 }
7266
7271 NameLoc);
7272 }
7275 NameLoc);
7278 return getNameForTemplate(DTS->getUnderlying(), NameLoc);
7279 }
7280 }
7281
7282 llvm_unreachable("bad template name kind!");
7283}
7284
7285static const TemplateArgument *
7287 auto handleParam = [](auto *TP) -> const TemplateArgument * {
7288 if (!TP->hasDefaultArgument())
7289 return nullptr;
7290 return &TP->getDefaultArgument().getArgument();
7291 };
7292 switch (P->getKind()) {
7293 case NamedDecl::TemplateTypeParm:
7294 return handleParam(cast<TemplateTypeParmDecl>(P));
7295 case NamedDecl::NonTypeTemplateParm:
7296 return handleParam(cast<NonTypeTemplateParmDecl>(P));
7297 case NamedDecl::TemplateTemplateParm:
7298 return handleParam(cast<TemplateTemplateParmDecl>(P));
7299 default:
7300 llvm_unreachable("Unexpected template parameter kind");
7301 }
7302}
7303
7305 bool IgnoreDeduced) const {
7306 while (std::optional<TemplateName> UnderlyingOrNone =
7307 Name.desugar(IgnoreDeduced))
7308 Name = *UnderlyingOrNone;
7309
7310 switch (Name.getKind()) {
7313 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
7315
7316 // The canonical template name is the canonical template declaration.
7317 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
7318 }
7319
7322 llvm_unreachable("cannot canonicalize unresolved template");
7323
7326 assert(DTN && "Non-dependent template names must refer to template decls.");
7327 NestedNameSpecifier Qualifier = DTN->getQualifier();
7328 NestedNameSpecifier CanonQualifier = Qualifier.getCanonical();
7329 if (Qualifier != CanonQualifier || !DTN->hasTemplateKeyword())
7330 return getDependentTemplateName({CanonQualifier, DTN->getName(),
7331 /*HasTemplateKeyword=*/true});
7332 return Name;
7333 }
7334
7338 TemplateArgument canonArgPack =
7341 canonArgPack, subst->getAssociatedDecl()->getCanonicalDecl(),
7342 subst->getIndex(), subst->getFinal());
7343 }
7345 assert(IgnoreDeduced == false);
7347 DefaultArguments DefArgs = DTS->getDefaultArguments();
7348 TemplateName Underlying = DTS->getUnderlying();
7349
7350 TemplateName CanonUnderlying =
7351 getCanonicalTemplateName(Underlying, /*IgnoreDeduced=*/true);
7352 bool NonCanonical = CanonUnderlying != Underlying;
7353 auto CanonArgs =
7354 getCanonicalTemplateArguments(*this, DefArgs.Args, NonCanonical);
7355
7356 ArrayRef<NamedDecl *> Params =
7357 CanonUnderlying.getAsTemplateDecl()->getTemplateParameters()->asArray();
7358 assert(CanonArgs.size() <= Params.size());
7359 // A deduced template name which deduces the same default arguments already
7360 // declared in the underlying template is the same template as the
7361 // underlying template. We need need to note any arguments which differ from
7362 // the corresponding declaration. If any argument differs, we must build a
7363 // deduced template name.
7364 for (int I = CanonArgs.size() - 1; I >= 0; --I) {
7366 if (!A)
7367 break;
7368 auto CanonParamDefArg = getCanonicalTemplateArgument(*A);
7369 TemplateArgument &CanonDefArg = CanonArgs[I];
7370 if (CanonDefArg.structurallyEquals(CanonParamDefArg))
7371 continue;
7372 // Keep popping from the back any deault arguments which are the same.
7373 if (I == int(CanonArgs.size() - 1))
7374 CanonArgs.pop_back();
7375 NonCanonical = true;
7376 }
7377 return NonCanonical ? getDeducedTemplateName(
7378 CanonUnderlying,
7379 /*DefaultArgs=*/{DefArgs.StartPos, CanonArgs})
7380 : Name;
7381 }
7385 llvm_unreachable("always sugar node");
7386 }
7387
7388 llvm_unreachable("bad template name!");
7389}
7390
7392 const TemplateName &Y,
7393 bool IgnoreDeduced) const {
7394 return getCanonicalTemplateName(X, IgnoreDeduced) ==
7395 getCanonicalTemplateName(Y, IgnoreDeduced);
7396}
7397
7399 const AssociatedConstraint &ACX, const AssociatedConstraint &ACY) const {
7400 if (ACX.ArgPackSubstIndex != ACY.ArgPackSubstIndex)
7401 return false;
7403 return false;
7404 return true;
7405}
7406
7407bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
7408 if (!XCE != !YCE)
7409 return false;
7410
7411 if (!XCE)
7412 return true;
7413
7414 llvm::FoldingSetNodeID XCEID, YCEID;
7415 XCE->Profile(XCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7416 YCE->Profile(YCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7417 return XCEID == YCEID;
7418}
7419
7421 const TypeConstraint *YTC) const {
7422 if (!XTC != !YTC)
7423 return false;
7424
7425 if (!XTC)
7426 return true;
7427
7428 auto *NCX = XTC->getNamedConcept();
7429 auto *NCY = YTC->getNamedConcept();
7430 if (!NCX || !NCY || !isSameEntity(NCX, NCY))
7431 return false;
7434 return false;
7436 if (XTC->getConceptReference()
7438 ->NumTemplateArgs !=
7440 return false;
7441
7442 // Compare slowly by profiling.
7443 //
7444 // We couldn't compare the profiling result for the template
7445 // args here. Consider the following example in different modules:
7446 //
7447 // template <__integer_like _Tp, C<_Tp> Sentinel>
7448 // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
7449 // return __t;
7450 // }
7451 //
7452 // When we compare the profiling result for `C<_Tp>` in different
7453 // modules, it will compare the type of `_Tp` in different modules.
7454 // However, the type of `_Tp` in different modules refer to different
7455 // types here naturally. So we couldn't compare the profiling result
7456 // for the template args directly.
7459}
7460
7462 const NamedDecl *Y) const {
7463 if (X->getKind() != Y->getKind())
7464 return false;
7465
7466 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
7467 auto *TY = cast<TemplateTypeParmDecl>(Y);
7468 if (TX->isParameterPack() != TY->isParameterPack())
7469 return false;
7470 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
7471 return false;
7472 return isSameTypeConstraint(TX->getTypeConstraint(),
7473 TY->getTypeConstraint());
7474 }
7475
7476 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7477 auto *TY = cast<NonTypeTemplateParmDecl>(Y);
7478 return TX->isParameterPack() == TY->isParameterPack() &&
7479 TX->getASTContext().hasSameType(TX->getType(), TY->getType()) &&
7480 isSameConstraintExpr(TX->getPlaceholderTypeConstraint(),
7481 TY->getPlaceholderTypeConstraint());
7482 }
7483
7485 auto *TY = cast<TemplateTemplateParmDecl>(Y);
7486 return TX->isParameterPack() == TY->isParameterPack() &&
7487 isSameTemplateParameterList(TX->getTemplateParameters(),
7488 TY->getTemplateParameters());
7489}
7490
7492 const TemplateParameterList *X, const TemplateParameterList *Y) const {
7493 if (X->size() != Y->size())
7494 return false;
7495
7496 for (unsigned I = 0, N = X->size(); I != N; ++I)
7497 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
7498 return false;
7499
7500 return isSameConstraintExpr(X->getRequiresClause(), Y->getRequiresClause());
7501}
7502
7504 const NamedDecl *Y) const {
7505 // If the type parameter isn't the same already, we don't need to check the
7506 // default argument further.
7507 if (!isSameTemplateParameter(X, Y))
7508 return false;
7509
7510 if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(X)) {
7511 auto *TTPY = cast<TemplateTypeParmDecl>(Y);
7512 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7513 return false;
7514
7515 return hasSameType(TTPX->getDefaultArgument().getArgument().getAsType(),
7516 TTPY->getDefaultArgument().getArgument().getAsType());
7517 }
7518
7519 if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7520 auto *NTTPY = cast<NonTypeTemplateParmDecl>(Y);
7521 if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
7522 return false;
7523
7524 Expr *DefaultArgumentX =
7525 NTTPX->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7526 Expr *DefaultArgumentY =
7527 NTTPY->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7528 llvm::FoldingSetNodeID XID, YID;
7529 DefaultArgumentX->Profile(XID, *this, /*Canonical=*/true);
7530 DefaultArgumentY->Profile(YID, *this, /*Canonical=*/true);
7531 return XID == YID;
7532 }
7533
7534 auto *TTPX = cast<TemplateTemplateParmDecl>(X);
7535 auto *TTPY = cast<TemplateTemplateParmDecl>(Y);
7536
7537 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7538 return false;
7539
7540 const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
7541 const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
7542 return hasSameTemplateName(TAX.getAsTemplate(), TAY.getAsTemplate());
7543}
7544
7546 const NestedNameSpecifier Y) {
7547 if (X == Y)
7548 return true;
7549 if (!X || !Y)
7550 return false;
7551
7552 auto Kind = X.getKind();
7553 if (Kind != Y.getKind())
7554 return false;
7555
7556 // FIXME: For namespaces and types, we're permitted to check that the entity
7557 // is named via the same tokens. We should probably do so.
7558 switch (Kind) {
7560 auto [NamespaceX, PrefixX] = X.getAsNamespaceAndPrefix();
7561 auto [NamespaceY, PrefixY] = Y.getAsNamespaceAndPrefix();
7562 if (!declaresSameEntity(NamespaceX->getNamespace(),
7563 NamespaceY->getNamespace()))
7564 return false;
7565 return isSameQualifier(PrefixX, PrefixY);
7566 }
7568 const auto *TX = X.getAsType(), *TY = Y.getAsType();
7569 if (TX->getCanonicalTypeInternal() != TY->getCanonicalTypeInternal())
7570 return false;
7571 return isSameQualifier(TX->getPrefix(), TY->getPrefix());
7572 }
7576 return true;
7577 }
7578 llvm_unreachable("unhandled qualifier kind");
7579}
7580
7581static bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B) {
7582 if (!A->getASTContext().getLangOpts().CUDA)
7583 return true; // Target attributes are overloadable in CUDA compilation only.
7584 if (A->hasAttr<CUDADeviceAttr>() != B->hasAttr<CUDADeviceAttr>())
7585 return false;
7586 if (A->hasAttr<CUDADeviceAttr>() && B->hasAttr<CUDADeviceAttr>())
7587 return A->hasAttr<CUDAHostAttr>() == B->hasAttr<CUDAHostAttr>();
7588 return true; // unattributed and __host__ functions are the same.
7589}
7590
7591/// Determine whether the attributes we can overload on are identical for A and
7592/// B. Will ignore any overloadable attrs represented in the type of A and B.
7594 const FunctionDecl *B) {
7595 // Note that pass_object_size attributes are represented in the function's
7596 // ExtParameterInfo, so we don't need to check them here.
7597
7598 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
7599 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
7600 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
7601
7602 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
7603 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
7604 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
7605
7606 // Return false if the number of enable_if attributes is different.
7607 if (!Cand1A || !Cand2A)
7608 return false;
7609
7610 Cand1ID.clear();
7611 Cand2ID.clear();
7612
7613 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
7614 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
7615
7616 // Return false if any of the enable_if expressions of A and B are
7617 // different.
7618 if (Cand1ID != Cand2ID)
7619 return false;
7620 }
7621 return hasSameCudaAttrs(A, B);
7622}
7623
7624bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
7625 // Caution: this function is called by the AST reader during deserialization,
7626 // so it cannot rely on AST invariants being met. Non-trivial accessors
7627 // should be avoided, along with any traversal of redeclaration chains.
7628
7629 if (X == Y)
7630 return true;
7631
7632 if (X->getDeclName() != Y->getDeclName())
7633 return false;
7634
7635 // Must be in the same context.
7636 //
7637 // Note that we can't use DeclContext::Equals here, because the DeclContexts
7638 // could be two different declarations of the same function. (We will fix the
7639 // semantic DC to refer to the primary definition after merging.)
7640 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
7642 return false;
7643
7644 // If either X or Y are local to the owning module, they are only possible to
7645 // be the same entity if they are in the same module.
7646 if (X->isModuleLocal() || Y->isModuleLocal())
7647 if (!isInSameModule(X->getOwningModule(), Y->getOwningModule()))
7648 return false;
7649
7650 // Two typedefs refer to the same entity if they have the same underlying
7651 // type.
7652 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
7653 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
7654 return hasSameType(TypedefX->getUnderlyingType(),
7655 TypedefY->getUnderlyingType());
7656
7657 // Must have the same kind.
7658 if (X->getKind() != Y->getKind())
7659 return false;
7660
7661 // Objective-C classes and protocols with the same name always match.
7663 return true;
7664
7666 // No need to handle these here: we merge them when adding them to the
7667 // template.
7668 return false;
7669 }
7670
7671 // Compatible tags match.
7672 if (const auto *TagX = dyn_cast<TagDecl>(X)) {
7673 const auto *TagY = cast<TagDecl>(Y);
7674 return (TagX->getTagKind() == TagY->getTagKind()) ||
7675 ((TagX->getTagKind() == TagTypeKind::Struct ||
7676 TagX->getTagKind() == TagTypeKind::Class ||
7677 TagX->getTagKind() == TagTypeKind::Interface) &&
7678 (TagY->getTagKind() == TagTypeKind::Struct ||
7679 TagY->getTagKind() == TagTypeKind::Class ||
7680 TagY->getTagKind() == TagTypeKind::Interface));
7681 }
7682
7683 // Functions with the same type and linkage match.
7684 // FIXME: This needs to cope with merging of prototyped/non-prototyped
7685 // functions, etc.
7686 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
7687 const auto *FuncY = cast<FunctionDecl>(Y);
7688 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
7689 const auto *CtorY = cast<CXXConstructorDecl>(Y);
7690 if (CtorX->getInheritedConstructor() &&
7691 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
7692 CtorY->getInheritedConstructor().getConstructor()))
7693 return false;
7694 }
7695
7696 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
7697 return false;
7698
7699 // Multiversioned functions with different feature strings are represented
7700 // as separate declarations.
7701 if (FuncX->isMultiVersion()) {
7702 const auto *TAX = FuncX->getAttr<TargetAttr>();
7703 const auto *TAY = FuncY->getAttr<TargetAttr>();
7704 assert(TAX && TAY && "Multiversion Function without target attribute");
7705
7706 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
7707 return false;
7708 }
7709
7710 // Per C++20 [temp.over.link]/4, friends in different classes are sometimes
7711 // not the same entity if they are constrained.
7712 if ((FuncX->isMemberLikeConstrainedFriend() ||
7713 FuncY->isMemberLikeConstrainedFriend()) &&
7714 !FuncX->getLexicalDeclContext()->Equals(
7715 FuncY->getLexicalDeclContext())) {
7716 return false;
7717 }
7718
7719 if (!isSameAssociatedConstraint(FuncX->getTrailingRequiresClause(),
7720 FuncY->getTrailingRequiresClause()))
7721 return false;
7722
7723 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
7724 // Map to the first declaration that we've already merged into this one.
7725 // The TSI of redeclarations might not match (due to calling conventions
7726 // being inherited onto the type but not the TSI), but the TSI type of
7727 // the first declaration of the function should match across modules.
7728 FD = FD->getCanonicalDecl();
7729 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
7730 : FD->getType();
7731 };
7732 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
7733 if (!hasSameType(XT, YT)) {
7734 // We can get functions with different types on the redecl chain in C++17
7735 // if they have differing exception specifications and at least one of
7736 // the excpetion specs is unresolved.
7737 auto *XFPT = XT->getAs<FunctionProtoType>();
7738 auto *YFPT = YT->getAs<FunctionProtoType>();
7739 if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
7740 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
7743 return true;
7744 return false;
7745 }
7746
7747 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
7748 hasSameOverloadableAttrs(FuncX, FuncY);
7749 }
7750
7751 // Variables with the same type and linkage match.
7752 if (const auto *VarX = dyn_cast<VarDecl>(X)) {
7753 const auto *VarY = cast<VarDecl>(Y);
7754 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
7755 // During deserialization, we might compare variables before we load
7756 // their types. Assume the types will end up being the same.
7757 if (VarX->getType().isNull() || VarY->getType().isNull())
7758 return true;
7759
7760 if (hasSameType(VarX->getType(), VarY->getType()))
7761 return true;
7762
7763 // We can get decls with different types on the redecl chain. Eg.
7764 // template <typename T> struct S { static T Var[]; }; // #1
7765 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
7766 // Only? happens when completing an incomplete array type. In this case
7767 // when comparing #1 and #2 we should go through their element type.
7768 const ArrayType *VarXTy = getAsArrayType(VarX->getType());
7769 const ArrayType *VarYTy = getAsArrayType(VarY->getType());
7770 if (!VarXTy || !VarYTy)
7771 return false;
7772 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
7773 return hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
7774 }
7775 return false;
7776 }
7777
7778 // Namespaces with the same name and inlinedness match.
7779 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
7780 const auto *NamespaceY = cast<NamespaceDecl>(Y);
7781 return NamespaceX->isInline() == NamespaceY->isInline();
7782 }
7783
7784 // Identical template names and kinds match if their template parameter lists
7785 // and patterns match.
7786 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
7787 const auto *TemplateY = cast<TemplateDecl>(Y);
7788
7789 // ConceptDecl wouldn't be the same if their constraint expression differs.
7790 if (const auto *ConceptX = dyn_cast<ConceptDecl>(X)) {
7791 const auto *ConceptY = cast<ConceptDecl>(Y);
7792 if (!isSameConstraintExpr(ConceptX->getConstraintExpr(),
7793 ConceptY->getConstraintExpr()))
7794 return false;
7795 }
7796
7797 return isSameEntity(TemplateX->getTemplatedDecl(),
7798 TemplateY->getTemplatedDecl()) &&
7799 isSameTemplateParameterList(TemplateX->getTemplateParameters(),
7800 TemplateY->getTemplateParameters());
7801 }
7802
7803 // Fields with the same name and the same type match.
7804 if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
7805 const auto *FDY = cast<FieldDecl>(Y);
7806 // FIXME: Also check the bitwidth is odr-equivalent, if any.
7807 return hasSameType(FDX->getType(), FDY->getType());
7808 }
7809
7810 // Indirect fields with the same target field match.
7811 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
7812 const auto *IFDY = cast<IndirectFieldDecl>(Y);
7813 return IFDX->getAnonField()->getCanonicalDecl() ==
7814 IFDY->getAnonField()->getCanonicalDecl();
7815 }
7816
7817 // Enumerators with the same name match.
7819 // FIXME: Also check the value is odr-equivalent.
7820 return true;
7821
7822 // Using shadow declarations with the same target match.
7823 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
7824 const auto *USY = cast<UsingShadowDecl>(Y);
7825 return declaresSameEntity(USX->getTargetDecl(), USY->getTargetDecl());
7826 }
7827
7828 // Using declarations with the same qualifier match. (We already know that
7829 // the name matches.)
7830 if (const auto *UX = dyn_cast<UsingDecl>(X)) {
7831 const auto *UY = cast<UsingDecl>(Y);
7832 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7833 UX->hasTypename() == UY->hasTypename() &&
7834 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7835 }
7836 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
7837 const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
7838 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7839 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7840 }
7841 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
7842 return isSameQualifier(
7843 UX->getQualifier(),
7844 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
7845 }
7846
7847 // Using-pack declarations are only created by instantiation, and match if
7848 // they're instantiated from matching UnresolvedUsing...Decls.
7849 if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
7850 return declaresSameEntity(
7851 UX->getInstantiatedFromUsingDecl(),
7852 cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
7853 }
7854
7855 // Namespace alias definitions with the same target match.
7856 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
7857 const auto *NAY = cast<NamespaceAliasDecl>(Y);
7858 return NAX->getNamespace()->Equals(NAY->getNamespace());
7859 }
7860
7861 return false;
7862}
7863
7866 switch (Arg.getKind()) {
7868 return Arg;
7869
7871 return TemplateArgument(Arg.getAsExpr(), /*IsCanonical=*/true,
7872 Arg.getIsDefaulted());
7873
7875 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
7877 Arg.getIsDefaulted());
7878 }
7879
7882 /*isNullPtr*/ true, Arg.getIsDefaulted());
7883
7886 Arg.getIsDefaulted());
7887
7889 return TemplateArgument(
7892
7895
7897 return TemplateArgument(*this,
7900
7903 /*isNullPtr*/ false, Arg.getIsDefaulted());
7904
7906 bool AnyNonCanonArgs = false;
7907 auto CanonArgs = ::getCanonicalTemplateArguments(
7908 *this, Arg.pack_elements(), AnyNonCanonArgs);
7909 if (!AnyNonCanonArgs)
7910 return Arg;
7912 const_cast<ASTContext &>(*this), CanonArgs);
7913 NewArg.setIsDefaulted(Arg.getIsDefaulted());
7914 return NewArg;
7915 }
7916 }
7917
7918 // Silence GCC warning
7919 llvm_unreachable("Unhandled template argument kind");
7920}
7921
7923 const TemplateArgument &Arg2) const {
7924 if (Arg1.getKind() != Arg2.getKind())
7925 return false;
7926
7927 switch (Arg1.getKind()) {
7929 llvm_unreachable("Comparing NULL template argument");
7930
7932 return hasSameType(Arg1.getAsType(), Arg2.getAsType());
7933
7935 return Arg1.getAsDecl()->getUnderlyingDecl()->getCanonicalDecl() ==
7937
7939 return hasSameType(Arg1.getNullPtrType(), Arg2.getNullPtrType());
7940
7945
7947 return llvm::APSInt::isSameValue(Arg1.getAsIntegral(),
7948 Arg2.getAsIntegral());
7949
7951 return Arg1.structurallyEquals(Arg2);
7952
7954 llvm::FoldingSetNodeID ID1, ID2;
7955 Arg1.getAsExpr()->Profile(ID1, *this, /*Canonical=*/true);
7956 Arg2.getAsExpr()->Profile(ID2, *this, /*Canonical=*/true);
7957 return ID1 == ID2;
7958 }
7959
7961 return llvm::equal(
7962 Arg1.getPackAsArray(), Arg2.getPackAsArray(),
7963 [&](const TemplateArgument &Arg1, const TemplateArgument &Arg2) {
7964 return isSameTemplateArgument(Arg1, Arg2);
7965 });
7966 }
7967
7968 llvm_unreachable("Unhandled template argument kind");
7969}
7970
7972 // Handle the non-qualified case efficiently.
7973 if (!T.hasLocalQualifiers()) {
7974 // Handle the common positive case fast.
7975 if (const auto *AT = dyn_cast<ArrayType>(T))
7976 return AT;
7977 }
7978
7979 // Handle the common negative case fast.
7980 if (!isa<ArrayType>(T.getCanonicalType()))
7981 return nullptr;
7982
7983 // Apply any qualifiers from the array type to the element type. This
7984 // implements C99 6.7.3p8: "If the specification of an array type includes
7985 // any type qualifiers, the element type is so qualified, not the array type."
7986
7987 // If we get here, we either have type qualifiers on the type, or we have
7988 // sugar such as a typedef in the way. If we have type qualifiers on the type
7989 // we must propagate them down into the element type.
7990
7991 SplitQualType split = T.getSplitDesugaredType();
7992 Qualifiers qs = split.Quals;
7993
7994 // If we have a simple case, just return now.
7995 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
7996 if (!ATy || qs.empty())
7997 return ATy;
7998
7999 // Otherwise, we have an array and we have qualifiers on it. Push the
8000 // qualifiers into the array element type and return a new array type.
8001 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
8002
8003 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
8004 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
8005 CAT->getSizeExpr(),
8006 CAT->getSizeModifier(),
8007 CAT->getIndexTypeCVRQualifiers()));
8008 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
8010 IAT->getSizeModifier(),
8011 IAT->getIndexTypeCVRQualifiers()));
8012
8013 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
8015 NewEltTy, DSAT->getSizeExpr(), DSAT->getSizeModifier(),
8016 DSAT->getIndexTypeCVRQualifiers()));
8017
8018 const auto *VAT = cast<VariableArrayType>(ATy);
8019 return cast<ArrayType>(
8020 getVariableArrayType(NewEltTy, VAT->getSizeExpr(), VAT->getSizeModifier(),
8021 VAT->getIndexTypeCVRQualifiers()));
8022}
8023
8025 if (getLangOpts().HLSL && T->isConstantArrayType())
8026 return getArrayParameterType(T);
8027 if (T->isArrayType() || T->isFunctionType())
8028 return getDecayedType(T);
8029 return T;
8030}
8031
8035 return T.getUnqualifiedType();
8036}
8037
8039 // C++ [except.throw]p3:
8040 // A throw-expression initializes a temporary object, called the exception
8041 // object, the type of which is determined by removing any top-level
8042 // cv-qualifiers from the static type of the operand of throw and adjusting
8043 // the type from "array of T" or "function returning T" to "pointer to T"
8044 // or "pointer to function returning T", [...]
8046 if (T->isArrayType() || T->isFunctionType())
8047 T = getDecayedType(T);
8048 return T.getUnqualifiedType();
8049}
8050
8051/// getArrayDecayedType - Return the properly qualified result of decaying the
8052/// specified array type to a pointer. This operation is non-trivial when
8053/// handling typedefs etc. The canonical type of "T" must be an array type,
8054/// this returns a pointer to a properly qualified element of the array.
8055///
8056/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
8058 // Get the element type with 'getAsArrayType' so that we don't lose any
8059 // typedefs in the element type of the array. This also handles propagation
8060 // of type qualifiers from the array type into the element type if present
8061 // (C99 6.7.3p8).
8062 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
8063 assert(PrettyArrayType && "Not an array type!");
8064
8065 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
8066
8067 // int x[restrict 4] -> int *restrict
8069 PrettyArrayType->getIndexTypeQualifiers());
8070
8071 // int x[_Nullable] -> int * _Nullable
8072 if (auto Nullability = Ty->getNullability()) {
8073 Result = const_cast<ASTContext *>(this)->getAttributedType(*Nullability,
8074 Result, Result);
8075 }
8076 return Result;
8077}
8078
8080 return getBaseElementType(array->getElementType());
8081}
8082
8084 Qualifiers qs;
8085 while (true) {
8086 SplitQualType split = type.getSplitDesugaredType();
8087 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
8088 if (!array) break;
8089
8090 type = array->getElementType();
8092 }
8093
8094 return getQualifiedType(type, qs);
8095}
8096
8097/// getConstantArrayElementCount - Returns number of constant array elements.
8098uint64_t
8100 uint64_t ElementCount = 1;
8101 do {
8102 ElementCount *= CA->getZExtSize();
8103 CA = dyn_cast_or_null<ConstantArrayType>(
8105 } while (CA);
8106 return ElementCount;
8107}
8108
8110 const ArrayInitLoopExpr *AILE) const {
8111 if (!AILE)
8112 return 0;
8113
8114 uint64_t ElementCount = 1;
8115
8116 do {
8117 ElementCount *= AILE->getArraySize().getZExtValue();
8118 AILE = dyn_cast<ArrayInitLoopExpr>(AILE->getSubExpr());
8119 } while (AILE);
8120
8121 return ElementCount;
8122}
8123
8124/// getFloatingRank - Return a relative rank for floating point types.
8125/// This routine will assert if passed a built-in type that isn't a float.
8127 if (const auto *CT = T->getAs<ComplexType>())
8128 return getFloatingRank(CT->getElementType());
8129
8130 switch (T->castAs<BuiltinType>()->getKind()) {
8131 default: llvm_unreachable("getFloatingRank(): not a floating type");
8132 case BuiltinType::Float16: return Float16Rank;
8133 case BuiltinType::Half: return HalfRank;
8134 case BuiltinType::Float: return FloatRank;
8135 case BuiltinType::Double: return DoubleRank;
8136 case BuiltinType::LongDouble: return LongDoubleRank;
8137 case BuiltinType::Float128: return Float128Rank;
8138 case BuiltinType::BFloat16: return BFloat16Rank;
8139 case BuiltinType::Ibm128: return Ibm128Rank;
8140 }
8141}
8142
8143/// getFloatingTypeOrder - Compare the rank of the two specified floating
8144/// point types, ignoring the domain of the type (i.e. 'double' ==
8145/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
8146/// LHS < RHS, return -1.
8148 FloatingRank LHSR = getFloatingRank(LHS);
8149 FloatingRank RHSR = getFloatingRank(RHS);
8150
8151 if (LHSR == RHSR)
8152 return 0;
8153 if (LHSR > RHSR)
8154 return 1;
8155 return -1;
8156}
8157
8160 return 0;
8161 return getFloatingTypeOrder(LHS, RHS);
8162}
8163
8164/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
8165/// routine will assert if passed a built-in type that isn't an integer or enum,
8166/// or if it is not canonicalized.
8167unsigned ASTContext::getIntegerRank(const Type *T) const {
8168 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
8169
8170 // Results in this 'losing' to any type of the same size, but winning if
8171 // larger.
8172 if (const auto *EIT = dyn_cast<BitIntType>(T))
8173 return 0 + (EIT->getNumBits() << 3);
8174
8175 switch (cast<BuiltinType>(T)->getKind()) {
8176 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
8177 case BuiltinType::Bool:
8178 return 1 + (getIntWidth(BoolTy) << 3);
8179 case BuiltinType::Char_S:
8180 case BuiltinType::Char_U:
8181 case BuiltinType::SChar:
8182 case BuiltinType::UChar:
8183 return 2 + (getIntWidth(CharTy) << 3);
8184 case BuiltinType::Short:
8185 case BuiltinType::UShort:
8186 return 3 + (getIntWidth(ShortTy) << 3);
8187 case BuiltinType::Int:
8188 case BuiltinType::UInt:
8189 return 4 + (getIntWidth(IntTy) << 3);
8190 case BuiltinType::Long:
8191 case BuiltinType::ULong:
8192 return 5 + (getIntWidth(LongTy) << 3);
8193 case BuiltinType::LongLong:
8194 case BuiltinType::ULongLong:
8195 return 6 + (getIntWidth(LongLongTy) << 3);
8196 case BuiltinType::Int128:
8197 case BuiltinType::UInt128:
8198 return 7 + (getIntWidth(Int128Ty) << 3);
8199
8200 // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
8201 // their underlying types" [c++20 conv.rank]
8202 case BuiltinType::Char8:
8203 return getIntegerRank(UnsignedCharTy.getTypePtr());
8204 case BuiltinType::Char16:
8205 return getIntegerRank(
8206 getFromTargetType(Target->getChar16Type()).getTypePtr());
8207 case BuiltinType::Char32:
8208 return getIntegerRank(
8209 getFromTargetType(Target->getChar32Type()).getTypePtr());
8210 case BuiltinType::WChar_S:
8211 case BuiltinType::WChar_U:
8212 return getIntegerRank(
8213 getFromTargetType(Target->getWCharType()).getTypePtr());
8214 }
8215}
8216
8217/// Whether this is a promotable bitfield reference according
8218/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
8219///
8220/// \returns the type this bit-field will promote to, or NULL if no
8221/// promotion occurs.
8223 if (E->isTypeDependent() || E->isValueDependent())
8224 return {};
8225
8226 // C++ [conv.prom]p5:
8227 // If the bit-field has an enumerated type, it is treated as any other
8228 // value of that type for promotion purposes.
8230 return {};
8231
8232 // FIXME: We should not do this unless E->refersToBitField() is true. This
8233 // matters in C where getSourceBitField() will find bit-fields for various
8234 // cases where the source expression is not a bit-field designator.
8235
8236 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
8237 if (!Field)
8238 return {};
8239
8240 QualType FT = Field->getType();
8241
8242 uint64_t BitWidth = Field->getBitWidthValue();
8243 uint64_t IntSize = getTypeSize(IntTy);
8244 // C++ [conv.prom]p5:
8245 // A prvalue for an integral bit-field can be converted to a prvalue of type
8246 // int if int can represent all the values of the bit-field; otherwise, it
8247 // can be converted to unsigned int if unsigned int can represent all the
8248 // values of the bit-field. If the bit-field is larger yet, no integral
8249 // promotion applies to it.
8250 // C11 6.3.1.1/2:
8251 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
8252 // If an int can represent all values of the original type (as restricted by
8253 // the width, for a bit-field), the value is converted to an int; otherwise,
8254 // it is converted to an unsigned int.
8255 //
8256 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
8257 // We perform that promotion here to match GCC and C++.
8258 // FIXME: C does not permit promotion of an enum bit-field whose rank is
8259 // greater than that of 'int'. We perform that promotion to match GCC.
8260 //
8261 // C23 6.3.1.1p2:
8262 // The value from a bit-field of a bit-precise integer type is converted to
8263 // the corresponding bit-precise integer type. (The rest is the same as in
8264 // C11.)
8265 if (QualType QT = Field->getType(); QT->isBitIntType())
8266 return QT;
8267
8268 if (BitWidth < IntSize)
8269 return IntTy;
8270
8271 if (BitWidth == IntSize)
8272 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
8273
8274 // Bit-fields wider than int are not subject to promotions, and therefore act
8275 // like the base type. GCC has some weird bugs in this area that we
8276 // deliberately do not follow (GCC follows a pre-standard resolution to
8277 // C's DR315 which treats bit-width as being part of the type, and this leaks
8278 // into their semantics in some cases).
8279 return {};
8280}
8281
8282/// getPromotedIntegerType - Returns the type that Promotable will
8283/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
8284/// integer type.
8286 assert(!Promotable.isNull());
8287 assert(isPromotableIntegerType(Promotable));
8288 if (const auto *ED = Promotable->getAsEnumDecl())
8289 return ED->getPromotionType();
8290
8291 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
8292 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
8293 // (3.9.1) can be converted to a prvalue of the first of the following
8294 // types that can represent all the values of its underlying type:
8295 // int, unsigned int, long int, unsigned long int, long long int, or
8296 // unsigned long long int [...]
8297 // FIXME: Is there some better way to compute this?
8298 if (BT->getKind() == BuiltinType::WChar_S ||
8299 BT->getKind() == BuiltinType::WChar_U ||
8300 BT->getKind() == BuiltinType::Char8 ||
8301 BT->getKind() == BuiltinType::Char16 ||
8302 BT->getKind() == BuiltinType::Char32) {
8303 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
8304 uint64_t FromSize = getTypeSize(BT);
8305 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
8307 for (const auto &PT : PromoteTypes) {
8308 uint64_t ToSize = getTypeSize(PT);
8309 if (FromSize < ToSize ||
8310 (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
8311 return PT;
8312 }
8313 llvm_unreachable("char type should fit into long long");
8314 }
8315 }
8316
8317 // At this point, we should have a signed or unsigned integer type.
8318 if (Promotable->isSignedIntegerType())
8319 return IntTy;
8320 uint64_t PromotableSize = getIntWidth(Promotable);
8321 uint64_t IntSize = getIntWidth(IntTy);
8322 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
8323 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
8324}
8325
8326/// Recurses in pointer/array types until it finds an objc retainable
8327/// type and returns its ownership.
8329 while (!T.isNull()) {
8330 if (T.getObjCLifetime() != Qualifiers::OCL_None)
8331 return T.getObjCLifetime();
8332 if (T->isArrayType())
8334 else if (const auto *PT = T->getAs<PointerType>())
8335 T = PT->getPointeeType();
8336 else if (const auto *RT = T->getAs<ReferenceType>())
8337 T = RT->getPointeeType();
8338 else
8339 break;
8340 }
8341
8342 return Qualifiers::OCL_None;
8343}
8344
8345static const Type *getIntegerTypeForEnum(const EnumType *ET) {
8346 // Incomplete enum types are not treated as integer types.
8347 // FIXME: In C++, enum types are never integer types.
8348 const EnumDecl *ED = ET->getOriginalDecl()->getDefinitionOrSelf();
8349 if (ED->isComplete() && !ED->isScoped())
8350 return ED->getIntegerType().getTypePtr();
8351 return nullptr;
8352}
8353
8354/// getIntegerTypeOrder - Returns the highest ranked integer type:
8355/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
8356/// LHS < RHS, return -1.
8358 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
8359 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
8360
8361 // Unwrap enums to their underlying type.
8362 if (const auto *ET = dyn_cast<EnumType>(LHSC))
8363 LHSC = getIntegerTypeForEnum(ET);
8364 if (const auto *ET = dyn_cast<EnumType>(RHSC))
8365 RHSC = getIntegerTypeForEnum(ET);
8366
8367 if (LHSC == RHSC) return 0;
8368
8369 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
8370 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
8371
8372 unsigned LHSRank = getIntegerRank(LHSC);
8373 unsigned RHSRank = getIntegerRank(RHSC);
8374
8375 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
8376 if (LHSRank == RHSRank) return 0;
8377 return LHSRank > RHSRank ? 1 : -1;
8378 }
8379
8380 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
8381 if (LHSUnsigned) {
8382 // If the unsigned [LHS] type is larger, return it.
8383 if (LHSRank >= RHSRank)
8384 return 1;
8385
8386 // If the signed type can represent all values of the unsigned type, it
8387 // wins. Because we are dealing with 2's complement and types that are
8388 // powers of two larger than each other, this is always safe.
8389 return -1;
8390 }
8391
8392 // If the unsigned [RHS] type is larger, return it.
8393 if (RHSRank >= LHSRank)
8394 return -1;
8395
8396 // If the signed type can represent all values of the unsigned type, it
8397 // wins. Because we are dealing with 2's complement and types that are
8398 // powers of two larger than each other, this is always safe.
8399 return 1;
8400}
8401
8403 if (CFConstantStringTypeDecl)
8404 return CFConstantStringTypeDecl;
8405
8406 assert(!CFConstantStringTagDecl &&
8407 "tag and typedef should be initialized together");
8408 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
8409 CFConstantStringTagDecl->startDefinition();
8410
8411 struct {
8412 QualType Type;
8413 const char *Name;
8414 } Fields[5];
8415 unsigned Count = 0;
8416
8417 /// Objective-C ABI
8418 ///
8419 /// typedef struct __NSConstantString_tag {
8420 /// const int *isa;
8421 /// int flags;
8422 /// const char *str;
8423 /// long length;
8424 /// } __NSConstantString;
8425 ///
8426 /// Swift ABI (4.1, 4.2)
8427 ///
8428 /// typedef struct __NSConstantString_tag {
8429 /// uintptr_t _cfisa;
8430 /// uintptr_t _swift_rc;
8431 /// _Atomic(uint64_t) _cfinfoa;
8432 /// const char *_ptr;
8433 /// uint32_t _length;
8434 /// } __NSConstantString;
8435 ///
8436 /// Swift ABI (5.0)
8437 ///
8438 /// typedef struct __NSConstantString_tag {
8439 /// uintptr_t _cfisa;
8440 /// uintptr_t _swift_rc;
8441 /// _Atomic(uint64_t) _cfinfoa;
8442 /// const char *_ptr;
8443 /// uintptr_t _length;
8444 /// } __NSConstantString;
8445
8446 const auto CFRuntime = getLangOpts().CFRuntime;
8447 if (static_cast<unsigned>(CFRuntime) <
8448 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
8449 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
8450 Fields[Count++] = { IntTy, "flags" };
8451 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
8452 Fields[Count++] = { LongTy, "length" };
8453 } else {
8454 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
8455 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
8456 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
8457 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
8460 Fields[Count++] = { IntTy, "_ptr" };
8461 else
8462 Fields[Count++] = { getUIntPtrType(), "_ptr" };
8463 }
8464
8465 // Create fields
8466 for (unsigned i = 0; i < Count; ++i) {
8467 FieldDecl *Field =
8468 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
8469 SourceLocation(), &Idents.get(Fields[i].Name),
8470 Fields[i].Type, /*TInfo=*/nullptr,
8471 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8472 Field->setAccess(AS_public);
8473 CFConstantStringTagDecl->addDecl(Field);
8474 }
8475
8476 CFConstantStringTagDecl->completeDefinition();
8477 // This type is designed to be compatible with NSConstantString, but cannot
8478 // use the same name, since NSConstantString is an interface.
8479 CanQualType tagType = getCanonicalTagType(CFConstantStringTagDecl);
8480 CFConstantStringTypeDecl =
8481 buildImplicitTypedef(tagType, "__NSConstantString");
8482
8483 return CFConstantStringTypeDecl;
8484}
8485
8487 if (!CFConstantStringTagDecl)
8488 getCFConstantStringDecl(); // Build the tag and the typedef.
8489 return CFConstantStringTagDecl;
8490}
8491
8492// getCFConstantStringType - Return the type used for constant CFStrings.
8497
8499 if (ObjCSuperType.isNull()) {
8500 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
8501 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl);
8502 ObjCSuperType = getCanonicalTagType(ObjCSuperTypeDecl);
8503 }
8504 return ObjCSuperType;
8505}
8506
8508 const auto *TT = T->castAs<TypedefType>();
8509 CFConstantStringTypeDecl = cast<TypedefDecl>(TT->getDecl());
8510 CFConstantStringTagDecl = TT->castAsRecordDecl();
8511}
8512
8514 if (BlockDescriptorType)
8515 return getCanonicalTagType(BlockDescriptorType);
8516
8517 RecordDecl *RD;
8518 // FIXME: Needs the FlagAppleBlock bit.
8519 RD = buildImplicitRecord("__block_descriptor");
8520 RD->startDefinition();
8521
8522 QualType FieldTypes[] = {
8525 };
8526
8527 static const char *const FieldNames[] = {
8528 "reserved",
8529 "Size"
8530 };
8531
8532 for (size_t i = 0; i < 2; ++i) {
8534 *this, RD, SourceLocation(), SourceLocation(),
8535 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8536 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8537 Field->setAccess(AS_public);
8538 RD->addDecl(Field);
8539 }
8540
8541 RD->completeDefinition();
8542
8543 BlockDescriptorType = RD;
8544
8545 return getCanonicalTagType(BlockDescriptorType);
8546}
8547
8549 if (BlockDescriptorExtendedType)
8550 return getCanonicalTagType(BlockDescriptorExtendedType);
8551
8552 RecordDecl *RD;
8553 // FIXME: Needs the FlagAppleBlock bit.
8554 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
8555 RD->startDefinition();
8556
8557 QualType FieldTypes[] = {
8562 };
8563
8564 static const char *const FieldNames[] = {
8565 "reserved",
8566 "Size",
8567 "CopyFuncPtr",
8568 "DestroyFuncPtr"
8569 };
8570
8571 for (size_t i = 0; i < 4; ++i) {
8573 *this, RD, SourceLocation(), SourceLocation(),
8574 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8575 /*BitWidth=*/nullptr,
8576 /*Mutable=*/false, ICIS_NoInit);
8577 Field->setAccess(AS_public);
8578 RD->addDecl(Field);
8579 }
8580
8581 RD->completeDefinition();
8582
8583 BlockDescriptorExtendedType = RD;
8584 return getCanonicalTagType(BlockDescriptorExtendedType);
8585}
8586
8588 const auto *BT = dyn_cast<BuiltinType>(T);
8589
8590 if (!BT) {
8591 if (isa<PipeType>(T))
8592 return OCLTK_Pipe;
8593
8594 return OCLTK_Default;
8595 }
8596
8597 switch (BT->getKind()) {
8598#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8599 case BuiltinType::Id: \
8600 return OCLTK_Image;
8601#include "clang/Basic/OpenCLImageTypes.def"
8602
8603 case BuiltinType::OCLClkEvent:
8604 return OCLTK_ClkEvent;
8605
8606 case BuiltinType::OCLEvent:
8607 return OCLTK_Event;
8608
8609 case BuiltinType::OCLQueue:
8610 return OCLTK_Queue;
8611
8612 case BuiltinType::OCLReserveID:
8613 return OCLTK_ReserveID;
8614
8615 case BuiltinType::OCLSampler:
8616 return OCLTK_Sampler;
8617
8618 default:
8619 return OCLTK_Default;
8620 }
8621}
8622
8624 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
8625}
8626
8627/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
8628/// requires copy/dispose. Note that this must match the logic
8629/// in buildByrefHelpers.
8631 const VarDecl *D) {
8632 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
8633 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
8634 if (!copyExpr && record->hasTrivialDestructor()) return false;
8635
8636 return true;
8637 }
8638
8640 return true;
8641
8642 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
8643 // move or destroy.
8645 return true;
8646
8647 if (!Ty->isObjCRetainableType()) return false;
8648
8649 Qualifiers qs = Ty.getQualifiers();
8650
8651 // If we have lifetime, that dominates.
8652 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
8653 switch (lifetime) {
8654 case Qualifiers::OCL_None: llvm_unreachable("impossible");
8655
8656 // These are just bits as far as the runtime is concerned.
8659 return false;
8660
8661 // These cases should have been taken care of when checking the type's
8662 // non-triviality.
8665 llvm_unreachable("impossible");
8666 }
8667 llvm_unreachable("fell out of lifetime switch!");
8668 }
8669 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
8671}
8672
8674 Qualifiers::ObjCLifetime &LifeTime,
8675 bool &HasByrefExtendedLayout) const {
8676 if (!getLangOpts().ObjC ||
8677 getLangOpts().getGC() != LangOptions::NonGC)
8678 return false;
8679
8680 HasByrefExtendedLayout = false;
8681 if (Ty->isRecordType()) {
8682 HasByrefExtendedLayout = true;
8683 LifeTime = Qualifiers::OCL_None;
8684 } else if ((LifeTime = Ty.getObjCLifetime())) {
8685 // Honor the ARC qualifiers.
8686 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
8687 // The MRR rule.
8689 } else {
8690 LifeTime = Qualifiers::OCL_None;
8691 }
8692 return true;
8693}
8694
8696 assert(Target && "Expected target to be initialized");
8697 const llvm::Triple &T = Target->getTriple();
8698 // Windows is LLP64 rather than LP64
8699 if (T.isOSWindows() && T.isArch64Bit())
8700 return UnsignedLongLongTy;
8701 return UnsignedLongTy;
8702}
8703
8705 assert(Target && "Expected target to be initialized");
8706 const llvm::Triple &T = Target->getTriple();
8707 // Windows is LLP64 rather than LP64
8708 if (T.isOSWindows() && T.isArch64Bit())
8709 return LongLongTy;
8710 return LongTy;
8711}
8712
8714 if (!ObjCInstanceTypeDecl)
8715 ObjCInstanceTypeDecl =
8716 buildImplicitTypedef(getObjCIdType(), "instancetype");
8717 return ObjCInstanceTypeDecl;
8718}
8719
8720// This returns true if a type has been typedefed to BOOL:
8721// typedef <type> BOOL;
8723 if (const auto *TT = dyn_cast<TypedefType>(T))
8724 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
8725 return II->isStr("BOOL");
8726
8727 return false;
8728}
8729
8730/// getObjCEncodingTypeSize returns size of type for objective-c encoding
8731/// purpose.
8733 if (!type->isIncompleteArrayType() && type->isIncompleteType())
8734 return CharUnits::Zero();
8735
8737
8738 // Make all integer and enum types at least as large as an int
8739 if (sz.isPositive() && type->isIntegralOrEnumerationType())
8740 sz = std::max(sz, getTypeSizeInChars(IntTy));
8741 // Treat arrays as pointers, since that's how they're passed in.
8742 else if (type->isArrayType())
8744 return sz;
8745}
8746
8753
8756 if (!VD->isInline())
8758
8759 // In almost all cases, it's a weak definition.
8760 auto *First = VD->getFirstDecl();
8761 if (First->isInlineSpecified() || !First->isStaticDataMember())
8763
8764 // If there's a file-context declaration in this translation unit, it's a
8765 // non-discardable definition.
8766 for (auto *D : VD->redecls())
8768 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
8770
8771 // If we've not seen one yet, we don't know.
8773}
8774
8775static std::string charUnitsToString(const CharUnits &CU) {
8776 return llvm::itostr(CU.getQuantity());
8777}
8778
8779/// getObjCEncodingForBlock - Return the encoded type for this block
8780/// declaration.
8782 std::string S;
8783
8784 const BlockDecl *Decl = Expr->getBlockDecl();
8785 QualType BlockTy =
8787 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
8788 // Encode result type.
8789 if (getLangOpts().EncodeExtendedBlockSig)
8791 true /*Extended*/);
8792 else
8793 getObjCEncodingForType(BlockReturnTy, S);
8794 // Compute size of all parameters.
8795 // Start with computing size of a pointer in number of bytes.
8796 // FIXME: There might(should) be a better way of doing this computation!
8798 CharUnits ParmOffset = PtrSize;
8799 for (auto *PI : Decl->parameters()) {
8800 QualType PType = PI->getType();
8802 if (sz.isZero())
8803 continue;
8804 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
8805 ParmOffset += sz;
8806 }
8807 // Size of the argument frame
8808 S += charUnitsToString(ParmOffset);
8809 // Block pointer and offset.
8810 S += "@?0";
8811
8812 // Argument types.
8813 ParmOffset = PtrSize;
8814 for (auto *PVDecl : Decl->parameters()) {
8815 QualType PType = PVDecl->getOriginalType();
8816 if (const auto *AT =
8817 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8818 // Use array's original type only if it has known number of
8819 // elements.
8820 if (!isa<ConstantArrayType>(AT))
8821 PType = PVDecl->getType();
8822 } else if (PType->isFunctionType())
8823 PType = PVDecl->getType();
8824 if (getLangOpts().EncodeExtendedBlockSig)
8826 S, true /*Extended*/);
8827 else
8828 getObjCEncodingForType(PType, S);
8829 S += charUnitsToString(ParmOffset);
8830 ParmOffset += getObjCEncodingTypeSize(PType);
8831 }
8832
8833 return S;
8834}
8835
8836std::string
8838 std::string S;
8839 // Encode result type.
8840 getObjCEncodingForType(Decl->getReturnType(), S);
8841 CharUnits ParmOffset;
8842 // Compute size of all parameters.
8843 for (auto *PI : Decl->parameters()) {
8844 QualType PType = PI->getType();
8846 if (sz.isZero())
8847 continue;
8848
8849 assert(sz.isPositive() &&
8850 "getObjCEncodingForFunctionDecl - Incomplete param type");
8851 ParmOffset += sz;
8852 }
8853 S += charUnitsToString(ParmOffset);
8854 ParmOffset = CharUnits::Zero();
8855
8856 // Argument types.
8857 for (auto *PVDecl : Decl->parameters()) {
8858 QualType PType = PVDecl->getOriginalType();
8859 if (const auto *AT =
8860 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8861 // Use array's original type only if it has known number of
8862 // elements.
8863 if (!isa<ConstantArrayType>(AT))
8864 PType = PVDecl->getType();
8865 } else if (PType->isFunctionType())
8866 PType = PVDecl->getType();
8867 getObjCEncodingForType(PType, S);
8868 S += charUnitsToString(ParmOffset);
8869 ParmOffset += getObjCEncodingTypeSize(PType);
8870 }
8871
8872 return S;
8873}
8874
8875/// getObjCEncodingForMethodParameter - Return the encoded type for a single
8876/// method parameter or return type. If Extended, include class names and
8877/// block object types.
8879 QualType T, std::string& S,
8880 bool Extended) const {
8881 // Encode type qualifier, 'in', 'inout', etc. for the parameter.
8883 // Encode parameter type.
8884 ObjCEncOptions Options = ObjCEncOptions()
8885 .setExpandPointedToStructures()
8886 .setExpandStructures()
8887 .setIsOutermostType();
8888 if (Extended)
8889 Options.setEncodeBlockParameters().setEncodeClassNames();
8890 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
8891}
8892
8893/// getObjCEncodingForMethodDecl - Return the encoded type for this method
8894/// declaration.
8896 bool Extended) const {
8897 // FIXME: This is not very efficient.
8898 // Encode return type.
8899 std::string S;
8900 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
8901 Decl->getReturnType(), S, Extended);
8902 // Compute size of all parameters.
8903 // Start with computing size of a pointer in number of bytes.
8904 // FIXME: There might(should) be a better way of doing this computation!
8906 // The first two arguments (self and _cmd) are pointers; account for
8907 // their size.
8908 CharUnits ParmOffset = 2 * PtrSize;
8909 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8910 E = Decl->sel_param_end(); PI != E; ++PI) {
8911 QualType PType = (*PI)->getType();
8913 if (sz.isZero())
8914 continue;
8915
8916 assert(sz.isPositive() &&
8917 "getObjCEncodingForMethodDecl - Incomplete param type");
8918 ParmOffset += sz;
8919 }
8920 S += charUnitsToString(ParmOffset);
8921 S += "@0:";
8922 S += charUnitsToString(PtrSize);
8923
8924 // Argument types.
8925 ParmOffset = 2 * PtrSize;
8926 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8927 E = Decl->sel_param_end(); PI != E; ++PI) {
8928 const ParmVarDecl *PVDecl = *PI;
8929 QualType PType = PVDecl->getOriginalType();
8930 if (const auto *AT =
8931 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8932 // Use array's original type only if it has known number of
8933 // elements.
8934 if (!isa<ConstantArrayType>(AT))
8935 PType = PVDecl->getType();
8936 } else if (PType->isFunctionType())
8937 PType = PVDecl->getType();
8939 PType, S, Extended);
8940 S += charUnitsToString(ParmOffset);
8941 ParmOffset += getObjCEncodingTypeSize(PType);
8942 }
8943
8944 return S;
8945}
8946
8949 const ObjCPropertyDecl *PD,
8950 const Decl *Container) const {
8951 if (!Container)
8952 return nullptr;
8953 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
8954 for (auto *PID : CID->property_impls())
8955 if (PID->getPropertyDecl() == PD)
8956 return PID;
8957 } else {
8958 const auto *OID = cast<ObjCImplementationDecl>(Container);
8959 for (auto *PID : OID->property_impls())
8960 if (PID->getPropertyDecl() == PD)
8961 return PID;
8962 }
8963 return nullptr;
8964}
8965
8966/// getObjCEncodingForPropertyDecl - Return the encoded type for this
8967/// property declaration. If non-NULL, Container must be either an
8968/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
8969/// NULL when getting encodings for protocol properties.
8970/// Property attributes are stored as a comma-delimited C string. The simple
8971/// attributes readonly and bycopy are encoded as single characters. The
8972/// parametrized attributes, getter=name, setter=name, and ivar=name, are
8973/// encoded as single characters, followed by an identifier. Property types
8974/// are also encoded as a parametrized attribute. The characters used to encode
8975/// these attributes are defined by the following enumeration:
8976/// @code
8977/// enum PropertyAttributes {
8978/// kPropertyReadOnly = 'R', // property is read-only.
8979/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
8980/// kPropertyByref = '&', // property is a reference to the value last assigned
8981/// kPropertyDynamic = 'D', // property is dynamic
8982/// kPropertyGetter = 'G', // followed by getter selector name
8983/// kPropertySetter = 'S', // followed by setter selector name
8984/// kPropertyInstanceVariable = 'V' // followed by instance variable name
8985/// kPropertyType = 'T' // followed by old-style type encoding.
8986/// kPropertyWeak = 'W' // 'weak' property
8987/// kPropertyStrong = 'P' // property GC'able
8988/// kPropertyNonAtomic = 'N' // property non-atomic
8989/// kPropertyOptional = '?' // property optional
8990/// };
8991/// @endcode
8992std::string
8994 const Decl *Container) const {
8995 // Collect information from the property implementation decl(s).
8996 bool Dynamic = false;
8997 ObjCPropertyImplDecl *SynthesizePID = nullptr;
8998
8999 if (ObjCPropertyImplDecl *PropertyImpDecl =
9001 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
9002 Dynamic = true;
9003 else
9004 SynthesizePID = PropertyImpDecl;
9005 }
9006
9007 // FIXME: This is not very efficient.
9008 std::string S = "T";
9009
9010 // Encode result type.
9011 // GCC has some special rules regarding encoding of properties which
9012 // closely resembles encoding of ivars.
9014
9015 if (PD->isOptional())
9016 S += ",?";
9017
9018 if (PD->isReadOnly()) {
9019 S += ",R";
9021 S += ",C";
9023 S += ",&";
9025 S += ",W";
9026 } else {
9027 switch (PD->getSetterKind()) {
9028 case ObjCPropertyDecl::Assign: break;
9029 case ObjCPropertyDecl::Copy: S += ",C"; break;
9030 case ObjCPropertyDecl::Retain: S += ",&"; break;
9031 case ObjCPropertyDecl::Weak: S += ",W"; break;
9032 }
9033 }
9034
9035 // It really isn't clear at all what this means, since properties
9036 // are "dynamic by default".
9037 if (Dynamic)
9038 S += ",D";
9039
9041 S += ",N";
9042
9044 S += ",G";
9045 S += PD->getGetterName().getAsString();
9046 }
9047
9049 S += ",S";
9050 S += PD->getSetterName().getAsString();
9051 }
9052
9053 if (SynthesizePID) {
9054 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
9055 S += ",V";
9056 S += OID->getNameAsString();
9057 }
9058
9059 // FIXME: OBJCGC: weak & strong
9060 return S;
9061}
9062
9063/// getLegacyIntegralTypeEncoding -
9064/// Another legacy compatibility encoding: 32-bit longs are encoded as
9065/// 'l' or 'L' , but not always. For typedefs, we need to use
9066/// 'i' or 'I' instead if encoding a struct field, or a pointer!
9068 if (PointeeTy->getAs<TypedefType>()) {
9069 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
9070 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
9071 PointeeTy = UnsignedIntTy;
9072 else
9073 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
9074 PointeeTy = IntTy;
9075 }
9076 }
9077}
9078
9080 const FieldDecl *Field,
9081 QualType *NotEncodedT) const {
9082 // We follow the behavior of gcc, expanding structures which are
9083 // directly pointed to, and expanding embedded structures. Note that
9084 // these rules are sufficient to prevent recursive encoding of the
9085 // same type.
9086 getObjCEncodingForTypeImpl(T, S,
9087 ObjCEncOptions()
9088 .setExpandPointedToStructures()
9089 .setExpandStructures()
9090 .setIsOutermostType(),
9091 Field, NotEncodedT);
9092}
9093
9095 std::string& S) const {
9096 // Encode result type.
9097 // GCC has some special rules regarding encoding of properties which
9098 // closely resembles encoding of ivars.
9099 getObjCEncodingForTypeImpl(T, S,
9100 ObjCEncOptions()
9101 .setExpandPointedToStructures()
9102 .setExpandStructures()
9103 .setIsOutermostType()
9104 .setEncodingProperty(),
9105 /*Field=*/nullptr);
9106}
9107
9109 const BuiltinType *BT) {
9110 BuiltinType::Kind kind = BT->getKind();
9111 switch (kind) {
9112 case BuiltinType::Void: return 'v';
9113 case BuiltinType::Bool: return 'B';
9114 case BuiltinType::Char8:
9115 case BuiltinType::Char_U:
9116 case BuiltinType::UChar: return 'C';
9117 case BuiltinType::Char16:
9118 case BuiltinType::UShort: return 'S';
9119 case BuiltinType::Char32:
9120 case BuiltinType::UInt: return 'I';
9121 case BuiltinType::ULong:
9122 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
9123 case BuiltinType::UInt128: return 'T';
9124 case BuiltinType::ULongLong: return 'Q';
9125 case BuiltinType::Char_S:
9126 case BuiltinType::SChar: return 'c';
9127 case BuiltinType::Short: return 's';
9128 case BuiltinType::WChar_S:
9129 case BuiltinType::WChar_U:
9130 case BuiltinType::Int: return 'i';
9131 case BuiltinType::Long:
9132 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
9133 case BuiltinType::LongLong: return 'q';
9134 case BuiltinType::Int128: return 't';
9135 case BuiltinType::Float: return 'f';
9136 case BuiltinType::Double: return 'd';
9137 case BuiltinType::LongDouble: return 'D';
9138 case BuiltinType::NullPtr: return '*'; // like char*
9139
9140 case BuiltinType::BFloat16:
9141 case BuiltinType::Float16:
9142 case BuiltinType::Float128:
9143 case BuiltinType::Ibm128:
9144 case BuiltinType::Half:
9145 case BuiltinType::ShortAccum:
9146 case BuiltinType::Accum:
9147 case BuiltinType::LongAccum:
9148 case BuiltinType::UShortAccum:
9149 case BuiltinType::UAccum:
9150 case BuiltinType::ULongAccum:
9151 case BuiltinType::ShortFract:
9152 case BuiltinType::Fract:
9153 case BuiltinType::LongFract:
9154 case BuiltinType::UShortFract:
9155 case BuiltinType::UFract:
9156 case BuiltinType::ULongFract:
9157 case BuiltinType::SatShortAccum:
9158 case BuiltinType::SatAccum:
9159 case BuiltinType::SatLongAccum:
9160 case BuiltinType::SatUShortAccum:
9161 case BuiltinType::SatUAccum:
9162 case BuiltinType::SatULongAccum:
9163 case BuiltinType::SatShortFract:
9164 case BuiltinType::SatFract:
9165 case BuiltinType::SatLongFract:
9166 case BuiltinType::SatUShortFract:
9167 case BuiltinType::SatUFract:
9168 case BuiltinType::SatULongFract:
9169 // FIXME: potentially need @encodes for these!
9170 return ' ';
9171
9172#define SVE_TYPE(Name, Id, SingletonId) \
9173 case BuiltinType::Id:
9174#include "clang/Basic/AArch64ACLETypes.def"
9175#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9176#include "clang/Basic/RISCVVTypes.def"
9177#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9178#include "clang/Basic/WebAssemblyReferenceTypes.def"
9179#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
9180#include "clang/Basic/AMDGPUTypes.def"
9181 {
9182 DiagnosticsEngine &Diags = C->getDiagnostics();
9183 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
9184 "cannot yet @encode type %0");
9185 Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
9186 return ' ';
9187 }
9188
9189 case BuiltinType::ObjCId:
9190 case BuiltinType::ObjCClass:
9191 case BuiltinType::ObjCSel:
9192 llvm_unreachable("@encoding ObjC primitive type");
9193
9194 // OpenCL and placeholder types don't need @encodings.
9195#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
9196 case BuiltinType::Id:
9197#include "clang/Basic/OpenCLImageTypes.def"
9198#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
9199 case BuiltinType::Id:
9200#include "clang/Basic/OpenCLExtensionTypes.def"
9201 case BuiltinType::OCLEvent:
9202 case BuiltinType::OCLClkEvent:
9203 case BuiltinType::OCLQueue:
9204 case BuiltinType::OCLReserveID:
9205 case BuiltinType::OCLSampler:
9206 case BuiltinType::Dependent:
9207#define PPC_VECTOR_TYPE(Name, Id, Size) \
9208 case BuiltinType::Id:
9209#include "clang/Basic/PPCTypes.def"
9210#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9211#include "clang/Basic/HLSLIntangibleTypes.def"
9212#define BUILTIN_TYPE(KIND, ID)
9213#define PLACEHOLDER_TYPE(KIND, ID) \
9214 case BuiltinType::KIND:
9215#include "clang/AST/BuiltinTypes.def"
9216 llvm_unreachable("invalid builtin type for @encode");
9217 }
9218 llvm_unreachable("invalid BuiltinType::Kind value");
9219}
9220
9221static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED) {
9223
9224 // The encoding of an non-fixed enum type is always 'i', regardless of size.
9225 if (!Enum->isFixed())
9226 return 'i';
9227
9228 // The encoding of a fixed enum type matches its fixed underlying type.
9229 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
9231}
9232
9233static void EncodeBitField(const ASTContext *Ctx, std::string& S,
9234 QualType T, const FieldDecl *FD) {
9235 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
9236 S += 'b';
9237 // The NeXT runtime encodes bit fields as b followed by the number of bits.
9238 // The GNU runtime requires more information; bitfields are encoded as b,
9239 // then the offset (in bits) of the first element, then the type of the
9240 // bitfield, then the size in bits. For example, in this structure:
9241 //
9242 // struct
9243 // {
9244 // int integer;
9245 // int flags:2;
9246 // };
9247 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
9248 // runtime, but b32i2 for the GNU runtime. The reason for this extra
9249 // information is not especially sensible, but we're stuck with it for
9250 // compatibility with GCC, although providing it breaks anything that
9251 // actually uses runtime introspection and wants to work on both runtimes...
9252 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
9253 uint64_t Offset;
9254
9255 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
9256 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), IVD);
9257 } else {
9258 const RecordDecl *RD = FD->getParent();
9259 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
9260 Offset = RL.getFieldOffset(FD->getFieldIndex());
9261 }
9262
9263 S += llvm::utostr(Offset);
9264
9265 if (const auto *ET = T->getAsCanonical<EnumType>())
9266 S += ObjCEncodingForEnumDecl(Ctx, ET->getOriginalDecl());
9267 else {
9268 const auto *BT = T->castAs<BuiltinType>();
9269 S += getObjCEncodingForPrimitiveType(Ctx, BT);
9270 }
9271 }
9272 S += llvm::utostr(FD->getBitWidthValue());
9273}
9274
9275// Helper function for determining whether the encoded type string would include
9276// a template specialization type.
9278 bool VisitBasesAndFields) {
9279 T = T->getBaseElementTypeUnsafe();
9280
9281 if (auto *PT = T->getAs<PointerType>())
9283 PT->getPointeeType().getTypePtr(), false);
9284
9285 auto *CXXRD = T->getAsCXXRecordDecl();
9286
9287 if (!CXXRD)
9288 return false;
9289
9291 return true;
9292
9293 if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
9294 return false;
9295
9296 for (const auto &B : CXXRD->bases())
9297 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
9298 true))
9299 return true;
9300
9301 for (auto *FD : CXXRD->fields())
9302 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
9303 true))
9304 return true;
9305
9306 return false;
9307}
9308
9309// FIXME: Use SmallString for accumulating string.
9310void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
9311 const ObjCEncOptions Options,
9312 const FieldDecl *FD,
9313 QualType *NotEncodedT) const {
9315 switch (CT->getTypeClass()) {
9316 case Type::Builtin:
9317 case Type::Enum:
9318 if (FD && FD->isBitField())
9319 return EncodeBitField(this, S, T, FD);
9320 if (const auto *BT = dyn_cast<BuiltinType>(CT))
9321 S += getObjCEncodingForPrimitiveType(this, BT);
9322 else
9323 S += ObjCEncodingForEnumDecl(this, cast<EnumType>(CT)->getOriginalDecl());
9324 return;
9325
9326 case Type::Complex:
9327 S += 'j';
9328 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
9329 ObjCEncOptions(),
9330 /*Field=*/nullptr);
9331 return;
9332
9333 case Type::Atomic:
9334 S += 'A';
9335 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
9336 ObjCEncOptions(),
9337 /*Field=*/nullptr);
9338 return;
9339
9340 // encoding for pointer or reference types.
9341 case Type::Pointer:
9342 case Type::LValueReference:
9343 case Type::RValueReference: {
9344 QualType PointeeTy;
9345 if (isa<PointerType>(CT)) {
9346 const auto *PT = T->castAs<PointerType>();
9347 if (PT->isObjCSelType()) {
9348 S += ':';
9349 return;
9350 }
9351 PointeeTy = PT->getPointeeType();
9352 } else {
9353 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
9354 }
9355
9356 bool isReadOnly = false;
9357 // For historical/compatibility reasons, the read-only qualifier of the
9358 // pointee gets emitted _before_ the '^'. The read-only qualifier of
9359 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
9360 // Also, do not emit the 'r' for anything but the outermost type!
9361 if (T->getAs<TypedefType>()) {
9362 if (Options.IsOutermostType() && T.isConstQualified()) {
9363 isReadOnly = true;
9364 S += 'r';
9365 }
9366 } else if (Options.IsOutermostType()) {
9367 QualType P = PointeeTy;
9368 while (auto PT = P->getAs<PointerType>())
9369 P = PT->getPointeeType();
9370 if (P.isConstQualified()) {
9371 isReadOnly = true;
9372 S += 'r';
9373 }
9374 }
9375 if (isReadOnly) {
9376 // Another legacy compatibility encoding. Some ObjC qualifier and type
9377 // combinations need to be rearranged.
9378 // Rewrite "in const" from "nr" to "rn"
9379 if (StringRef(S).ends_with("nr"))
9380 S.replace(S.end()-2, S.end(), "rn");
9381 }
9382
9383 if (PointeeTy->isCharType()) {
9384 // char pointer types should be encoded as '*' unless it is a
9385 // type that has been typedef'd to 'BOOL'.
9386 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
9387 S += '*';
9388 return;
9389 }
9390 } else if (const auto *RTy = PointeeTy->getAsCanonical<RecordType>()) {
9391 const IdentifierInfo *II = RTy->getOriginalDecl()->getIdentifier();
9392 // GCC binary compat: Need to convert "struct objc_class *" to "#".
9393 if (II == &Idents.get("objc_class")) {
9394 S += '#';
9395 return;
9396 }
9397 // GCC binary compat: Need to convert "struct objc_object *" to "@".
9398 if (II == &Idents.get("objc_object")) {
9399 S += '@';
9400 return;
9401 }
9402 // If the encoded string for the class includes template names, just emit
9403 // "^v" for pointers to the class.
9404 if (getLangOpts().CPlusPlus &&
9405 (!getLangOpts().EncodeCXXClassTemplateSpec &&
9407 RTy, Options.ExpandPointedToStructures()))) {
9408 S += "^v";
9409 return;
9410 }
9411 // fall through...
9412 }
9413 S += '^';
9415
9416 ObjCEncOptions NewOptions;
9417 if (Options.ExpandPointedToStructures())
9418 NewOptions.setExpandStructures();
9419 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
9420 /*Field=*/nullptr, NotEncodedT);
9421 return;
9422 }
9423
9424 case Type::ConstantArray:
9425 case Type::IncompleteArray:
9426 case Type::VariableArray: {
9427 const auto *AT = cast<ArrayType>(CT);
9428
9429 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
9430 // Incomplete arrays are encoded as a pointer to the array element.
9431 S += '^';
9432
9433 getObjCEncodingForTypeImpl(
9434 AT->getElementType(), S,
9435 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
9436 } else {
9437 S += '[';
9438
9439 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
9440 S += llvm::utostr(CAT->getZExtSize());
9441 else {
9442 //Variable length arrays are encoded as a regular array with 0 elements.
9444 "Unknown array type!");
9445 S += '0';
9446 }
9447
9448 getObjCEncodingForTypeImpl(
9449 AT->getElementType(), S,
9450 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
9451 NotEncodedT);
9452 S += ']';
9453 }
9454 return;
9455 }
9456
9457 case Type::FunctionNoProto:
9458 case Type::FunctionProto:
9459 S += '?';
9460 return;
9461
9462 case Type::Record: {
9463 RecordDecl *RDecl = cast<RecordType>(CT)->getOriginalDecl();
9464 S += RDecl->isUnion() ? '(' : '{';
9465 // Anonymous structures print as '?'
9466 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
9467 S += II->getName();
9468 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
9469 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
9470 llvm::raw_string_ostream OS(S);
9471 printTemplateArgumentList(OS, TemplateArgs.asArray(),
9473 }
9474 } else {
9475 S += '?';
9476 }
9477 if (Options.ExpandStructures()) {
9478 S += '=';
9479 if (!RDecl->isUnion()) {
9480 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
9481 } else {
9482 for (const auto *Field : RDecl->fields()) {
9483 if (FD) {
9484 S += '"';
9485 S += Field->getNameAsString();
9486 S += '"';
9487 }
9488
9489 // Special case bit-fields.
9490 if (Field->isBitField()) {
9491 getObjCEncodingForTypeImpl(Field->getType(), S,
9492 ObjCEncOptions().setExpandStructures(),
9493 Field);
9494 } else {
9495 QualType qt = Field->getType();
9497 getObjCEncodingForTypeImpl(
9498 qt, S,
9499 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
9500 NotEncodedT);
9501 }
9502 }
9503 }
9504 }
9505 S += RDecl->isUnion() ? ')' : '}';
9506 return;
9507 }
9508
9509 case Type::BlockPointer: {
9510 const auto *BT = T->castAs<BlockPointerType>();
9511 S += "@?"; // Unlike a pointer-to-function, which is "^?".
9512 if (Options.EncodeBlockParameters()) {
9513 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
9514
9515 S += '<';
9516 // Block return type
9517 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
9518 Options.forComponentType(), FD, NotEncodedT);
9519 // Block self
9520 S += "@?";
9521 // Block parameters
9522 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
9523 for (const auto &I : FPT->param_types())
9524 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
9525 NotEncodedT);
9526 }
9527 S += '>';
9528 }
9529 return;
9530 }
9531
9532 case Type::ObjCObject: {
9533 // hack to match legacy encoding of *id and *Class
9534 QualType Ty = getObjCObjectPointerType(CT);
9535 if (Ty->isObjCIdType()) {
9536 S += "{objc_object=}";
9537 return;
9538 }
9539 else if (Ty->isObjCClassType()) {
9540 S += "{objc_class=}";
9541 return;
9542 }
9543 // TODO: Double check to make sure this intentionally falls through.
9544 [[fallthrough]];
9545 }
9546
9547 case Type::ObjCInterface: {
9548 // Ignore protocol qualifiers when mangling at this level.
9549 // @encode(class_name)
9550 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
9551 S += '{';
9552 S += OI->getObjCRuntimeNameAsString();
9553 if (Options.ExpandStructures()) {
9554 S += '=';
9555 SmallVector<const ObjCIvarDecl*, 32> Ivars;
9556 DeepCollectObjCIvars(OI, true, Ivars);
9557 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
9558 const FieldDecl *Field = Ivars[i];
9559 if (Field->isBitField())
9560 getObjCEncodingForTypeImpl(Field->getType(), S,
9561 ObjCEncOptions().setExpandStructures(),
9562 Field);
9563 else
9564 getObjCEncodingForTypeImpl(Field->getType(), S,
9565 ObjCEncOptions().setExpandStructures(), FD,
9566 NotEncodedT);
9567 }
9568 }
9569 S += '}';
9570 return;
9571 }
9572
9573 case Type::ObjCObjectPointer: {
9574 const auto *OPT = T->castAs<ObjCObjectPointerType>();
9575 if (OPT->isObjCIdType()) {
9576 S += '@';
9577 return;
9578 }
9579
9580 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
9581 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
9582 // Since this is a binary compatibility issue, need to consult with
9583 // runtime folks. Fortunately, this is a *very* obscure construct.
9584 S += '#';
9585 return;
9586 }
9587
9588 if (OPT->isObjCQualifiedIdType()) {
9589 getObjCEncodingForTypeImpl(
9590 getObjCIdType(), S,
9591 Options.keepingOnly(ObjCEncOptions()
9592 .setExpandPointedToStructures()
9593 .setExpandStructures()),
9594 FD);
9595 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
9596 // Note that we do extended encoding of protocol qualifier list
9597 // Only when doing ivar or property encoding.
9598 S += '"';
9599 for (const auto *I : OPT->quals()) {
9600 S += '<';
9601 S += I->getObjCRuntimeNameAsString();
9602 S += '>';
9603 }
9604 S += '"';
9605 }
9606 return;
9607 }
9608
9609 S += '@';
9610 if (OPT->getInterfaceDecl() &&
9611 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
9612 S += '"';
9613 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
9614 for (const auto *I : OPT->quals()) {
9615 S += '<';
9616 S += I->getObjCRuntimeNameAsString();
9617 S += '>';
9618 }
9619 S += '"';
9620 }
9621 return;
9622 }
9623
9624 // gcc just blithely ignores member pointers.
9625 // FIXME: we should do better than that. 'M' is available.
9626 case Type::MemberPointer:
9627 // This matches gcc's encoding, even though technically it is insufficient.
9628 //FIXME. We should do a better job than gcc.
9629 case Type::Vector:
9630 case Type::ExtVector:
9631 // Until we have a coherent encoding of these three types, issue warning.
9632 if (NotEncodedT)
9633 *NotEncodedT = T;
9634 return;
9635
9636 case Type::ConstantMatrix:
9637 if (NotEncodedT)
9638 *NotEncodedT = T;
9639 return;
9640
9641 case Type::BitInt:
9642 if (NotEncodedT)
9643 *NotEncodedT = T;
9644 return;
9645
9646 // We could see an undeduced auto type here during error recovery.
9647 // Just ignore it.
9648 case Type::Auto:
9649 case Type::DeducedTemplateSpecialization:
9650 return;
9651
9652 case Type::HLSLAttributedResource:
9653 case Type::HLSLInlineSpirv:
9654 llvm_unreachable("unexpected type");
9655
9656 case Type::ArrayParameter:
9657 case Type::Pipe:
9658#define ABSTRACT_TYPE(KIND, BASE)
9659#define TYPE(KIND, BASE)
9660#define DEPENDENT_TYPE(KIND, BASE) \
9661 case Type::KIND:
9662#define NON_CANONICAL_TYPE(KIND, BASE) \
9663 case Type::KIND:
9664#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
9665 case Type::KIND:
9666#include "clang/AST/TypeNodes.inc"
9667 llvm_unreachable("@encode for dependent type!");
9668 }
9669 llvm_unreachable("bad type kind!");
9670}
9671
9672void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
9673 std::string &S,
9674 const FieldDecl *FD,
9675 bool includeVBases,
9676 QualType *NotEncodedT) const {
9677 assert(RDecl && "Expected non-null RecordDecl");
9678 assert(!RDecl->isUnion() && "Should not be called for unions");
9679 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
9680 return;
9681
9682 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
9683 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
9684 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
9685
9686 if (CXXRec) {
9687 for (const auto &BI : CXXRec->bases()) {
9688 if (!BI.isVirtual()) {
9689 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9690 if (base->isEmpty())
9691 continue;
9692 uint64_t offs = toBits(layout.getBaseClassOffset(base));
9693 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9694 std::make_pair(offs, base));
9695 }
9696 }
9697 }
9698
9699 for (FieldDecl *Field : RDecl->fields()) {
9700 if (!Field->isZeroLengthBitField() && Field->isZeroSize(*this))
9701 continue;
9702 uint64_t offs = layout.getFieldOffset(Field->getFieldIndex());
9703 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9704 std::make_pair(offs, Field));
9705 }
9706
9707 if (CXXRec && includeVBases) {
9708 for (const auto &BI : CXXRec->vbases()) {
9709 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9710 if (base->isEmpty())
9711 continue;
9712 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
9713 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
9714 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
9715 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
9716 std::make_pair(offs, base));
9717 }
9718 }
9719
9720 CharUnits size;
9721 if (CXXRec) {
9722 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
9723 } else {
9724 size = layout.getSize();
9725 }
9726
9727#ifndef NDEBUG
9728 uint64_t CurOffs = 0;
9729#endif
9730 std::multimap<uint64_t, NamedDecl *>::iterator
9731 CurLayObj = FieldOrBaseOffsets.begin();
9732
9733 if (CXXRec && CXXRec->isDynamicClass() &&
9734 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
9735 if (FD) {
9736 S += "\"_vptr$";
9737 std::string recname = CXXRec->getNameAsString();
9738 if (recname.empty()) recname = "?";
9739 S += recname;
9740 S += '"';
9741 }
9742 S += "^^?";
9743#ifndef NDEBUG
9744 CurOffs += getTypeSize(VoidPtrTy);
9745#endif
9746 }
9747
9748 if (!RDecl->hasFlexibleArrayMember()) {
9749 // Mark the end of the structure.
9750 uint64_t offs = toBits(size);
9751 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9752 std::make_pair(offs, nullptr));
9753 }
9754
9755 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
9756#ifndef NDEBUG
9757 assert(CurOffs <= CurLayObj->first);
9758 if (CurOffs < CurLayObj->first) {
9759 uint64_t padding = CurLayObj->first - CurOffs;
9760 // FIXME: There doesn't seem to be a way to indicate in the encoding that
9761 // packing/alignment of members is different that normal, in which case
9762 // the encoding will be out-of-sync with the real layout.
9763 // If the runtime switches to just consider the size of types without
9764 // taking into account alignment, we could make padding explicit in the
9765 // encoding (e.g. using arrays of chars). The encoding strings would be
9766 // longer then though.
9767 CurOffs += padding;
9768 }
9769#endif
9770
9771 NamedDecl *dcl = CurLayObj->second;
9772 if (!dcl)
9773 break; // reached end of structure.
9774
9775 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
9776 // We expand the bases without their virtual bases since those are going
9777 // in the initial structure. Note that this differs from gcc which
9778 // expands virtual bases each time one is encountered in the hierarchy,
9779 // making the encoding type bigger than it really is.
9780 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
9781 NotEncodedT);
9782 assert(!base->isEmpty());
9783#ifndef NDEBUG
9784 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
9785#endif
9786 } else {
9787 const auto *field = cast<FieldDecl>(dcl);
9788 if (FD) {
9789 S += '"';
9790 S += field->getNameAsString();
9791 S += '"';
9792 }
9793
9794 if (field->isBitField()) {
9795 EncodeBitField(this, S, field->getType(), field);
9796#ifndef NDEBUG
9797 CurOffs += field->getBitWidthValue();
9798#endif
9799 } else {
9800 QualType qt = field->getType();
9802 getObjCEncodingForTypeImpl(
9803 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
9804 FD, NotEncodedT);
9805#ifndef NDEBUG
9806 CurOffs += getTypeSize(field->getType());
9807#endif
9808 }
9809 }
9810 }
9811}
9812
9814 std::string& S) const {
9815 if (QT & Decl::OBJC_TQ_In)
9816 S += 'n';
9817 if (QT & Decl::OBJC_TQ_Inout)
9818 S += 'N';
9819 if (QT & Decl::OBJC_TQ_Out)
9820 S += 'o';
9821 if (QT & Decl::OBJC_TQ_Bycopy)
9822 S += 'O';
9823 if (QT & Decl::OBJC_TQ_Byref)
9824 S += 'R';
9825 if (QT & Decl::OBJC_TQ_Oneway)
9826 S += 'V';
9827}
9828
9830 if (!ObjCIdDecl) {
9833 ObjCIdDecl = buildImplicitTypedef(T, "id");
9834 }
9835 return ObjCIdDecl;
9836}
9837
9839 if (!ObjCSelDecl) {
9841 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
9842 }
9843 return ObjCSelDecl;
9844}
9845
9847 if (!ObjCClassDecl) {
9850 ObjCClassDecl = buildImplicitTypedef(T, "Class");
9851 }
9852 return ObjCClassDecl;
9853}
9854
9856 if (!ObjCProtocolClassDecl) {
9857 ObjCProtocolClassDecl
9860 &Idents.get("Protocol"),
9861 /*typeParamList=*/nullptr,
9862 /*PrevDecl=*/nullptr,
9863 SourceLocation(), true);
9864 }
9865
9866 return ObjCProtocolClassDecl;
9867}
9868
9870 if (!getLangOpts().PointerAuthObjcInterfaceSel)
9871 return PointerAuthQualifier();
9873 getLangOpts().PointerAuthObjcInterfaceSelKey,
9874 /*isAddressDiscriminated=*/true, SelPointerConstantDiscriminator,
9876 /*isIsaPointer=*/false,
9877 /*authenticatesNullValues=*/false);
9878}
9879
9880//===----------------------------------------------------------------------===//
9881// __builtin_va_list Construction Functions
9882//===----------------------------------------------------------------------===//
9883
9885 StringRef Name) {
9886 // typedef char* __builtin[_ms]_va_list;
9887 QualType T = Context->getPointerType(Context->CharTy);
9888 return Context->buildImplicitTypedef(T, Name);
9889}
9890
9892 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
9893}
9894
9896 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
9897}
9898
9900 // typedef void* __builtin_va_list;
9901 QualType T = Context->getPointerType(Context->VoidTy);
9902 return Context->buildImplicitTypedef(T, "__builtin_va_list");
9903}
9904
9905static TypedefDecl *
9907 // struct __va_list
9908 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
9909 if (Context->getLangOpts().CPlusPlus) {
9910 // namespace std { struct __va_list {
9911 auto *NS = NamespaceDecl::Create(
9912 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(),
9913 /*Inline=*/false, SourceLocation(), SourceLocation(),
9914 &Context->Idents.get("std"),
9915 /*PrevDecl=*/nullptr, /*Nested=*/false);
9916 NS->setImplicit();
9918 }
9919
9920 VaListTagDecl->startDefinition();
9921
9922 const size_t NumFields = 5;
9923 QualType FieldTypes[NumFields];
9924 const char *FieldNames[NumFields];
9925
9926 // void *__stack;
9927 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
9928 FieldNames[0] = "__stack";
9929
9930 // void *__gr_top;
9931 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
9932 FieldNames[1] = "__gr_top";
9933
9934 // void *__vr_top;
9935 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9936 FieldNames[2] = "__vr_top";
9937
9938 // int __gr_offs;
9939 FieldTypes[3] = Context->IntTy;
9940 FieldNames[3] = "__gr_offs";
9941
9942 // int __vr_offs;
9943 FieldTypes[4] = Context->IntTy;
9944 FieldNames[4] = "__vr_offs";
9945
9946 // Create fields
9947 for (unsigned i = 0; i < NumFields; ++i) {
9948 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9952 &Context->Idents.get(FieldNames[i]),
9953 FieldTypes[i], /*TInfo=*/nullptr,
9954 /*BitWidth=*/nullptr,
9955 /*Mutable=*/false,
9956 ICIS_NoInit);
9957 Field->setAccess(AS_public);
9958 VaListTagDecl->addDecl(Field);
9959 }
9960 VaListTagDecl->completeDefinition();
9961 Context->VaListTagDecl = VaListTagDecl;
9962 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
9963
9964 // } __builtin_va_list;
9965 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
9966}
9967
9969 // typedef struct __va_list_tag {
9971
9972 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9973 VaListTagDecl->startDefinition();
9974
9975 const size_t NumFields = 5;
9976 QualType FieldTypes[NumFields];
9977 const char *FieldNames[NumFields];
9978
9979 // unsigned char gpr;
9980 FieldTypes[0] = Context->UnsignedCharTy;
9981 FieldNames[0] = "gpr";
9982
9983 // unsigned char fpr;
9984 FieldTypes[1] = Context->UnsignedCharTy;
9985 FieldNames[1] = "fpr";
9986
9987 // unsigned short reserved;
9988 FieldTypes[2] = Context->UnsignedShortTy;
9989 FieldNames[2] = "reserved";
9990
9991 // void* overflow_arg_area;
9992 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
9993 FieldNames[3] = "overflow_arg_area";
9994
9995 // void* reg_save_area;
9996 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
9997 FieldNames[4] = "reg_save_area";
9998
9999 // Create fields
10000 for (unsigned i = 0; i < NumFields; ++i) {
10001 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
10004 &Context->Idents.get(FieldNames[i]),
10005 FieldTypes[i], /*TInfo=*/nullptr,
10006 /*BitWidth=*/nullptr,
10007 /*Mutable=*/false,
10008 ICIS_NoInit);
10009 Field->setAccess(AS_public);
10010 VaListTagDecl->addDecl(Field);
10011 }
10012 VaListTagDecl->completeDefinition();
10013 Context->VaListTagDecl = VaListTagDecl;
10014 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10015
10016 // } __va_list_tag;
10017 TypedefDecl *VaListTagTypedefDecl =
10018 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10019
10020 QualType VaListTagTypedefType =
10021 Context->getTypedefType(ElaboratedTypeKeyword::None,
10022 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10023
10024 // typedef __va_list_tag __builtin_va_list[1];
10025 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10026 QualType VaListTagArrayType = Context->getConstantArrayType(
10027 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10028 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10029}
10030
10031static TypedefDecl *
10033 // struct __va_list_tag {
10035 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10036 VaListTagDecl->startDefinition();
10037
10038 const size_t NumFields = 4;
10039 QualType FieldTypes[NumFields];
10040 const char *FieldNames[NumFields];
10041
10042 // unsigned gp_offset;
10043 FieldTypes[0] = Context->UnsignedIntTy;
10044 FieldNames[0] = "gp_offset";
10045
10046 // unsigned fp_offset;
10047 FieldTypes[1] = Context->UnsignedIntTy;
10048 FieldNames[1] = "fp_offset";
10049
10050 // void* overflow_arg_area;
10051 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10052 FieldNames[2] = "overflow_arg_area";
10053
10054 // void* reg_save_area;
10055 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10056 FieldNames[3] = "reg_save_area";
10057
10058 // Create fields
10059 for (unsigned i = 0; i < NumFields; ++i) {
10060 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10064 &Context->Idents.get(FieldNames[i]),
10065 FieldTypes[i], /*TInfo=*/nullptr,
10066 /*BitWidth=*/nullptr,
10067 /*Mutable=*/false,
10068 ICIS_NoInit);
10069 Field->setAccess(AS_public);
10070 VaListTagDecl->addDecl(Field);
10071 }
10072 VaListTagDecl->completeDefinition();
10073 Context->VaListTagDecl = VaListTagDecl;
10074 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10075
10076 // };
10077
10078 // typedef struct __va_list_tag __builtin_va_list[1];
10079 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10080 QualType VaListTagArrayType = Context->getConstantArrayType(
10081 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10082 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10083}
10084
10085static TypedefDecl *
10087 // struct __va_list
10088 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
10089 if (Context->getLangOpts().CPlusPlus) {
10090 // namespace std { struct __va_list {
10091 NamespaceDecl *NS;
10092 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
10093 Context->getTranslationUnitDecl(),
10094 /*Inline=*/false, SourceLocation(),
10095 SourceLocation(), &Context->Idents.get("std"),
10096 /*PrevDecl=*/nullptr, /*Nested=*/false);
10097 NS->setImplicit();
10098 VaListDecl->setDeclContext(NS);
10099 }
10100
10101 VaListDecl->startDefinition();
10102
10103 // void * __ap;
10104 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10105 VaListDecl,
10108 &Context->Idents.get("__ap"),
10109 Context->getPointerType(Context->VoidTy),
10110 /*TInfo=*/nullptr,
10111 /*BitWidth=*/nullptr,
10112 /*Mutable=*/false,
10113 ICIS_NoInit);
10114 Field->setAccess(AS_public);
10115 VaListDecl->addDecl(Field);
10116
10117 // };
10118 VaListDecl->completeDefinition();
10119 Context->VaListTagDecl = VaListDecl;
10120
10121 // typedef struct __va_list __builtin_va_list;
10122 CanQualType T = Context->getCanonicalTagType(VaListDecl);
10123 return Context->buildImplicitTypedef(T, "__builtin_va_list");
10124}
10125
10126static TypedefDecl *
10128 // struct __va_list_tag {
10130 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10131 VaListTagDecl->startDefinition();
10132
10133 const size_t NumFields = 4;
10134 QualType FieldTypes[NumFields];
10135 const char *FieldNames[NumFields];
10136
10137 // long __gpr;
10138 FieldTypes[0] = Context->LongTy;
10139 FieldNames[0] = "__gpr";
10140
10141 // long __fpr;
10142 FieldTypes[1] = Context->LongTy;
10143 FieldNames[1] = "__fpr";
10144
10145 // void *__overflow_arg_area;
10146 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10147 FieldNames[2] = "__overflow_arg_area";
10148
10149 // void *__reg_save_area;
10150 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10151 FieldNames[3] = "__reg_save_area";
10152
10153 // Create fields
10154 for (unsigned i = 0; i < NumFields; ++i) {
10155 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10159 &Context->Idents.get(FieldNames[i]),
10160 FieldTypes[i], /*TInfo=*/nullptr,
10161 /*BitWidth=*/nullptr,
10162 /*Mutable=*/false,
10163 ICIS_NoInit);
10164 Field->setAccess(AS_public);
10165 VaListTagDecl->addDecl(Field);
10166 }
10167 VaListTagDecl->completeDefinition();
10168 Context->VaListTagDecl = VaListTagDecl;
10169 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10170
10171 // };
10172
10173 // typedef __va_list_tag __builtin_va_list[1];
10174 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10175 QualType VaListTagArrayType = Context->getConstantArrayType(
10176 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10177
10178 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10179}
10180
10182 // typedef struct __va_list_tag {
10184 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10185 VaListTagDecl->startDefinition();
10186
10187 const size_t NumFields = 3;
10188 QualType FieldTypes[NumFields];
10189 const char *FieldNames[NumFields];
10190
10191 // void *CurrentSavedRegisterArea;
10192 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
10193 FieldNames[0] = "__current_saved_reg_area_pointer";
10194
10195 // void *SavedRegAreaEnd;
10196 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
10197 FieldNames[1] = "__saved_reg_area_end_pointer";
10198
10199 // void *OverflowArea;
10200 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10201 FieldNames[2] = "__overflow_area_pointer";
10202
10203 // Create fields
10204 for (unsigned i = 0; i < NumFields; ++i) {
10206 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
10207 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
10208 /*TInfo=*/nullptr,
10209 /*BitWidth=*/nullptr,
10210 /*Mutable=*/false, ICIS_NoInit);
10211 Field->setAccess(AS_public);
10212 VaListTagDecl->addDecl(Field);
10213 }
10214 VaListTagDecl->completeDefinition();
10215 Context->VaListTagDecl = VaListTagDecl;
10216 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10217
10218 // } __va_list_tag;
10219 TypedefDecl *VaListTagTypedefDecl =
10220 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10221
10222 QualType VaListTagTypedefType =
10223 Context->getTypedefType(ElaboratedTypeKeyword::None,
10224 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10225
10226 // typedef __va_list_tag __builtin_va_list[1];
10227 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10228 QualType VaListTagArrayType = Context->getConstantArrayType(
10229 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10230
10231 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10232}
10233
10234static TypedefDecl *
10236 // typedef struct __va_list_tag {
10237 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10238
10239 VaListTagDecl->startDefinition();
10240
10241 // int* __va_stk;
10242 // int* __va_reg;
10243 // int __va_ndx;
10244 constexpr size_t NumFields = 3;
10245 QualType FieldTypes[NumFields] = {Context->getPointerType(Context->IntTy),
10246 Context->getPointerType(Context->IntTy),
10247 Context->IntTy};
10248 const char *FieldNames[NumFields] = {"__va_stk", "__va_reg", "__va_ndx"};
10249
10250 // Create fields
10251 for (unsigned i = 0; i < NumFields; ++i) {
10254 &Context->Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
10255 /*BitWidth=*/nullptr,
10256 /*Mutable=*/false, ICIS_NoInit);
10257 Field->setAccess(AS_public);
10258 VaListTagDecl->addDecl(Field);
10259 }
10260 VaListTagDecl->completeDefinition();
10261 Context->VaListTagDecl = VaListTagDecl;
10262 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10263
10264 // } __va_list_tag;
10265 TypedefDecl *VaListTagTypedefDecl =
10266 Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
10267
10268 return VaListTagTypedefDecl;
10269}
10270
10273 switch (Kind) {
10275 return CreateCharPtrBuiltinVaListDecl(Context);
10277 return CreateVoidPtrBuiltinVaListDecl(Context);
10279 return CreateAArch64ABIBuiltinVaListDecl(Context);
10281 return CreatePowerABIBuiltinVaListDecl(Context);
10283 return CreateX86_64ABIBuiltinVaListDecl(Context);
10285 return CreateAAPCSABIBuiltinVaListDecl(Context);
10287 return CreateSystemZBuiltinVaListDecl(Context);
10289 return CreateHexagonBuiltinVaListDecl(Context);
10291 return CreateXtensaABIBuiltinVaListDecl(Context);
10292 }
10293
10294 llvm_unreachable("Unhandled __builtin_va_list type kind");
10295}
10296
10298 if (!BuiltinVaListDecl) {
10299 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
10300 assert(BuiltinVaListDecl->isImplicit());
10301 }
10302
10303 return BuiltinVaListDecl;
10304}
10305
10307 // Force the creation of VaListTagDecl by building the __builtin_va_list
10308 // declaration.
10309 if (!VaListTagDecl)
10310 (void)getBuiltinVaListDecl();
10311
10312 return VaListTagDecl;
10313}
10314
10316 if (!BuiltinMSVaListDecl)
10317 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
10318
10319 return BuiltinMSVaListDecl;
10320}
10321
10323 // Allow redecl custom type checking builtin for HLSL.
10324 if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
10325 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10326 return true;
10327 // Allow redecl custom type checking builtin for SPIR-V.
10328 if (getTargetInfo().getTriple().isSPIROrSPIRV() &&
10329 BuiltinInfo.isTSBuiltin(FD->getBuiltinID()) &&
10330 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10331 return true;
10332 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
10333}
10334
10336 assert(ObjCConstantStringType.isNull() &&
10337 "'NSConstantString' type already set!");
10338
10339 ObjCConstantStringType = getObjCInterfaceType(Decl);
10340}
10341
10342/// Retrieve the template name that corresponds to a non-empty
10343/// lookup.
10346 UnresolvedSetIterator End) const {
10347 unsigned size = End - Begin;
10348 assert(size > 1 && "set is not overloaded!");
10349
10350 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
10351 size * sizeof(FunctionTemplateDecl*));
10352 auto *OT = new (memory) OverloadedTemplateStorage(size);
10353
10354 NamedDecl **Storage = OT->getStorage();
10355 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
10356 NamedDecl *D = *I;
10357 assert(isa<FunctionTemplateDecl>(D) ||
10361 *Storage++ = D;
10362 }
10363
10364 return TemplateName(OT);
10365}
10366
10367/// Retrieve a template name representing an unqualified-id that has been
10368/// assumed to name a template for ADL purposes.
10370 auto *OT = new (*this) AssumedTemplateStorage(Name);
10371 return TemplateName(OT);
10372}
10373
10374/// Retrieve the template name that represents a qualified
10375/// template name such as \c std::vector.
10377 bool TemplateKeyword,
10378 TemplateName Template) const {
10379 assert(Template.getKind() == TemplateName::Template ||
10381
10382 if (Template.getAsTemplateDecl()->getKind() == Decl::TemplateTemplateParm) {
10383 assert(!Qualifier && "unexpected qualified template template parameter");
10384 assert(TemplateKeyword == false);
10385 return Template;
10386 }
10387
10388 // FIXME: Canonicalization?
10389 llvm::FoldingSetNodeID ID;
10390 QualifiedTemplateName::Profile(ID, Qualifier, TemplateKeyword, Template);
10391
10392 void *InsertPos = nullptr;
10394 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
10395 if (!QTN) {
10396 QTN = new (*this, alignof(QualifiedTemplateName))
10397 QualifiedTemplateName(Qualifier, TemplateKeyword, Template);
10398 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
10399 }
10400
10401 return TemplateName(QTN);
10402}
10403
10404/// Retrieve the template name that represents a dependent
10405/// template name such as \c MetaFun::template operator+.
10408 llvm::FoldingSetNodeID ID;
10409 S.Profile(ID);
10410
10411 void *InsertPos = nullptr;
10412 if (DependentTemplateName *QTN =
10413 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos))
10414 return TemplateName(QTN);
10415
10417 new (*this, alignof(DependentTemplateName)) DependentTemplateName(S);
10418 DependentTemplateNames.InsertNode(QTN, InsertPos);
10419 return TemplateName(QTN);
10420}
10421
10423 Decl *AssociatedDecl,
10424 unsigned Index,
10425 UnsignedOrNone PackIndex,
10426 bool Final) const {
10427 llvm::FoldingSetNodeID ID;
10428 SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
10429 Index, PackIndex, Final);
10430
10431 void *insertPos = nullptr;
10433 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
10434
10435 if (!subst) {
10436 subst = new (*this) SubstTemplateTemplateParmStorage(
10437 Replacement, AssociatedDecl, Index, PackIndex, Final);
10438 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
10439 }
10440
10441 return TemplateName(subst);
10442}
10443
10446 Decl *AssociatedDecl,
10447 unsigned Index, bool Final) const {
10448 auto &Self = const_cast<ASTContext &>(*this);
10449 llvm::FoldingSetNodeID ID;
10451 AssociatedDecl, Index, Final);
10452
10453 void *InsertPos = nullptr;
10455 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
10456
10457 if (!Subst) {
10458 Subst = new (*this) SubstTemplateTemplateParmPackStorage(
10459 ArgPack.pack_elements(), AssociatedDecl, Index, Final);
10460 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
10461 }
10462
10463 return TemplateName(Subst);
10464}
10465
10466/// Retrieve the template name that represents a template name
10467/// deduced from a specialization.
10470 DefaultArguments DefaultArgs) const {
10471 if (!DefaultArgs)
10472 return Underlying;
10473
10474 llvm::FoldingSetNodeID ID;
10475 DeducedTemplateStorage::Profile(ID, *this, Underlying, DefaultArgs);
10476
10477 void *InsertPos = nullptr;
10479 DeducedTemplates.FindNodeOrInsertPos(ID, InsertPos);
10480 if (!DTS) {
10481 void *Mem = Allocate(sizeof(DeducedTemplateStorage) +
10482 sizeof(TemplateArgument) * DefaultArgs.Args.size(),
10483 alignof(DeducedTemplateStorage));
10484 DTS = new (Mem) DeducedTemplateStorage(Underlying, DefaultArgs);
10485 DeducedTemplates.InsertNode(DTS, InsertPos);
10486 }
10487 return TemplateName(DTS);
10488}
10489
10490/// getFromTargetType - Given one of the integer types provided by
10491/// TargetInfo, produce the corresponding type. The unsigned @p Type
10492/// is actually a value of type @c TargetInfo::IntType.
10493CanQualType ASTContext::getFromTargetType(unsigned Type) const {
10494 switch (Type) {
10495 case TargetInfo::NoInt: return {};
10498 case TargetInfo::SignedShort: return ShortTy;
10500 case TargetInfo::SignedInt: return IntTy;
10502 case TargetInfo::SignedLong: return LongTy;
10506 }
10507
10508 llvm_unreachable("Unhandled TargetInfo::IntType value");
10509}
10510
10511//===----------------------------------------------------------------------===//
10512// Type Predicates.
10513//===----------------------------------------------------------------------===//
10514
10515/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
10516/// garbage collection attribute.
10517///
10519 if (getLangOpts().getGC() == LangOptions::NonGC)
10520 return Qualifiers::GCNone;
10521
10522 assert(getLangOpts().ObjC);
10523 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
10524
10525 // Default behaviour under objective-C's gc is for ObjC pointers
10526 // (or pointers to them) be treated as though they were declared
10527 // as __strong.
10528 if (GCAttrs == Qualifiers::GCNone) {
10530 return Qualifiers::Strong;
10531 else if (Ty->isPointerType())
10533 } else {
10534 // It's not valid to set GC attributes on anything that isn't a
10535 // pointer.
10536#ifndef NDEBUG
10538 while (const auto *AT = dyn_cast<ArrayType>(CT))
10539 CT = AT->getElementType();
10540 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
10541#endif
10542 }
10543 return GCAttrs;
10544}
10545
10546//===----------------------------------------------------------------------===//
10547// Type Compatibility Testing
10548//===----------------------------------------------------------------------===//
10549
10550/// areCompatVectorTypes - Return true if the two specified vector types are
10551/// compatible.
10552static bool areCompatVectorTypes(const VectorType *LHS,
10553 const VectorType *RHS) {
10554 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10555 return LHS->getElementType() == RHS->getElementType() &&
10556 LHS->getNumElements() == RHS->getNumElements();
10557}
10558
10559/// areCompatMatrixTypes - Return true if the two specified matrix types are
10560/// compatible.
10562 const ConstantMatrixType *RHS) {
10563 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10564 return LHS->getElementType() == RHS->getElementType() &&
10565 LHS->getNumRows() == RHS->getNumRows() &&
10566 LHS->getNumColumns() == RHS->getNumColumns();
10567}
10568
10570 QualType SecondVec) {
10571 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
10572 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
10573
10574 if (hasSameUnqualifiedType(FirstVec, SecondVec))
10575 return true;
10576
10577 // Treat Neon vector types and most AltiVec vector types as if they are the
10578 // equivalent GCC vector types.
10579 const auto *First = FirstVec->castAs<VectorType>();
10580 const auto *Second = SecondVec->castAs<VectorType>();
10581 if (First->getNumElements() == Second->getNumElements() &&
10582 hasSameType(First->getElementType(), Second->getElementType()) &&
10583 First->getVectorKind() != VectorKind::AltiVecPixel &&
10584 First->getVectorKind() != VectorKind::AltiVecBool &&
10587 First->getVectorKind() != VectorKind::SveFixedLengthData &&
10588 First->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10591 First->getVectorKind() != VectorKind::RVVFixedLengthData &&
10593 First->getVectorKind() != VectorKind::RVVFixedLengthMask &&
10595 First->getVectorKind() != VectorKind::RVVFixedLengthMask_1 &&
10597 First->getVectorKind() != VectorKind::RVVFixedLengthMask_2 &&
10599 First->getVectorKind() != VectorKind::RVVFixedLengthMask_4 &&
10601 return true;
10602
10603 return false;
10604}
10605
10606/// getRVVTypeSize - Return RVV vector register size.
10607static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) {
10608 assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type");
10609 auto VScale = Context.getTargetInfo().getVScaleRange(
10610 Context.getLangOpts(), TargetInfo::ArmStreamingKind::NotStreaming);
10611 if (!VScale)
10612 return 0;
10613
10614 ASTContext::BuiltinVectorTypeInfo Info = Context.getBuiltinVectorTypeInfo(Ty);
10615
10616 uint64_t EltSize = Context.getTypeSize(Info.ElementType);
10617 if (Info.ElementType == Context.BoolTy)
10618 EltSize = 1;
10619
10620 uint64_t MinElts = Info.EC.getKnownMinValue();
10621 return VScale->first * MinElts * EltSize;
10622}
10623
10625 QualType SecondType) {
10626 assert(
10627 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10628 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10629 "Expected RVV builtin type and vector type!");
10630
10631 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10632 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10633 if (const auto *VT = SecondType->getAs<VectorType>()) {
10634 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask) {
10636 return FirstType->isRVVVLSBuiltinType() &&
10637 Info.ElementType == BoolTy &&
10638 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)));
10639 }
10640 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1) {
10642 return FirstType->isRVVVLSBuiltinType() &&
10643 Info.ElementType == BoolTy &&
10644 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT) * 8));
10645 }
10646 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2) {
10648 return FirstType->isRVVVLSBuiltinType() &&
10649 Info.ElementType == BoolTy &&
10650 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 4);
10651 }
10652 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10654 return FirstType->isRVVVLSBuiltinType() &&
10655 Info.ElementType == BoolTy &&
10656 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 2);
10657 }
10658 if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
10659 VT->getVectorKind() == VectorKind::Generic)
10660 return FirstType->isRVVVLSBuiltinType() &&
10661 getTypeSize(SecondType) == getRVVTypeSize(*this, BT) &&
10662 hasSameType(VT->getElementType(),
10663 getBuiltinVectorTypeInfo(BT).ElementType);
10664 }
10665 }
10666 return false;
10667 };
10668
10669 return IsValidCast(FirstType, SecondType) ||
10670 IsValidCast(SecondType, FirstType);
10671}
10672
10674 QualType SecondType) {
10675 assert(
10676 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10677 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10678 "Expected RVV builtin type and vector type!");
10679
10680 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10681 const auto *BT = FirstType->getAs<BuiltinType>();
10682 if (!BT)
10683 return false;
10684
10685 if (!BT->isRVVVLSBuiltinType())
10686 return false;
10687
10688 const auto *VecTy = SecondType->getAs<VectorType>();
10689 if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) {
10691 getLangOpts().getLaxVectorConversions();
10692
10693 // If __riscv_v_fixed_vlen != N do not allow vector lax conversion.
10694 if (getTypeSize(SecondType) != getRVVTypeSize(*this, BT))
10695 return false;
10696
10697 // If -flax-vector-conversions=all is specified, the types are
10698 // certainly compatible.
10700 return true;
10701
10702 // If -flax-vector-conversions=integer is specified, the types are
10703 // compatible if the elements are integer types.
10705 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10706 FirstType->getRVVEltType(*this)->isIntegerType();
10707 }
10708
10709 return false;
10710 };
10711
10712 return IsLaxCompatible(FirstType, SecondType) ||
10713 IsLaxCompatible(SecondType, FirstType);
10714}
10715
10717 while (true) {
10718 // __strong id
10719 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
10720 if (Attr->getAttrKind() == attr::ObjCOwnership)
10721 return true;
10722
10723 Ty = Attr->getModifiedType();
10724
10725 // X *__strong (...)
10726 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
10727 Ty = Paren->getInnerType();
10728
10729 // We do not want to look through typedefs, typeof(expr),
10730 // typeof(type), or any other way that the type is somehow
10731 // abstracted.
10732 } else {
10733 return false;
10734 }
10735 }
10736}
10737
10738//===----------------------------------------------------------------------===//
10739// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
10740//===----------------------------------------------------------------------===//
10741
10742/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
10743/// inheritance hierarchy of 'rProto'.
10744bool
10746 ObjCProtocolDecl *rProto) const {
10747 if (declaresSameEntity(lProto, rProto))
10748 return true;
10749 for (auto *PI : rProto->protocols())
10750 if (ProtocolCompatibleWithProtocol(lProto, PI))
10751 return true;
10752 return false;
10753}
10754
10755/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
10756/// Class<pr1, ...>.
10758 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
10759 for (auto *lhsProto : lhs->quals()) {
10760 bool match = false;
10761 for (auto *rhsProto : rhs->quals()) {
10762 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
10763 match = true;
10764 break;
10765 }
10766 }
10767 if (!match)
10768 return false;
10769 }
10770 return true;
10771}
10772
10773/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
10774/// ObjCQualifiedIDType.
10776 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
10777 bool compare) {
10778 // Allow id<P..> and an 'id' in all cases.
10779 if (lhs->isObjCIdType() || rhs->isObjCIdType())
10780 return true;
10781
10782 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
10783 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
10785 return false;
10786
10787 if (lhs->isObjCQualifiedIdType()) {
10788 if (rhs->qual_empty()) {
10789 // If the RHS is a unqualified interface pointer "NSString*",
10790 // make sure we check the class hierarchy.
10791 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10792 for (auto *I : lhs->quals()) {
10793 // when comparing an id<P> on lhs with a static type on rhs,
10794 // see if static class implements all of id's protocols, directly or
10795 // through its super class and categories.
10796 if (!rhsID->ClassImplementsProtocol(I, true))
10797 return false;
10798 }
10799 }
10800 // If there are no qualifiers and no interface, we have an 'id'.
10801 return true;
10802 }
10803 // Both the right and left sides have qualifiers.
10804 for (auto *lhsProto : lhs->quals()) {
10805 bool match = false;
10806
10807 // when comparing an id<P> on lhs with a static type on rhs,
10808 // see if static class implements all of id's protocols, directly or
10809 // through its super class and categories.
10810 for (auto *rhsProto : rhs->quals()) {
10811 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10812 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10813 match = true;
10814 break;
10815 }
10816 }
10817 // If the RHS is a qualified interface pointer "NSString<P>*",
10818 // make sure we check the class hierarchy.
10819 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10820 for (auto *I : lhs->quals()) {
10821 // when comparing an id<P> on lhs with a static type on rhs,
10822 // see if static class implements all of id's protocols, directly or
10823 // through its super class and categories.
10824 if (rhsID->ClassImplementsProtocol(I, true)) {
10825 match = true;
10826 break;
10827 }
10828 }
10829 }
10830 if (!match)
10831 return false;
10832 }
10833
10834 return true;
10835 }
10836
10837 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
10838
10839 if (lhs->getInterfaceType()) {
10840 // If both the right and left sides have qualifiers.
10841 for (auto *lhsProto : lhs->quals()) {
10842 bool match = false;
10843
10844 // when comparing an id<P> on rhs with a static type on lhs,
10845 // see if static class implements all of id's protocols, directly or
10846 // through its super class and categories.
10847 // First, lhs protocols in the qualifier list must be found, direct
10848 // or indirect in rhs's qualifier list or it is a mismatch.
10849 for (auto *rhsProto : rhs->quals()) {
10850 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10851 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10852 match = true;
10853 break;
10854 }
10855 }
10856 if (!match)
10857 return false;
10858 }
10859
10860 // Static class's protocols, or its super class or category protocols
10861 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
10862 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
10863 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
10864 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
10865 // This is rather dubious but matches gcc's behavior. If lhs has
10866 // no type qualifier and its class has no static protocol(s)
10867 // assume that it is mismatch.
10868 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
10869 return false;
10870 for (auto *lhsProto : LHSInheritedProtocols) {
10871 bool match = false;
10872 for (auto *rhsProto : rhs->quals()) {
10873 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10874 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10875 match = true;
10876 break;
10877 }
10878 }
10879 if (!match)
10880 return false;
10881 }
10882 }
10883 return true;
10884 }
10885 return false;
10886}
10887
10888/// canAssignObjCInterfaces - Return true if the two interface types are
10889/// compatible for assignment from RHS to LHS. This handles validation of any
10890/// protocol qualifiers on the LHS or RHS.
10892 const ObjCObjectPointerType *RHSOPT) {
10893 const ObjCObjectType* LHS = LHSOPT->getObjectType();
10894 const ObjCObjectType* RHS = RHSOPT->getObjectType();
10895
10896 // If either type represents the built-in 'id' type, return true.
10897 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
10898 return true;
10899
10900 // Function object that propagates a successful result or handles
10901 // __kindof types.
10902 auto finish = [&](bool succeeded) -> bool {
10903 if (succeeded)
10904 return true;
10905
10906 if (!RHS->isKindOfType())
10907 return false;
10908
10909 // Strip off __kindof and protocol qualifiers, then check whether
10910 // we can assign the other way.
10912 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
10913 };
10914
10915 // Casts from or to id<P> are allowed when the other side has compatible
10916 // protocols.
10917 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
10918 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
10919 }
10920
10921 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
10922 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
10923 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
10924 }
10925
10926 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
10927 if (LHS->isObjCClass() && RHS->isObjCClass()) {
10928 return true;
10929 }
10930
10931 // If we have 2 user-defined types, fall into that path.
10932 if (LHS->getInterface() && RHS->getInterface()) {
10933 return finish(canAssignObjCInterfaces(LHS, RHS));
10934 }
10935
10936 return false;
10937}
10938
10939/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
10940/// for providing type-safety for objective-c pointers used to pass/return
10941/// arguments in block literals. When passed as arguments, passing 'A*' where
10942/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
10943/// not OK. For the return type, the opposite is not OK.
10945 const ObjCObjectPointerType *LHSOPT,
10946 const ObjCObjectPointerType *RHSOPT,
10947 bool BlockReturnType) {
10948
10949 // Function object that propagates a successful result or handles
10950 // __kindof types.
10951 auto finish = [&](bool succeeded) -> bool {
10952 if (succeeded)
10953 return true;
10954
10955 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
10956 if (!Expected->isKindOfType())
10957 return false;
10958
10959 // Strip off __kindof and protocol qualifiers, then check whether
10960 // we can assign the other way.
10962 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
10963 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
10964 BlockReturnType);
10965 };
10966
10967 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
10968 return true;
10969
10970 if (LHSOPT->isObjCBuiltinType()) {
10971 return finish(RHSOPT->isObjCBuiltinType() ||
10972 RHSOPT->isObjCQualifiedIdType());
10973 }
10974
10975 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
10976 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
10977 // Use for block parameters previous type checking for compatibility.
10978 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
10979 // Or corrected type checking as in non-compat mode.
10980 (!BlockReturnType &&
10981 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
10982 else
10984 (BlockReturnType ? LHSOPT : RHSOPT),
10985 (BlockReturnType ? RHSOPT : LHSOPT), false));
10986 }
10987
10988 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
10989 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
10990 if (LHS && RHS) { // We have 2 user-defined types.
10991 if (LHS != RHS) {
10992 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
10993 return finish(BlockReturnType);
10994 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
10995 return finish(!BlockReturnType);
10996 }
10997 else
10998 return true;
10999 }
11000 return false;
11001}
11002
11003/// Comparison routine for Objective-C protocols to be used with
11004/// llvm::array_pod_sort.
11006 ObjCProtocolDecl * const *rhs) {
11007 return (*lhs)->getName().compare((*rhs)->getName());
11008}
11009
11010/// getIntersectionOfProtocols - This routine finds the intersection of set
11011/// of protocols inherited from two distinct objective-c pointer objects with
11012/// the given common base.
11013/// It is used to build composite qualifier list of the composite type of
11014/// the conditional expression involving two objective-c pointer objects.
11015static
11017 const ObjCInterfaceDecl *CommonBase,
11018 const ObjCObjectPointerType *LHSOPT,
11019 const ObjCObjectPointerType *RHSOPT,
11020 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
11021
11022 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11023 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11024 assert(LHS->getInterface() && "LHS must have an interface base");
11025 assert(RHS->getInterface() && "RHS must have an interface base");
11026
11027 // Add all of the protocols for the LHS.
11029
11030 // Start with the protocol qualifiers.
11031 for (auto *proto : LHS->quals()) {
11032 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
11033 }
11034
11035 // Also add the protocols associated with the LHS interface.
11036 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
11037
11038 // Add all of the protocols for the RHS.
11040
11041 // Start with the protocol qualifiers.
11042 for (auto *proto : RHS->quals()) {
11043 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
11044 }
11045
11046 // Also add the protocols associated with the RHS interface.
11047 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
11048
11049 // Compute the intersection of the collected protocol sets.
11050 for (auto *proto : LHSProtocolSet) {
11051 if (RHSProtocolSet.count(proto))
11052 IntersectionSet.push_back(proto);
11053 }
11054
11055 // Compute the set of protocols that is implied by either the common type or
11056 // the protocols within the intersection.
11058 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
11059
11060 // Remove any implied protocols from the list of inherited protocols.
11061 if (!ImpliedProtocols.empty()) {
11062 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool {
11063 return ImpliedProtocols.contains(proto);
11064 });
11065 }
11066
11067 // Sort the remaining protocols by name.
11068 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
11070}
11071
11072/// Determine whether the first type is a subtype of the second.
11074 QualType rhs) {
11075 // Common case: two object pointers.
11076 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
11077 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
11078 if (lhsOPT && rhsOPT)
11079 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
11080
11081 // Two block pointers.
11082 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
11083 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
11084 if (lhsBlock && rhsBlock)
11085 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
11086
11087 // If either is an unqualified 'id' and the other is a block, it's
11088 // acceptable.
11089 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
11090 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
11091 return true;
11092
11093 return false;
11094}
11095
11096// Check that the given Objective-C type argument lists are equivalent.
11098 const ObjCInterfaceDecl *iface,
11099 ArrayRef<QualType> lhsArgs,
11100 ArrayRef<QualType> rhsArgs,
11101 bool stripKindOf) {
11102 if (lhsArgs.size() != rhsArgs.size())
11103 return false;
11104
11105 ObjCTypeParamList *typeParams = iface->getTypeParamList();
11106 if (!typeParams)
11107 return false;
11108
11109 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
11110 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
11111 continue;
11112
11113 switch (typeParams->begin()[i]->getVariance()) {
11115 if (!stripKindOf ||
11116 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
11117 rhsArgs[i].stripObjCKindOfType(ctx))) {
11118 return false;
11119 }
11120 break;
11121
11123 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
11124 return false;
11125 break;
11126
11128 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
11129 return false;
11130 break;
11131 }
11132 }
11133
11134 return true;
11135}
11136
11138 const ObjCObjectPointerType *Lptr,
11139 const ObjCObjectPointerType *Rptr) {
11140 const ObjCObjectType *LHS = Lptr->getObjectType();
11141 const ObjCObjectType *RHS = Rptr->getObjectType();
11142 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
11143 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
11144
11145 if (!LDecl || !RDecl)
11146 return {};
11147
11148 // When either LHS or RHS is a kindof type, we should return a kindof type.
11149 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
11150 // kindof(A).
11151 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
11152
11153 // Follow the left-hand side up the class hierarchy until we either hit a
11154 // root or find the RHS. Record the ancestors in case we don't find it.
11155 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
11156 LHSAncestors;
11157 while (true) {
11158 // Record this ancestor. We'll need this if the common type isn't in the
11159 // path from the LHS to the root.
11160 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
11161
11162 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
11163 // Get the type arguments.
11164 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
11165 bool anyChanges = false;
11166 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11167 // Both have type arguments, compare them.
11168 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11169 LHS->getTypeArgs(), RHS->getTypeArgs(),
11170 /*stripKindOf=*/true))
11171 return {};
11172 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11173 // If only one has type arguments, the result will not have type
11174 // arguments.
11175 LHSTypeArgs = {};
11176 anyChanges = true;
11177 }
11178
11179 // Compute the intersection of protocols.
11181 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
11182 Protocols);
11183 if (!Protocols.empty())
11184 anyChanges = true;
11185
11186 // If anything in the LHS will have changed, build a new result type.
11187 // If we need to return a kindof type but LHS is not a kindof type, we
11188 // build a new result type.
11189 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
11190 QualType Result = getObjCInterfaceType(LHS->getInterface());
11191 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
11192 anyKindOf || LHS->isKindOfType());
11194 }
11195
11196 return getObjCObjectPointerType(QualType(LHS, 0));
11197 }
11198
11199 // Find the superclass.
11200 QualType LHSSuperType = LHS->getSuperClassType();
11201 if (LHSSuperType.isNull())
11202 break;
11203
11204 LHS = LHSSuperType->castAs<ObjCObjectType>();
11205 }
11206
11207 // We didn't find anything by following the LHS to its root; now check
11208 // the RHS against the cached set of ancestors.
11209 while (true) {
11210 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
11211 if (KnownLHS != LHSAncestors.end()) {
11212 LHS = KnownLHS->second;
11213
11214 // Get the type arguments.
11215 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
11216 bool anyChanges = false;
11217 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11218 // Both have type arguments, compare them.
11219 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11220 LHS->getTypeArgs(), RHS->getTypeArgs(),
11221 /*stripKindOf=*/true))
11222 return {};
11223 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11224 // If only one has type arguments, the result will not have type
11225 // arguments.
11226 RHSTypeArgs = {};
11227 anyChanges = true;
11228 }
11229
11230 // Compute the intersection of protocols.
11232 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
11233 Protocols);
11234 if (!Protocols.empty())
11235 anyChanges = true;
11236
11237 // If we need to return a kindof type but RHS is not a kindof type, we
11238 // build a new result type.
11239 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
11240 QualType Result = getObjCInterfaceType(RHS->getInterface());
11241 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
11242 anyKindOf || RHS->isKindOfType());
11244 }
11245
11246 return getObjCObjectPointerType(QualType(RHS, 0));
11247 }
11248
11249 // Find the superclass of the RHS.
11250 QualType RHSSuperType = RHS->getSuperClassType();
11251 if (RHSSuperType.isNull())
11252 break;
11253
11254 RHS = RHSSuperType->castAs<ObjCObjectType>();
11255 }
11256
11257 return {};
11258}
11259
11261 const ObjCObjectType *RHS) {
11262 assert(LHS->getInterface() && "LHS is not an interface type");
11263 assert(RHS->getInterface() && "RHS is not an interface type");
11264
11265 // Verify that the base decls are compatible: the RHS must be a subclass of
11266 // the LHS.
11267 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
11268 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
11269 if (!IsSuperClass)
11270 return false;
11271
11272 // If the LHS has protocol qualifiers, determine whether all of them are
11273 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
11274 // LHS).
11275 if (LHS->getNumProtocols() > 0) {
11276 // OK if conversion of LHS to SuperClass results in narrowing of types
11277 // ; i.e., SuperClass may implement at least one of the protocols
11278 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
11279 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
11280 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
11281 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
11282 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
11283 // qualifiers.
11284 for (auto *RHSPI : RHS->quals())
11285 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
11286 // If there is no protocols associated with RHS, it is not a match.
11287 if (SuperClassInheritedProtocols.empty())
11288 return false;
11289
11290 for (const auto *LHSProto : LHS->quals()) {
11291 bool SuperImplementsProtocol = false;
11292 for (auto *SuperClassProto : SuperClassInheritedProtocols)
11293 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
11294 SuperImplementsProtocol = true;
11295 break;
11296 }
11297 if (!SuperImplementsProtocol)
11298 return false;
11299 }
11300 }
11301
11302 // If the LHS is specialized, we may need to check type arguments.
11303 if (LHS->isSpecialized()) {
11304 // Follow the superclass chain until we've matched the LHS class in the
11305 // hierarchy. This substitutes type arguments through.
11306 const ObjCObjectType *RHSSuper = RHS;
11307 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
11308 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
11309
11310 // If the RHS is specializd, compare type arguments.
11311 if (RHSSuper->isSpecialized() &&
11312 !sameObjCTypeArgs(*this, LHS->getInterface(),
11313 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
11314 /*stripKindOf=*/true)) {
11315 return false;
11316 }
11317 }
11318
11319 return true;
11320}
11321
11323 // get the "pointed to" types
11324 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
11325 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
11326
11327 if (!LHSOPT || !RHSOPT)
11328 return false;
11329
11330 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
11331 canAssignObjCInterfaces(RHSOPT, LHSOPT);
11332}
11333
11336 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
11337 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
11338}
11339
11340/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
11341/// both shall have the identically qualified version of a compatible type.
11342/// C99 6.2.7p1: Two types have compatible types if their types are the
11343/// same. See 6.7.[2,3,5] for additional rules.
11345 bool CompareUnqualified) {
11346 if (getLangOpts().CPlusPlus)
11347 return hasSameType(LHS, RHS);
11348
11349 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
11350}
11351
11353 return typesAreCompatible(LHS, RHS);
11354}
11355
11357 return !mergeTypes(LHS, RHS, true).isNull();
11358}
11359
11360/// mergeTransparentUnionType - if T is a transparent union type and a member
11361/// of T is compatible with SubType, return the merged type, else return
11362/// QualType()
11364 bool OfBlockPointer,
11365 bool Unqualified) {
11366 if (const RecordType *UT = T->getAsUnionType()) {
11367 RecordDecl *UD = UT->getOriginalDecl()->getMostRecentDecl();
11368 if (UD->hasAttr<TransparentUnionAttr>()) {
11369 for (const auto *I : UD->fields()) {
11370 QualType ET = I->getType().getUnqualifiedType();
11371 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
11372 if (!MT.isNull())
11373 return MT;
11374 }
11375 }
11376 }
11377
11378 return {};
11379}
11380
11381/// mergeFunctionParameterTypes - merge two types which appear as function
11382/// parameter types
11384 bool OfBlockPointer,
11385 bool Unqualified) {
11386 // GNU extension: two types are compatible if they appear as a function
11387 // argument, one of the types is a transparent union type and the other
11388 // type is compatible with a union member
11389 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
11390 Unqualified);
11391 if (!lmerge.isNull())
11392 return lmerge;
11393
11394 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
11395 Unqualified);
11396 if (!rmerge.isNull())
11397 return rmerge;
11398
11399 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
11400}
11401
11403 bool OfBlockPointer, bool Unqualified,
11404 bool AllowCXX,
11405 bool IsConditionalOperator) {
11406 const auto *lbase = lhs->castAs<FunctionType>();
11407 const auto *rbase = rhs->castAs<FunctionType>();
11408 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
11409 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
11410 bool allLTypes = true;
11411 bool allRTypes = true;
11412
11413 // Check return type
11414 QualType retType;
11415 if (OfBlockPointer) {
11416 QualType RHS = rbase->getReturnType();
11417 QualType LHS = lbase->getReturnType();
11418 bool UnqualifiedResult = Unqualified;
11419 if (!UnqualifiedResult)
11420 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
11421 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
11422 }
11423 else
11424 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
11425 Unqualified);
11426 if (retType.isNull())
11427 return {};
11428
11429 if (Unqualified)
11430 retType = retType.getUnqualifiedType();
11431
11432 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
11433 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
11434 if (Unqualified) {
11435 LRetType = LRetType.getUnqualifiedType();
11436 RRetType = RRetType.getUnqualifiedType();
11437 }
11438
11439 if (getCanonicalType(retType) != LRetType)
11440 allLTypes = false;
11441 if (getCanonicalType(retType) != RRetType)
11442 allRTypes = false;
11443
11444 // FIXME: double check this
11445 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
11446 // rbase->getRegParmAttr() != 0 &&
11447 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
11448 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
11449 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
11450
11451 // Compatible functions must have compatible calling conventions
11452 if (lbaseInfo.getCC() != rbaseInfo.getCC())
11453 return {};
11454
11455 // Regparm is part of the calling convention.
11456 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
11457 return {};
11458 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
11459 return {};
11460
11461 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
11462 return {};
11463 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
11464 return {};
11465 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
11466 return {};
11467
11468 // When merging declarations, it's common for supplemental information like
11469 // attributes to only be present in one of the declarations, and we generally
11470 // want type merging to preserve the union of information. So a merged
11471 // function type should be noreturn if it was noreturn in *either* operand
11472 // type.
11473 //
11474 // But for the conditional operator, this is backwards. The result of the
11475 // operator could be either operand, and its type should conservatively
11476 // reflect that. So a function type in a composite type is noreturn only
11477 // if it's noreturn in *both* operand types.
11478 //
11479 // Arguably, noreturn is a kind of subtype, and the conditional operator
11480 // ought to produce the most specific common supertype of its operand types.
11481 // That would differ from this rule in contravariant positions. However,
11482 // neither C nor C++ generally uses this kind of subtype reasoning. Also,
11483 // as a practical matter, it would only affect C code that does abstraction of
11484 // higher-order functions (taking noreturn callbacks!), which is uncommon to
11485 // say the least. So we use the simpler rule.
11486 bool NoReturn = IsConditionalOperator
11487 ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
11488 : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
11489 if (lbaseInfo.getNoReturn() != NoReturn)
11490 allLTypes = false;
11491 if (rbaseInfo.getNoReturn() != NoReturn)
11492 allRTypes = false;
11493
11494 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
11495
11496 std::optional<FunctionEffectSet> MergedFX;
11497
11498 if (lproto && rproto) { // two C99 style function prototypes
11499 assert((AllowCXX ||
11500 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
11501 "C++ shouldn't be here");
11502 // Compatible functions must have the same number of parameters
11503 if (lproto->getNumParams() != rproto->getNumParams())
11504 return {};
11505
11506 // Variadic and non-variadic functions aren't compatible
11507 if (lproto->isVariadic() != rproto->isVariadic())
11508 return {};
11509
11510 if (lproto->getMethodQuals() != rproto->getMethodQuals())
11511 return {};
11512
11513 // Function protos with different 'cfi_salt' values aren't compatible.
11514 if (lproto->getExtraAttributeInfo().CFISalt !=
11515 rproto->getExtraAttributeInfo().CFISalt)
11516 return {};
11517
11518 // Function effects are handled similarly to noreturn, see above.
11519 FunctionEffectsRef LHSFX = lproto->getFunctionEffects();
11520 FunctionEffectsRef RHSFX = rproto->getFunctionEffects();
11521 if (LHSFX != RHSFX) {
11522 if (IsConditionalOperator)
11523 MergedFX = FunctionEffectSet::getIntersection(LHSFX, RHSFX);
11524 else {
11526 MergedFX = FunctionEffectSet::getUnion(LHSFX, RHSFX, Errs);
11527 // Here we're discarding a possible error due to conflicts in the effect
11528 // sets. But we're not in a context where we can report it. The
11529 // operation does however guarantee maintenance of invariants.
11530 }
11531 if (*MergedFX != LHSFX)
11532 allLTypes = false;
11533 if (*MergedFX != RHSFX)
11534 allRTypes = false;
11535 }
11536
11538 bool canUseLeft, canUseRight;
11539 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
11540 newParamInfos))
11541 return {};
11542
11543 if (!canUseLeft)
11544 allLTypes = false;
11545 if (!canUseRight)
11546 allRTypes = false;
11547
11548 // Check parameter type compatibility
11550 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
11551 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
11552 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
11554 lParamType, rParamType, OfBlockPointer, Unqualified);
11555 if (paramType.isNull())
11556 return {};
11557
11558 if (Unqualified)
11559 paramType = paramType.getUnqualifiedType();
11560
11561 types.push_back(paramType);
11562 if (Unqualified) {
11563 lParamType = lParamType.getUnqualifiedType();
11564 rParamType = rParamType.getUnqualifiedType();
11565 }
11566
11567 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
11568 allLTypes = false;
11569 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
11570 allRTypes = false;
11571 }
11572
11573 if (allLTypes) return lhs;
11574 if (allRTypes) return rhs;
11575
11576 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
11577 EPI.ExtInfo = einfo;
11578 EPI.ExtParameterInfos =
11579 newParamInfos.empty() ? nullptr : newParamInfos.data();
11580 if (MergedFX)
11581 EPI.FunctionEffects = *MergedFX;
11582 return getFunctionType(retType, types, EPI);
11583 }
11584
11585 if (lproto) allRTypes = false;
11586 if (rproto) allLTypes = false;
11587
11588 const FunctionProtoType *proto = lproto ? lproto : rproto;
11589 if (proto) {
11590 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
11591 if (proto->isVariadic())
11592 return {};
11593 // Check that the types are compatible with the types that
11594 // would result from default argument promotions (C99 6.7.5.3p15).
11595 // The only types actually affected are promotable integer
11596 // types and floats, which would be passed as a different
11597 // type depending on whether the prototype is visible.
11598 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
11599 QualType paramTy = proto->getParamType(i);
11600
11601 // Look at the converted type of enum types, since that is the type used
11602 // to pass enum values.
11603 if (const auto *ED = paramTy->getAsEnumDecl()) {
11604 paramTy = ED->getIntegerType();
11605 if (paramTy.isNull())
11606 return {};
11607 }
11608
11609 if (isPromotableIntegerType(paramTy) ||
11610 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
11611 return {};
11612 }
11613
11614 if (allLTypes) return lhs;
11615 if (allRTypes) return rhs;
11616
11618 EPI.ExtInfo = einfo;
11619 if (MergedFX)
11620 EPI.FunctionEffects = *MergedFX;
11621 return getFunctionType(retType, proto->getParamTypes(), EPI);
11622 }
11623
11624 if (allLTypes) return lhs;
11625 if (allRTypes) return rhs;
11626 return getFunctionNoProtoType(retType, einfo);
11627}
11628
11629/// Given that we have an enum type and a non-enum type, try to merge them.
11630static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
11631 QualType other, bool isBlockReturnType) {
11632 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
11633 // a signed integer type, or an unsigned integer type.
11634 // Compatibility is based on the underlying type, not the promotion
11635 // type.
11636 QualType underlyingType =
11637 ET->getOriginalDecl()->getDefinitionOrSelf()->getIntegerType();
11638 if (underlyingType.isNull())
11639 return {};
11640 if (Context.hasSameType(underlyingType, other))
11641 return other;
11642
11643 // In block return types, we're more permissive and accept any
11644 // integral type of the same size.
11645 if (isBlockReturnType && other->isIntegerType() &&
11646 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
11647 return other;
11648
11649 return {};
11650}
11651
11653 // C17 and earlier and C++ disallow two tag definitions within the same TU
11654 // from being compatible.
11655 if (LangOpts.CPlusPlus || !LangOpts.C23)
11656 return {};
11657
11658 // C23, on the other hand, requires the members to be "the same enough", so
11659 // we use a structural equivalence check.
11662 getLangOpts(), *this, *this, NonEquivalentDecls,
11663 StructuralEquivalenceKind::Default, /*StrictTypeSpelling=*/false,
11664 /*Complain=*/false, /*ErrorOnTagTypeMismatch=*/true);
11665 return Ctx.IsEquivalent(LHS, RHS) ? LHS : QualType{};
11666}
11667
11668QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
11669 bool Unqualified, bool BlockReturnType,
11670 bool IsConditionalOperator) {
11671 // For C++ we will not reach this code with reference types (see below),
11672 // for OpenMP variant call overloading we might.
11673 //
11674 // C++ [expr]: If an expression initially has the type "reference to T", the
11675 // type is adjusted to "T" prior to any further analysis, the expression
11676 // designates the object or function denoted by the reference, and the
11677 // expression is an lvalue unless the reference is an rvalue reference and
11678 // the expression is a function call (possibly inside parentheses).
11679 auto *LHSRefTy = LHS->getAs<ReferenceType>();
11680 auto *RHSRefTy = RHS->getAs<ReferenceType>();
11681 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
11682 LHS->getTypeClass() == RHS->getTypeClass())
11683 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(),
11684 OfBlockPointer, Unqualified, BlockReturnType);
11685 if (LHSRefTy || RHSRefTy)
11686 return {};
11687
11688 if (Unqualified) {
11689 LHS = LHS.getUnqualifiedType();
11690 RHS = RHS.getUnqualifiedType();
11691 }
11692
11693 QualType LHSCan = getCanonicalType(LHS),
11694 RHSCan = getCanonicalType(RHS);
11695
11696 // If two types are identical, they are compatible.
11697 if (LHSCan == RHSCan)
11698 return LHS;
11699
11700 // If the qualifiers are different, the types aren't compatible... mostly.
11701 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11702 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11703 if (LQuals != RQuals) {
11704 // If any of these qualifiers are different, we have a type
11705 // mismatch.
11706 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11707 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
11708 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
11709 !LQuals.getPointerAuth().isEquivalent(RQuals.getPointerAuth()) ||
11710 LQuals.hasUnaligned() != RQuals.hasUnaligned())
11711 return {};
11712
11713 // Exactly one GC qualifier difference is allowed: __strong is
11714 // okay if the other type has no GC qualifier but is an Objective
11715 // C object pointer (i.e. implicitly strong by default). We fix
11716 // this by pretending that the unqualified type was actually
11717 // qualified __strong.
11718 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11719 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11720 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11721
11722 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
11723 return {};
11724
11725 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
11727 }
11728 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
11730 }
11731 return {};
11732 }
11733
11734 // Okay, qualifiers are equal.
11735
11736 Type::TypeClass LHSClass = LHSCan->getTypeClass();
11737 Type::TypeClass RHSClass = RHSCan->getTypeClass();
11738
11739 // We want to consider the two function types to be the same for these
11740 // comparisons, just force one to the other.
11741 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
11742 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
11743
11744 // Same as above for arrays
11745 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
11746 LHSClass = Type::ConstantArray;
11747 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
11748 RHSClass = Type::ConstantArray;
11749
11750 // ObjCInterfaces are just specialized ObjCObjects.
11751 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
11752 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
11753
11754 // Canonicalize ExtVector -> Vector.
11755 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
11756 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
11757
11758 // If the canonical type classes don't match.
11759 if (LHSClass != RHSClass) {
11760 // Note that we only have special rules for turning block enum
11761 // returns into block int returns, not vice-versa.
11762 if (const auto *ETy = LHS->getAsCanonical<EnumType>()) {
11763 return mergeEnumWithInteger(*this, ETy, RHS, false);
11764 }
11765 if (const EnumType *ETy = RHS->getAsCanonical<EnumType>()) {
11766 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
11767 }
11768 // allow block pointer type to match an 'id' type.
11769 if (OfBlockPointer && !BlockReturnType) {
11770 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
11771 return LHS;
11772 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
11773 return RHS;
11774 }
11775 // Allow __auto_type to match anything; it merges to the type with more
11776 // information.
11777 if (const auto *AT = LHS->getAs<AutoType>()) {
11778 if (!AT->isDeduced() && AT->isGNUAutoType())
11779 return RHS;
11780 }
11781 if (const auto *AT = RHS->getAs<AutoType>()) {
11782 if (!AT->isDeduced() && AT->isGNUAutoType())
11783 return LHS;
11784 }
11785 return {};
11786 }
11787
11788 // The canonical type classes match.
11789 switch (LHSClass) {
11790#define TYPE(Class, Base)
11791#define ABSTRACT_TYPE(Class, Base)
11792#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
11793#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
11794#define DEPENDENT_TYPE(Class, Base) case Type::Class:
11795#include "clang/AST/TypeNodes.inc"
11796 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
11797
11798 case Type::Auto:
11799 case Type::DeducedTemplateSpecialization:
11800 case Type::LValueReference:
11801 case Type::RValueReference:
11802 case Type::MemberPointer:
11803 llvm_unreachable("C++ should never be in mergeTypes");
11804
11805 case Type::ObjCInterface:
11806 case Type::IncompleteArray:
11807 case Type::VariableArray:
11808 case Type::FunctionProto:
11809 case Type::ExtVector:
11810 llvm_unreachable("Types are eliminated above");
11811
11812 case Type::Pointer:
11813 {
11814 // Merge two pointer types, while trying to preserve typedef info
11815 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
11816 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
11817 if (Unqualified) {
11818 LHSPointee = LHSPointee.getUnqualifiedType();
11819 RHSPointee = RHSPointee.getUnqualifiedType();
11820 }
11821 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
11822 Unqualified);
11823 if (ResultType.isNull())
11824 return {};
11825 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
11826 return LHS;
11827 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
11828 return RHS;
11829 return getPointerType(ResultType);
11830 }
11831 case Type::BlockPointer:
11832 {
11833 // Merge two block pointer types, while trying to preserve typedef info
11834 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
11835 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
11836 if (Unqualified) {
11837 LHSPointee = LHSPointee.getUnqualifiedType();
11838 RHSPointee = RHSPointee.getUnqualifiedType();
11839 }
11840 if (getLangOpts().OpenCL) {
11841 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
11842 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
11843 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
11844 // 6.12.5) thus the following check is asymmetric.
11845 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual, *this))
11846 return {};
11847 LHSPteeQual.removeAddressSpace();
11848 RHSPteeQual.removeAddressSpace();
11849 LHSPointee =
11850 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
11851 RHSPointee =
11852 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
11853 }
11854 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
11855 Unqualified);
11856 if (ResultType.isNull())
11857 return {};
11858 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
11859 return LHS;
11860 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
11861 return RHS;
11862 return getBlockPointerType(ResultType);
11863 }
11864 case Type::Atomic:
11865 {
11866 // Merge two pointer types, while trying to preserve typedef info
11867 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
11868 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
11869 if (Unqualified) {
11870 LHSValue = LHSValue.getUnqualifiedType();
11871 RHSValue = RHSValue.getUnqualifiedType();
11872 }
11873 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
11874 Unqualified);
11875 if (ResultType.isNull())
11876 return {};
11877 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
11878 return LHS;
11879 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
11880 return RHS;
11881 return getAtomicType(ResultType);
11882 }
11883 case Type::ConstantArray:
11884 {
11885 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
11886 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
11887 if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize())
11888 return {};
11889
11890 QualType LHSElem = getAsArrayType(LHS)->getElementType();
11891 QualType RHSElem = getAsArrayType(RHS)->getElementType();
11892 if (Unqualified) {
11893 LHSElem = LHSElem.getUnqualifiedType();
11894 RHSElem = RHSElem.getUnqualifiedType();
11895 }
11896
11897 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
11898 if (ResultType.isNull())
11899 return {};
11900
11901 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
11902 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
11903
11904 // If either side is a variable array, and both are complete, check whether
11905 // the current dimension is definite.
11906 if (LVAT || RVAT) {
11907 auto SizeFetch = [this](const VariableArrayType* VAT,
11908 const ConstantArrayType* CAT)
11909 -> std::pair<bool,llvm::APInt> {
11910 if (VAT) {
11911 std::optional<llvm::APSInt> TheInt;
11912 Expr *E = VAT->getSizeExpr();
11913 if (E && (TheInt = E->getIntegerConstantExpr(*this)))
11914 return std::make_pair(true, *TheInt);
11915 return std::make_pair(false, llvm::APSInt());
11916 }
11917 if (CAT)
11918 return std::make_pair(true, CAT->getSize());
11919 return std::make_pair(false, llvm::APInt());
11920 };
11921
11922 bool HaveLSize, HaveRSize;
11923 llvm::APInt LSize, RSize;
11924 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
11925 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
11926 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
11927 return {}; // Definite, but unequal, array dimension
11928 }
11929
11930 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
11931 return LHS;
11932 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
11933 return RHS;
11934 if (LCAT)
11935 return getConstantArrayType(ResultType, LCAT->getSize(),
11936 LCAT->getSizeExpr(), ArraySizeModifier(), 0);
11937 if (RCAT)
11938 return getConstantArrayType(ResultType, RCAT->getSize(),
11939 RCAT->getSizeExpr(), ArraySizeModifier(), 0);
11940 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
11941 return LHS;
11942 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
11943 return RHS;
11944 if (LVAT) {
11945 // FIXME: This isn't correct! But tricky to implement because
11946 // the array's size has to be the size of LHS, but the type
11947 // has to be different.
11948 return LHS;
11949 }
11950 if (RVAT) {
11951 // FIXME: This isn't correct! But tricky to implement because
11952 // the array's size has to be the size of RHS, but the type
11953 // has to be different.
11954 return RHS;
11955 }
11956 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
11957 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
11958 return getIncompleteArrayType(ResultType, ArraySizeModifier(), 0);
11959 }
11960 case Type::FunctionNoProto:
11961 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified,
11962 /*AllowCXX=*/false, IsConditionalOperator);
11963 case Type::Record:
11964 case Type::Enum:
11965 return mergeTagDefinitions(LHS, RHS);
11966 case Type::Builtin:
11967 // Only exactly equal builtin types are compatible, which is tested above.
11968 return {};
11969 case Type::Complex:
11970 // Distinct complex types are incompatible.
11971 return {};
11972 case Type::Vector:
11973 // FIXME: The merged type should be an ExtVector!
11974 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
11975 RHSCan->castAs<VectorType>()))
11976 return LHS;
11977 return {};
11978 case Type::ConstantMatrix:
11980 RHSCan->castAs<ConstantMatrixType>()))
11981 return LHS;
11982 return {};
11983 case Type::ObjCObject: {
11984 // Check if the types are assignment compatible.
11985 // FIXME: This should be type compatibility, e.g. whether
11986 // "LHS x; RHS x;" at global scope is legal.
11988 RHS->castAs<ObjCObjectType>()))
11989 return LHS;
11990 return {};
11991 }
11992 case Type::ObjCObjectPointer:
11993 if (OfBlockPointer) {
11996 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
11997 return LHS;
11998 return {};
11999 }
12002 return LHS;
12003 return {};
12004 case Type::Pipe:
12005 assert(LHS != RHS &&
12006 "Equivalent pipe types should have already been handled!");
12007 return {};
12008 case Type::ArrayParameter:
12009 assert(LHS != RHS &&
12010 "Equivalent ArrayParameter types should have already been handled!");
12011 return {};
12012 case Type::BitInt: {
12013 // Merge two bit-precise int types, while trying to preserve typedef info.
12014 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
12015 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
12016 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
12017 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
12018
12019 // Like unsigned/int, shouldn't have a type if they don't match.
12020 if (LHSUnsigned != RHSUnsigned)
12021 return {};
12022
12023 if (LHSBits != RHSBits)
12024 return {};
12025 return LHS;
12026 }
12027 case Type::HLSLAttributedResource: {
12028 const HLSLAttributedResourceType *LHSTy =
12029 LHS->castAs<HLSLAttributedResourceType>();
12030 const HLSLAttributedResourceType *RHSTy =
12031 RHS->castAs<HLSLAttributedResourceType>();
12032 assert(LHSTy->getWrappedType() == RHSTy->getWrappedType() &&
12033 LHSTy->getWrappedType()->isHLSLResourceType() &&
12034 "HLSLAttributedResourceType should always wrap __hlsl_resource_t");
12035
12036 if (LHSTy->getAttrs() == RHSTy->getAttrs() &&
12037 LHSTy->getContainedType() == RHSTy->getContainedType())
12038 return LHS;
12039 return {};
12040 }
12041 case Type::HLSLInlineSpirv:
12042 const HLSLInlineSpirvType *LHSTy = LHS->castAs<HLSLInlineSpirvType>();
12043 const HLSLInlineSpirvType *RHSTy = RHS->castAs<HLSLInlineSpirvType>();
12044
12045 if (LHSTy->getOpcode() == RHSTy->getOpcode() &&
12046 LHSTy->getSize() == RHSTy->getSize() &&
12047 LHSTy->getAlignment() == RHSTy->getAlignment()) {
12048 for (size_t I = 0; I < LHSTy->getOperands().size(); I++)
12049 if (LHSTy->getOperands()[I] != RHSTy->getOperands()[I])
12050 return {};
12051
12052 return LHS;
12053 }
12054 return {};
12055 }
12056
12057 llvm_unreachable("Invalid Type::Class!");
12058}
12059
12061 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
12062 bool &CanUseFirst, bool &CanUseSecond,
12064 assert(NewParamInfos.empty() && "param info list not empty");
12065 CanUseFirst = CanUseSecond = true;
12066 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
12067 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
12068
12069 // Fast path: if the first type doesn't have ext parameter infos,
12070 // we match if and only if the second type also doesn't have them.
12071 if (!FirstHasInfo && !SecondHasInfo)
12072 return true;
12073
12074 bool NeedParamInfo = false;
12075 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
12076 : SecondFnType->getExtParameterInfos().size();
12077
12078 for (size_t I = 0; I < E; ++I) {
12079 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
12080 if (FirstHasInfo)
12081 FirstParam = FirstFnType->getExtParameterInfo(I);
12082 if (SecondHasInfo)
12083 SecondParam = SecondFnType->getExtParameterInfo(I);
12084
12085 // Cannot merge unless everything except the noescape flag matches.
12086 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
12087 return false;
12088
12089 bool FirstNoEscape = FirstParam.isNoEscape();
12090 bool SecondNoEscape = SecondParam.isNoEscape();
12091 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
12092 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
12093 if (NewParamInfos.back().getOpaqueValue())
12094 NeedParamInfo = true;
12095 if (FirstNoEscape != IsNoEscape)
12096 CanUseFirst = false;
12097 if (SecondNoEscape != IsNoEscape)
12098 CanUseSecond = false;
12099 }
12100
12101 if (!NeedParamInfo)
12102 NewParamInfos.clear();
12103
12104 return true;
12105}
12106
12108 if (auto It = ObjCLayouts.find(D); It != ObjCLayouts.end()) {
12109 It->second = nullptr;
12110 for (auto *SubClass : ObjCSubClasses[D])
12111 ResetObjCLayout(SubClass);
12112 }
12113}
12114
12115/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
12116/// 'RHS' attributes and returns the merged version; including for function
12117/// return types.
12119 QualType LHSCan = getCanonicalType(LHS),
12120 RHSCan = getCanonicalType(RHS);
12121 // If two types are identical, they are compatible.
12122 if (LHSCan == RHSCan)
12123 return LHS;
12124 if (RHSCan->isFunctionType()) {
12125 if (!LHSCan->isFunctionType())
12126 return {};
12127 QualType OldReturnType =
12128 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
12129 QualType NewReturnType =
12130 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
12131 QualType ResReturnType =
12132 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
12133 if (ResReturnType.isNull())
12134 return {};
12135 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
12136 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
12137 // In either case, use OldReturnType to build the new function type.
12138 const auto *F = LHS->castAs<FunctionType>();
12139 if (const auto *FPT = cast<FunctionProtoType>(F)) {
12140 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12141 EPI.ExtInfo = getFunctionExtInfo(LHS);
12142 QualType ResultType =
12143 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
12144 return ResultType;
12145 }
12146 }
12147 return {};
12148 }
12149
12150 // If the qualifiers are different, the types can still be merged.
12151 Qualifiers LQuals = LHSCan.getLocalQualifiers();
12152 Qualifiers RQuals = RHSCan.getLocalQualifiers();
12153 if (LQuals != RQuals) {
12154 // If any of these qualifiers are different, we have a type mismatch.
12155 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
12156 LQuals.getAddressSpace() != RQuals.getAddressSpace())
12157 return {};
12158
12159 // Exactly one GC qualifier difference is allowed: __strong is
12160 // okay if the other type has no GC qualifier but is an Objective
12161 // C object pointer (i.e. implicitly strong by default). We fix
12162 // this by pretending that the unqualified type was actually
12163 // qualified __strong.
12164 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
12165 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
12166 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
12167
12168 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
12169 return {};
12170
12171 if (GC_L == Qualifiers::Strong)
12172 return LHS;
12173 if (GC_R == Qualifiers::Strong)
12174 return RHS;
12175 return {};
12176 }
12177
12178 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
12179 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12180 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12181 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
12182 if (ResQT == LHSBaseQT)
12183 return LHS;
12184 if (ResQT == RHSBaseQT)
12185 return RHS;
12186 }
12187 return {};
12188}
12189
12190//===----------------------------------------------------------------------===//
12191// Integer Predicates
12192//===----------------------------------------------------------------------===//
12193
12195 if (const auto *ED = T->getAsEnumDecl())
12196 T = ED->getIntegerType();
12197 if (T->isBooleanType())
12198 return 1;
12199 if (const auto *EIT = T->getAs<BitIntType>())
12200 return EIT->getNumBits();
12201 // For builtin types, just use the standard type sizing method
12202 return (unsigned)getTypeSize(T);
12203}
12204
12206 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12207 T->isFixedPointType()) &&
12208 "Unexpected type");
12209
12210 // Turn <4 x signed int> -> <4 x unsigned int>
12211 if (const auto *VTy = T->getAs<VectorType>())
12212 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
12213 VTy->getNumElements(), VTy->getVectorKind());
12214
12215 // For _BitInt, return an unsigned _BitInt with same width.
12216 if (const auto *EITy = T->getAs<BitIntType>())
12217 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits());
12218
12219 // For enums, get the underlying integer type of the enum, and let the general
12220 // integer type signchanging code handle it.
12221 if (const auto *ED = T->getAsEnumDecl())
12222 T = ED->getIntegerType();
12223
12224 switch (T->castAs<BuiltinType>()->getKind()) {
12225 case BuiltinType::Char_U:
12226 // Plain `char` is mapped to `unsigned char` even if it's already unsigned
12227 case BuiltinType::Char_S:
12228 case BuiltinType::SChar:
12229 case BuiltinType::Char8:
12230 return UnsignedCharTy;
12231 case BuiltinType::Short:
12232 return UnsignedShortTy;
12233 case BuiltinType::Int:
12234 return UnsignedIntTy;
12235 case BuiltinType::Long:
12236 return UnsignedLongTy;
12237 case BuiltinType::LongLong:
12238 return UnsignedLongLongTy;
12239 case BuiltinType::Int128:
12240 return UnsignedInt128Ty;
12241 // wchar_t is special. It is either signed or not, but when it's signed,
12242 // there's no matching "unsigned wchar_t". Therefore we return the unsigned
12243 // version of its underlying type instead.
12244 case BuiltinType::WChar_S:
12245 return getUnsignedWCharType();
12246
12247 case BuiltinType::ShortAccum:
12248 return UnsignedShortAccumTy;
12249 case BuiltinType::Accum:
12250 return UnsignedAccumTy;
12251 case BuiltinType::LongAccum:
12252 return UnsignedLongAccumTy;
12253 case BuiltinType::SatShortAccum:
12255 case BuiltinType::SatAccum:
12256 return SatUnsignedAccumTy;
12257 case BuiltinType::SatLongAccum:
12259 case BuiltinType::ShortFract:
12260 return UnsignedShortFractTy;
12261 case BuiltinType::Fract:
12262 return UnsignedFractTy;
12263 case BuiltinType::LongFract:
12264 return UnsignedLongFractTy;
12265 case BuiltinType::SatShortFract:
12267 case BuiltinType::SatFract:
12268 return SatUnsignedFractTy;
12269 case BuiltinType::SatLongFract:
12271 default:
12272 assert((T->hasUnsignedIntegerRepresentation() ||
12273 T->isUnsignedFixedPointType()) &&
12274 "Unexpected signed integer or fixed point type");
12275 return T;
12276 }
12277}
12278
12280 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12281 T->isFixedPointType()) &&
12282 "Unexpected type");
12283
12284 // Turn <4 x unsigned int> -> <4 x signed int>
12285 if (const auto *VTy = T->getAs<VectorType>())
12286 return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
12287 VTy->getNumElements(), VTy->getVectorKind());
12288
12289 // For _BitInt, return a signed _BitInt with same width.
12290 if (const auto *EITy = T->getAs<BitIntType>())
12291 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits());
12292
12293 // For enums, get the underlying integer type of the enum, and let the general
12294 // integer type signchanging code handle it.
12295 if (const auto *ED = T->getAsEnumDecl())
12296 T = ED->getIntegerType();
12297
12298 switch (T->castAs<BuiltinType>()->getKind()) {
12299 case BuiltinType::Char_S:
12300 // Plain `char` is mapped to `signed char` even if it's already signed
12301 case BuiltinType::Char_U:
12302 case BuiltinType::UChar:
12303 case BuiltinType::Char8:
12304 return SignedCharTy;
12305 case BuiltinType::UShort:
12306 return ShortTy;
12307 case BuiltinType::UInt:
12308 return IntTy;
12309 case BuiltinType::ULong:
12310 return LongTy;
12311 case BuiltinType::ULongLong:
12312 return LongLongTy;
12313 case BuiltinType::UInt128:
12314 return Int128Ty;
12315 // wchar_t is special. It is either unsigned or not, but when it's unsigned,
12316 // there's no matching "signed wchar_t". Therefore we return the signed
12317 // version of its underlying type instead.
12318 case BuiltinType::WChar_U:
12319 return getSignedWCharType();
12320
12321 case BuiltinType::UShortAccum:
12322 return ShortAccumTy;
12323 case BuiltinType::UAccum:
12324 return AccumTy;
12325 case BuiltinType::ULongAccum:
12326 return LongAccumTy;
12327 case BuiltinType::SatUShortAccum:
12328 return SatShortAccumTy;
12329 case BuiltinType::SatUAccum:
12330 return SatAccumTy;
12331 case BuiltinType::SatULongAccum:
12332 return SatLongAccumTy;
12333 case BuiltinType::UShortFract:
12334 return ShortFractTy;
12335 case BuiltinType::UFract:
12336 return FractTy;
12337 case BuiltinType::ULongFract:
12338 return LongFractTy;
12339 case BuiltinType::SatUShortFract:
12340 return SatShortFractTy;
12341 case BuiltinType::SatUFract:
12342 return SatFractTy;
12343 case BuiltinType::SatULongFract:
12344 return SatLongFractTy;
12345 default:
12346 assert(
12347 (T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
12348 "Unexpected signed integer or fixed point type");
12349 return T;
12350 }
12351}
12352
12354
12357
12358//===----------------------------------------------------------------------===//
12359// Builtin Type Computation
12360//===----------------------------------------------------------------------===//
12361
12362/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
12363/// pointer over the consumed characters. This returns the resultant type. If
12364/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
12365/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
12366/// a vector of "i*".
12367///
12368/// RequiresICE is filled in on return to indicate whether the value is required
12369/// to be an Integer Constant Expression.
12370static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
12372 bool &RequiresICE,
12373 bool AllowTypeModifiers) {
12374 // Modifiers.
12375 int HowLong = 0;
12376 bool Signed = false, Unsigned = false;
12377 RequiresICE = false;
12378
12379 // Read the prefixed modifiers first.
12380 bool Done = false;
12381 #ifndef NDEBUG
12382 bool IsSpecial = false;
12383 #endif
12384 while (!Done) {
12385 switch (*Str++) {
12386 default: Done = true; --Str; break;
12387 case 'I':
12388 RequiresICE = true;
12389 break;
12390 case 'S':
12391 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
12392 assert(!Signed && "Can't use 'S' modifier multiple times!");
12393 Signed = true;
12394 break;
12395 case 'U':
12396 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
12397 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
12398 Unsigned = true;
12399 break;
12400 case 'L':
12401 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
12402 assert(HowLong <= 2 && "Can't have LLLL modifier");
12403 ++HowLong;
12404 break;
12405 case 'N':
12406 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
12407 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12408 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
12409 #ifndef NDEBUG
12410 IsSpecial = true;
12411 #endif
12412 if (Context.getTargetInfo().getLongWidth() == 32)
12413 ++HowLong;
12414 break;
12415 case 'W':
12416 // This modifier represents int64 type.
12417 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12418 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
12419 #ifndef NDEBUG
12420 IsSpecial = true;
12421 #endif
12422 switch (Context.getTargetInfo().getInt64Type()) {
12423 default:
12424 llvm_unreachable("Unexpected integer type");
12426 HowLong = 1;
12427 break;
12429 HowLong = 2;
12430 break;
12431 }
12432 break;
12433 case 'Z':
12434 // This modifier represents int32 type.
12435 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12436 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
12437 #ifndef NDEBUG
12438 IsSpecial = true;
12439 #endif
12440 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
12441 default:
12442 llvm_unreachable("Unexpected integer type");
12444 HowLong = 0;
12445 break;
12447 HowLong = 1;
12448 break;
12450 HowLong = 2;
12451 break;
12452 }
12453 break;
12454 case 'O':
12455 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12456 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
12457 #ifndef NDEBUG
12458 IsSpecial = true;
12459 #endif
12460 if (Context.getLangOpts().OpenCL)
12461 HowLong = 1;
12462 else
12463 HowLong = 2;
12464 break;
12465 }
12466 }
12467
12468 QualType Type;
12469
12470 // Read the base type.
12471 switch (*Str++) {
12472 default: llvm_unreachable("Unknown builtin type letter!");
12473 case 'x':
12474 assert(HowLong == 0 && !Signed && !Unsigned &&
12475 "Bad modifiers used with 'x'!");
12476 Type = Context.Float16Ty;
12477 break;
12478 case 'y':
12479 assert(HowLong == 0 && !Signed && !Unsigned &&
12480 "Bad modifiers used with 'y'!");
12481 Type = Context.BFloat16Ty;
12482 break;
12483 case 'v':
12484 assert(HowLong == 0 && !Signed && !Unsigned &&
12485 "Bad modifiers used with 'v'!");
12486 Type = Context.VoidTy;
12487 break;
12488 case 'h':
12489 assert(HowLong == 0 && !Signed && !Unsigned &&
12490 "Bad modifiers used with 'h'!");
12491 Type = Context.HalfTy;
12492 break;
12493 case 'f':
12494 assert(HowLong == 0 && !Signed && !Unsigned &&
12495 "Bad modifiers used with 'f'!");
12496 Type = Context.FloatTy;
12497 break;
12498 case 'd':
12499 assert(HowLong < 3 && !Signed && !Unsigned &&
12500 "Bad modifiers used with 'd'!");
12501 if (HowLong == 1)
12502 Type = Context.LongDoubleTy;
12503 else if (HowLong == 2)
12504 Type = Context.Float128Ty;
12505 else
12506 Type = Context.DoubleTy;
12507 break;
12508 case 's':
12509 assert(HowLong == 0 && "Bad modifiers used with 's'!");
12510 if (Unsigned)
12511 Type = Context.UnsignedShortTy;
12512 else
12513 Type = Context.ShortTy;
12514 break;
12515 case 'i':
12516 if (HowLong == 3)
12517 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
12518 else if (HowLong == 2)
12519 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
12520 else if (HowLong == 1)
12521 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
12522 else
12523 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
12524 break;
12525 case 'c':
12526 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
12527 if (Signed)
12528 Type = Context.SignedCharTy;
12529 else if (Unsigned)
12530 Type = Context.UnsignedCharTy;
12531 else
12532 Type = Context.CharTy;
12533 break;
12534 case 'b': // boolean
12535 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
12536 Type = Context.BoolTy;
12537 break;
12538 case 'z': // size_t.
12539 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
12540 Type = Context.getSizeType();
12541 break;
12542 case 'w': // wchar_t.
12543 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
12544 Type = Context.getWideCharType();
12545 break;
12546 case 'F':
12547 Type = Context.getCFConstantStringType();
12548 break;
12549 case 'G':
12550 Type = Context.getObjCIdType();
12551 break;
12552 case 'H':
12553 Type = Context.getObjCSelType();
12554 break;
12555 case 'M':
12556 Type = Context.getObjCSuperType();
12557 break;
12558 case 'a':
12559 Type = Context.getBuiltinVaListType();
12560 assert(!Type.isNull() && "builtin va list type not initialized!");
12561 break;
12562 case 'A':
12563 // This is a "reference" to a va_list; however, what exactly
12564 // this means depends on how va_list is defined. There are two
12565 // different kinds of va_list: ones passed by value, and ones
12566 // passed by reference. An example of a by-value va_list is
12567 // x86, where va_list is a char*. An example of by-ref va_list
12568 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
12569 // we want this argument to be a char*&; for x86-64, we want
12570 // it to be a __va_list_tag*.
12571 Type = Context.getBuiltinVaListType();
12572 assert(!Type.isNull() && "builtin va list type not initialized!");
12573 if (Type->isArrayType())
12574 Type = Context.getArrayDecayedType(Type);
12575 else
12576 Type = Context.getLValueReferenceType(Type);
12577 break;
12578 case 'q': {
12579 char *End;
12580 unsigned NumElements = strtoul(Str, &End, 10);
12581 assert(End != Str && "Missing vector size");
12582 Str = End;
12583
12584 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12585 RequiresICE, false);
12586 assert(!RequiresICE && "Can't require vector ICE");
12587
12588 Type = Context.getScalableVectorType(ElementType, NumElements);
12589 break;
12590 }
12591 case 'Q': {
12592 switch (*Str++) {
12593 case 'a': {
12594 Type = Context.SveCountTy;
12595 break;
12596 }
12597 case 'b': {
12598 Type = Context.AMDGPUBufferRsrcTy;
12599 break;
12600 }
12601 default:
12602 llvm_unreachable("Unexpected target builtin type");
12603 }
12604 break;
12605 }
12606 case 'V': {
12607 char *End;
12608 unsigned NumElements = strtoul(Str, &End, 10);
12609 assert(End != Str && "Missing vector size");
12610 Str = End;
12611
12612 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12613 RequiresICE, false);
12614 assert(!RequiresICE && "Can't require vector ICE");
12615
12616 // TODO: No way to make AltiVec vectors in builtins yet.
12617 Type = Context.getVectorType(ElementType, NumElements, VectorKind::Generic);
12618 break;
12619 }
12620 case 'E': {
12621 char *End;
12622
12623 unsigned NumElements = strtoul(Str, &End, 10);
12624 assert(End != Str && "Missing vector size");
12625
12626 Str = End;
12627
12628 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12629 false);
12630 Type = Context.getExtVectorType(ElementType, NumElements);
12631 break;
12632 }
12633 case 'X': {
12634 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12635 false);
12636 assert(!RequiresICE && "Can't require complex ICE");
12637 Type = Context.getComplexType(ElementType);
12638 break;
12639 }
12640 case 'Y':
12641 Type = Context.getPointerDiffType();
12642 break;
12643 case 'P':
12644 Type = Context.getFILEType();
12645 if (Type.isNull()) {
12647 return {};
12648 }
12649 break;
12650 case 'J':
12651 if (Signed)
12652 Type = Context.getsigjmp_bufType();
12653 else
12654 Type = Context.getjmp_bufType();
12655
12656 if (Type.isNull()) {
12658 return {};
12659 }
12660 break;
12661 case 'K':
12662 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
12663 Type = Context.getucontext_tType();
12664
12665 if (Type.isNull()) {
12667 return {};
12668 }
12669 break;
12670 case 'p':
12671 Type = Context.getProcessIDType();
12672 break;
12673 case 'm':
12674 Type = Context.MFloat8Ty;
12675 break;
12676 }
12677
12678 // If there are modifiers and if we're allowed to parse them, go for it.
12679 Done = !AllowTypeModifiers;
12680 while (!Done) {
12681 switch (char c = *Str++) {
12682 default: Done = true; --Str; break;
12683 case '*':
12684 case '&': {
12685 // Both pointers and references can have their pointee types
12686 // qualified with an address space.
12687 char *End;
12688 unsigned AddrSpace = strtoul(Str, &End, 10);
12689 if (End != Str) {
12690 // Note AddrSpace == 0 is not the same as an unspecified address space.
12691 Type = Context.getAddrSpaceQualType(
12692 Type,
12693 Context.getLangASForBuiltinAddressSpace(AddrSpace));
12694 Str = End;
12695 }
12696 if (c == '*')
12697 Type = Context.getPointerType(Type);
12698 else
12699 Type = Context.getLValueReferenceType(Type);
12700 break;
12701 }
12702 // FIXME: There's no way to have a built-in with an rvalue ref arg.
12703 case 'C':
12704 Type = Type.withConst();
12705 break;
12706 case 'D':
12707 Type = Context.getVolatileType(Type);
12708 break;
12709 case 'R':
12710 Type = Type.withRestrict();
12711 break;
12712 }
12713 }
12714
12715 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
12716 "Integer constant 'I' type must be an integer");
12717
12718 return Type;
12719}
12720
12721// On some targets such as PowerPC, some of the builtins are defined with custom
12722// type descriptors for target-dependent types. These descriptors are decoded in
12723// other functions, but it may be useful to be able to fall back to default
12724// descriptor decoding to define builtins mixing target-dependent and target-
12725// independent types. This function allows decoding one type descriptor with
12726// default decoding.
12727QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
12728 GetBuiltinTypeError &Error, bool &RequireICE,
12729 bool AllowTypeModifiers) const {
12730 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
12731}
12732
12733/// GetBuiltinType - Return the type for the specified builtin.
12736 unsigned *IntegerConstantArgs) const {
12737 const char *TypeStr = BuiltinInfo.getTypeString(Id);
12738 if (TypeStr[0] == '\0') {
12740 return {};
12741 }
12742
12743 SmallVector<QualType, 8> ArgTypes;
12744
12745 bool RequiresICE = false;
12746 Error = GE_None;
12747 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
12748 RequiresICE, true);
12749 if (Error != GE_None)
12750 return {};
12751
12752 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
12753
12754 while (TypeStr[0] && TypeStr[0] != '.') {
12755 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
12756 if (Error != GE_None)
12757 return {};
12758
12759 // If this argument is required to be an IntegerConstantExpression and the
12760 // caller cares, fill in the bitmask we return.
12761 if (RequiresICE && IntegerConstantArgs)
12762 *IntegerConstantArgs |= 1 << ArgTypes.size();
12763
12764 // Do array -> pointer decay. The builtin should use the decayed type.
12765 if (Ty->isArrayType())
12766 Ty = getArrayDecayedType(Ty);
12767
12768 ArgTypes.push_back(Ty);
12769 }
12770
12771 if (Id == Builtin::BI__GetExceptionInfo)
12772 return {};
12773
12774 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
12775 "'.' should only occur at end of builtin type list!");
12776
12777 bool Variadic = (TypeStr[0] == '.');
12778
12779 FunctionType::ExtInfo EI(Target->getDefaultCallingConv());
12780 if (BuiltinInfo.isNoReturn(Id))
12781 EI = EI.withNoReturn(true);
12782
12783 // We really shouldn't be making a no-proto type here.
12784 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
12785 return getFunctionNoProtoType(ResType, EI);
12786
12788 EPI.ExtInfo = EI;
12789 EPI.Variadic = Variadic;
12790 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
12791 EPI.ExceptionSpec.Type =
12793
12794 return getFunctionType(ResType, ArgTypes, EPI);
12795}
12796
12798 const FunctionDecl *FD) {
12799 if (!FD->isExternallyVisible())
12800 return GVA_Internal;
12801
12802 // Non-user-provided functions get emitted as weak definitions with every
12803 // use, no matter whether they've been explicitly instantiated etc.
12804 if (!FD->isUserProvided())
12805 return GVA_DiscardableODR;
12806
12808 switch (FD->getTemplateSpecializationKind()) {
12809 case TSK_Undeclared:
12812 break;
12813
12815 return GVA_StrongODR;
12816
12817 // C++11 [temp.explicit]p10:
12818 // [ Note: The intent is that an inline function that is the subject of
12819 // an explicit instantiation declaration will still be implicitly
12820 // instantiated when used so that the body can be considered for
12821 // inlining, but that no out-of-line copy of the inline function would be
12822 // generated in the translation unit. -- end note ]
12825
12828 break;
12829 }
12830
12831 if (!FD->isInlined())
12832 return External;
12833
12834 if ((!Context.getLangOpts().CPlusPlus &&
12835 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12836 !FD->hasAttr<DLLExportAttr>()) ||
12837 FD->hasAttr<GNUInlineAttr>()) {
12838 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
12839
12840 // GNU or C99 inline semantics. Determine whether this symbol should be
12841 // externally visible.
12843 return External;
12844
12845 // C99 inline semantics, where the symbol is not externally visible.
12847 }
12848
12849 // Functions specified with extern and inline in -fms-compatibility mode
12850 // forcibly get emitted. While the body of the function cannot be later
12851 // replaced, the function definition cannot be discarded.
12852 if (FD->isMSExternInline())
12853 return GVA_StrongODR;
12854
12855 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12857 cast<CXXConstructorDecl>(FD)->isInheritingConstructor())
12858 // Our approach to inheriting constructors is fundamentally different from
12859 // that used by the MS ABI, so keep our inheriting constructor thunks
12860 // internal rather than trying to pick an unambiguous mangling for them.
12861 return GVA_Internal;
12862
12863 return GVA_DiscardableODR;
12864}
12865
12867 const Decl *D, GVALinkage L) {
12868 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
12869 // dllexport/dllimport on inline functions.
12870 if (D->hasAttr<DLLImportAttr>()) {
12871 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
12873 } else if (D->hasAttr<DLLExportAttr>()) {
12874 if (L == GVA_DiscardableODR)
12875 return GVA_StrongODR;
12876 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
12877 // Device-side functions with __global__ attribute must always be
12878 // visible externally so they can be launched from host.
12879 if (D->hasAttr<CUDAGlobalAttr>() &&
12880 (L == GVA_DiscardableODR || L == GVA_Internal))
12881 return GVA_StrongODR;
12882 // Single source offloading languages like CUDA/HIP need to be able to
12883 // access static device variables from host code of the same compilation
12884 // unit. This is done by externalizing the static variable with a shared
12885 // name between the host and device compilation which is the same for the
12886 // same compilation unit whereas different among different compilation
12887 // units.
12888 if (Context.shouldExternalize(D))
12889 return GVA_StrongExternal;
12890 }
12891 return L;
12892}
12893
12894/// Adjust the GVALinkage for a declaration based on what an external AST source
12895/// knows about whether there can be other definitions of this declaration.
12896static GVALinkage
12898 GVALinkage L) {
12899 ExternalASTSource *Source = Ctx.getExternalSource();
12900 if (!Source)
12901 return L;
12902
12903 switch (Source->hasExternalDefinitions(D)) {
12905 // Other translation units rely on us to provide the definition.
12906 if (L == GVA_DiscardableODR)
12907 return GVA_StrongODR;
12908 break;
12909
12912
12914 break;
12915 }
12916 return L;
12917}
12918
12924
12926 const VarDecl *VD) {
12927 // As an extension for interactive REPLs, make sure constant variables are
12928 // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
12929 // marking them as internal.
12930 if (Context.getLangOpts().CPlusPlus &&
12931 Context.getLangOpts().IncrementalExtensions &&
12932 VD->getType().isConstQualified() &&
12933 !VD->getType().isVolatileQualified() && !VD->isInline() &&
12935 return GVA_DiscardableODR;
12936
12937 if (!VD->isExternallyVisible())
12938 return GVA_Internal;
12939
12940 if (VD->isStaticLocal()) {
12941 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
12942 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
12943 LexicalContext = LexicalContext->getLexicalParent();
12944
12945 // ObjC Blocks can create local variables that don't have a FunctionDecl
12946 // LexicalContext.
12947 if (!LexicalContext)
12948 return GVA_DiscardableODR;
12949
12950 // Otherwise, let the static local variable inherit its linkage from the
12951 // nearest enclosing function.
12952 auto StaticLocalLinkage =
12953 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
12954
12955 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
12956 // be emitted in any object with references to the symbol for the object it
12957 // contains, whether inline or out-of-line."
12958 // Similar behavior is observed with MSVC. An alternative ABI could use
12959 // StrongODR/AvailableExternally to match the function, but none are
12960 // known/supported currently.
12961 if (StaticLocalLinkage == GVA_StrongODR ||
12962 StaticLocalLinkage == GVA_AvailableExternally)
12963 return GVA_DiscardableODR;
12964 return StaticLocalLinkage;
12965 }
12966
12967 // MSVC treats in-class initialized static data members as definitions.
12968 // By giving them non-strong linkage, out-of-line definitions won't
12969 // cause link errors.
12970 if (Context.isMSStaticDataMemberInlineDefinition(VD))
12971 return GVA_DiscardableODR;
12972
12973 // Most non-template variables have strong linkage; inline variables are
12974 // linkonce_odr or (occasionally, for compatibility) weak_odr.
12975 GVALinkage StrongLinkage;
12976 switch (Context.getInlineVariableDefinitionKind(VD)) {
12978 StrongLinkage = GVA_StrongExternal;
12979 break;
12982 StrongLinkage = GVA_DiscardableODR;
12983 break;
12985 StrongLinkage = GVA_StrongODR;
12986 break;
12987 }
12988
12989 switch (VD->getTemplateSpecializationKind()) {
12990 case TSK_Undeclared:
12991 return StrongLinkage;
12992
12994 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12995 VD->isStaticDataMember()
12997 : StrongLinkage;
12998
13000 return GVA_StrongODR;
13001
13004
13006 return GVA_DiscardableODR;
13007 }
13008
13009 llvm_unreachable("Invalid Linkage!");
13010}
13011
13017
13019 if (const auto *VD = dyn_cast<VarDecl>(D)) {
13020 if (!VD->isFileVarDecl())
13021 return false;
13022 // Global named register variables (GNU extension) are never emitted.
13023 if (VD->getStorageClass() == SC_Register)
13024 return false;
13025 if (VD->getDescribedVarTemplate() ||
13027 return false;
13028 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13029 // We never need to emit an uninstantiated function template.
13030 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13031 return false;
13032 } else if (isa<PragmaCommentDecl>(D))
13033 return true;
13035 return true;
13036 else if (isa<OMPRequiresDecl>(D))
13037 return true;
13038 else if (isa<OMPThreadPrivateDecl>(D))
13039 return !D->getDeclContext()->isDependentContext();
13040 else if (isa<OMPAllocateDecl>(D))
13041 return !D->getDeclContext()->isDependentContext();
13043 return !D->getDeclContext()->isDependentContext();
13044 else if (isa<ImportDecl>(D))
13045 return true;
13046 else
13047 return false;
13048
13049 // If this is a member of a class template, we do not need to emit it.
13051 return false;
13052
13053 // Weak references don't produce any output by themselves.
13054 if (D->hasAttr<WeakRefAttr>())
13055 return false;
13056
13057 // SYCL device compilation requires that functions defined with the
13058 // sycl_kernel_entry_point or sycl_external attributes be emitted. All
13059 // other entities are emitted only if they are used by a function
13060 // defined with one of those attributes.
13061 if (LangOpts.SYCLIsDevice)
13062 return isa<FunctionDecl>(D) && (D->hasAttr<SYCLKernelEntryPointAttr>() ||
13063 D->hasAttr<SYCLExternalAttr>());
13064
13065 // Aliases and used decls are required.
13066 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
13067 return true;
13068
13069 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13070 // Forward declarations aren't required.
13071 if (!FD->doesThisDeclarationHaveABody())
13072 return FD->doesDeclarationForceExternallyVisibleDefinition();
13073
13074 // Constructors and destructors are required.
13075 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
13076 return true;
13077
13078 // The key function for a class is required. This rule only comes
13079 // into play when inline functions can be key functions, though.
13080 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13081 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13082 const CXXRecordDecl *RD = MD->getParent();
13083 if (MD->isOutOfLine() && RD->isDynamicClass()) {
13084 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
13085 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
13086 return true;
13087 }
13088 }
13089 }
13090
13092
13093 // static, static inline, always_inline, and extern inline functions can
13094 // always be deferred. Normal inline functions can be deferred in C99/C++.
13095 // Implicit template instantiations can also be deferred in C++.
13097 }
13098
13099 const auto *VD = cast<VarDecl>(D);
13100 assert(VD->isFileVarDecl() && "Expected file scoped var");
13101
13102 // If the decl is marked as `declare target to`, it should be emitted for the
13103 // host and for the device.
13104 if (LangOpts.OpenMP &&
13105 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
13106 return true;
13107
13108 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
13110 return false;
13111
13112 if (VD->shouldEmitInExternalSource())
13113 return false;
13114
13115 // Variables that can be needed in other TUs are required.
13118 return true;
13119
13120 // We never need to emit a variable that is available in another TU.
13122 return false;
13123
13124 // Variables that have destruction with side-effects are required.
13125 if (VD->needsDestruction(*this))
13126 return true;
13127
13128 // Variables that have initialization with side-effects are required.
13129 if (VD->hasInitWithSideEffects())
13130 return true;
13131
13132 // Likewise, variables with tuple-like bindings are required if their
13133 // bindings have side-effects.
13134 if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) {
13135 for (const auto *BD : DD->flat_bindings())
13136 if (const auto *BindingVD = BD->getHoldingVar())
13137 if (DeclMustBeEmitted(BindingVD))
13138 return true;
13139 }
13140
13141 return false;
13142}
13143
13145 const FunctionDecl *FD,
13146 llvm::function_ref<void(FunctionDecl *)> Pred) const {
13147 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
13148 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
13149 FD = FD->getMostRecentDecl();
13150 // FIXME: The order of traversal here matters and depends on the order of
13151 // lookup results, which happens to be (mostly) oldest-to-newest, but we
13152 // shouldn't rely on that.
13153 for (auto *CurDecl :
13155 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
13156 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
13157 SeenDecls.insert(CurFD).second) {
13158 Pred(CurFD);
13159 }
13160 }
13161}
13162
13164 bool IsCXXMethod) const {
13165 // Pass through to the C++ ABI object
13166 if (IsCXXMethod)
13167 return ABI->getDefaultMethodCallConv(IsVariadic);
13168
13169 switch (LangOpts.getDefaultCallingConv()) {
13171 break;
13173 return CC_C;
13175 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
13176 return CC_X86FastCall;
13177 break;
13179 if (!IsVariadic)
13180 return CC_X86StdCall;
13181 break;
13183 // __vectorcall cannot be applied to variadic functions.
13184 if (!IsVariadic)
13185 return CC_X86VectorCall;
13186 break;
13188 // __regcall cannot be applied to variadic functions.
13189 if (!IsVariadic)
13190 return CC_X86RegCall;
13191 break;
13193 if (!IsVariadic)
13194 return CC_M68kRTD;
13195 break;
13196 }
13197 return Target->getDefaultCallingConv();
13198}
13199
13201 // Pass through to the C++ ABI object
13202 return ABI->isNearlyEmpty(RD);
13203}
13204
13206 if (!VTContext) {
13207 auto ABI = Target->getCXXABI();
13208 if (ABI.isMicrosoft())
13209 VTContext.reset(new MicrosoftVTableContext(*this));
13210 else {
13211 auto ComponentLayout = getLangOpts().RelativeCXXABIVTables
13214 VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout));
13215 }
13216 }
13217 return VTContext.get();
13218}
13219
13221 if (!T)
13222 T = Target;
13223 switch (T->getCXXABI().getKind()) {
13224 case TargetCXXABI::AppleARM64:
13225 case TargetCXXABI::Fuchsia:
13226 case TargetCXXABI::GenericAArch64:
13227 case TargetCXXABI::GenericItanium:
13228 case TargetCXXABI::GenericARM:
13229 case TargetCXXABI::GenericMIPS:
13230 case TargetCXXABI::iOS:
13231 case TargetCXXABI::WebAssembly:
13232 case TargetCXXABI::WatchOS:
13233 case TargetCXXABI::XL:
13235 case TargetCXXABI::Microsoft:
13237 }
13238 llvm_unreachable("Unsupported ABI");
13239}
13240
13242 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
13243 "Device mangle context does not support Microsoft mangling.");
13244 switch (T.getCXXABI().getKind()) {
13245 case TargetCXXABI::AppleARM64:
13246 case TargetCXXABI::Fuchsia:
13247 case TargetCXXABI::GenericAArch64:
13248 case TargetCXXABI::GenericItanium:
13249 case TargetCXXABI::GenericARM:
13250 case TargetCXXABI::GenericMIPS:
13251 case TargetCXXABI::iOS:
13252 case TargetCXXABI::WebAssembly:
13253 case TargetCXXABI::WatchOS:
13254 case TargetCXXABI::XL:
13256 *this, getDiagnostics(),
13257 [](ASTContext &, const NamedDecl *ND) -> UnsignedOrNone {
13258 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
13259 return RD->getDeviceLambdaManglingNumber();
13260 return std::nullopt;
13261 },
13262 /*IsAux=*/true);
13263 case TargetCXXABI::Microsoft:
13265 /*IsAux=*/true);
13266 }
13267 llvm_unreachable("Unsupported ABI");
13268}
13269
13270CXXABI::~CXXABI() = default;
13271
13273 return ASTRecordLayouts.getMemorySize() +
13274 llvm::capacity_in_bytes(ObjCLayouts) +
13275 llvm::capacity_in_bytes(KeyFunctions) +
13276 llvm::capacity_in_bytes(ObjCImpls) +
13277 llvm::capacity_in_bytes(BlockVarCopyInits) +
13278 llvm::capacity_in_bytes(DeclAttrs) +
13279 llvm::capacity_in_bytes(TemplateOrInstantiation) +
13280 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
13281 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
13282 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
13283 llvm::capacity_in_bytes(OverriddenMethods) +
13284 llvm::capacity_in_bytes(Types) +
13285 llvm::capacity_in_bytes(VariableArrayTypes);
13286}
13287
13288/// getIntTypeForBitwidth -
13289/// sets integer QualTy according to specified details:
13290/// bitwidth, signed/unsigned.
13291/// Returns empty type if there is no appropriate target types.
13293 unsigned Signed) const {
13295 CanQualType QualTy = getFromTargetType(Ty);
13296 if (!QualTy && DestWidth == 128)
13297 return Signed ? Int128Ty : UnsignedInt128Ty;
13298 return QualTy;
13299}
13300
13301/// getRealTypeForBitwidth -
13302/// sets floating point QualTy according to specified bitwidth.
13303/// Returns empty type if there is no appropriate target types.
13305 FloatModeKind ExplicitType) const {
13306 FloatModeKind Ty =
13307 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType);
13308 switch (Ty) {
13310 return HalfTy;
13312 return FloatTy;
13314 return DoubleTy;
13316 return LongDoubleTy;
13318 return Float128Ty;
13320 return Ibm128Ty;
13322 return {};
13323 }
13324
13325 llvm_unreachable("Unhandled TargetInfo::RealType value");
13326}
13327
13328void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
13329 if (Number <= 1)
13330 return;
13331
13332 MangleNumbers[ND] = Number;
13333
13334 if (Listener)
13335 Listener->AddedManglingNumber(ND, Number);
13336}
13337
13339 bool ForAuxTarget) const {
13340 auto I = MangleNumbers.find(ND);
13341 unsigned Res = I != MangleNumbers.end() ? I->second : 1;
13342 // CUDA/HIP host compilation encodes host and device mangling numbers
13343 // as lower and upper half of 32 bit integer.
13344 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
13345 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
13346 } else {
13347 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
13348 "number for aux target");
13349 }
13350 return Res > 1 ? Res : 1;
13351}
13352
13353void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
13354 if (Number <= 1)
13355 return;
13356
13357 StaticLocalNumbers[VD] = Number;
13358
13359 if (Listener)
13360 Listener->AddedStaticLocalNumbers(VD, Number);
13361}
13362
13364 auto I = StaticLocalNumbers.find(VD);
13365 return I != StaticLocalNumbers.end() ? I->second : 1;
13366}
13367
13369 bool IsDestroying) {
13370 if (!IsDestroying) {
13371 assert(!DestroyingOperatorDeletes.contains(FD->getCanonicalDecl()));
13372 return;
13373 }
13374 DestroyingOperatorDeletes.insert(FD->getCanonicalDecl());
13375}
13376
13378 return DestroyingOperatorDeletes.contains(FD->getCanonicalDecl());
13379}
13380
13382 bool IsTypeAware) {
13383 if (!IsTypeAware) {
13384 assert(!TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl()));
13385 return;
13386 }
13387 TypeAwareOperatorNewAndDeletes.insert(FD->getCanonicalDecl());
13388}
13389
13391 return TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl());
13392}
13393
13396 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13397 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
13398 if (!MCtx)
13400 return *MCtx;
13401}
13402
13405 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13406 std::unique_ptr<MangleNumberingContext> &MCtx =
13407 ExtraMangleNumberingContexts[D];
13408 if (!MCtx)
13410 return *MCtx;
13411}
13412
13413std::unique_ptr<MangleNumberingContext>
13415 return ABI->createMangleNumberingContext();
13416}
13417
13418const CXXConstructorDecl *
13420 return ABI->getCopyConstructorForExceptionObject(
13422}
13423
13425 CXXConstructorDecl *CD) {
13426 return ABI->addCopyConstructorForExceptionObject(
13429}
13430
13432 TypedefNameDecl *DD) {
13433 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
13434}
13435
13438 return ABI->getTypedefNameForUnnamedTagDecl(TD);
13439}
13440
13442 DeclaratorDecl *DD) {
13443 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
13444}
13445
13447 return ABI->getDeclaratorForUnnamedTagDecl(TD);
13448}
13449
13451 ParamIndices[D] = index;
13452}
13453
13455 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
13456 assert(I != ParamIndices.end() &&
13457 "ParmIndices lacks entry set by ParmVarDecl");
13458 return I->second;
13459}
13460
13462 unsigned Length) const {
13463 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
13464 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
13465 EltTy = EltTy.withConst();
13466
13467 EltTy = adjustStringLiteralBaseType(EltTy);
13468
13469 // Get an array type for the string, according to C99 6.4.5. This includes
13470 // the null terminator character.
13471 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
13472 ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0);
13473}
13474
13477 StringLiteral *&Result = StringLiteralCache[Key];
13478 if (!Result)
13480 *this, Key, StringLiteralKind::Ordinary,
13481 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
13482 SourceLocation());
13483 return Result;
13484}
13485
13486MSGuidDecl *
13488 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
13489
13490 llvm::FoldingSetNodeID ID;
13491 MSGuidDecl::Profile(ID, Parts);
13492
13493 void *InsertPos;
13494 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
13495 return Existing;
13496
13497 QualType GUIDType = getMSGuidType().withConst();
13498 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
13499 MSGuidDecls.InsertNode(New, InsertPos);
13500 return New;
13501}
13502
13505 const APValue &APVal) const {
13506 llvm::FoldingSetNodeID ID;
13508
13509 void *InsertPos;
13510 if (UnnamedGlobalConstantDecl *Existing =
13511 UnnamedGlobalConstantDecls.FindNodeOrInsertPos(ID, InsertPos))
13512 return Existing;
13513
13515 UnnamedGlobalConstantDecl::Create(*this, Ty, APVal);
13516 UnnamedGlobalConstantDecls.InsertNode(New, InsertPos);
13517 return New;
13518}
13519
13522 assert(T->isRecordType() && "template param object of unexpected type");
13523
13524 // C++ [temp.param]p8:
13525 // [...] a static storage duration object of type 'const T' [...]
13526 T.addConst();
13527
13528 llvm::FoldingSetNodeID ID;
13530
13531 void *InsertPos;
13532 if (TemplateParamObjectDecl *Existing =
13533 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
13534 return Existing;
13535
13536 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
13537 TemplateParamObjectDecls.InsertNode(New, InsertPos);
13538 return New;
13539}
13540
13542 const llvm::Triple &T = getTargetInfo().getTriple();
13543 if (!T.isOSDarwin())
13544 return false;
13545
13546 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
13547 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
13548 return false;
13549
13550 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
13551 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
13552 uint64_t Size = sizeChars.getQuantity();
13553 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
13554 unsigned Align = alignChars.getQuantity();
13555 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
13556 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
13557}
13558
13559bool
13561 const ObjCMethodDecl *MethodImpl) {
13562 // No point trying to match an unavailable/deprecated mothod.
13563 if (MethodDecl->hasAttr<UnavailableAttr>()
13564 || MethodDecl->hasAttr<DeprecatedAttr>())
13565 return false;
13566 if (MethodDecl->getObjCDeclQualifier() !=
13567 MethodImpl->getObjCDeclQualifier())
13568 return false;
13569 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
13570 return false;
13571
13572 if (MethodDecl->param_size() != MethodImpl->param_size())
13573 return false;
13574
13575 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
13576 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
13577 EF = MethodDecl->param_end();
13578 IM != EM && IF != EF; ++IM, ++IF) {
13579 const ParmVarDecl *DeclVar = (*IF);
13580 const ParmVarDecl *ImplVar = (*IM);
13581 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
13582 return false;
13583 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
13584 return false;
13585 }
13586
13587 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
13588}
13589
13591 LangAS AS;
13593 AS = LangAS::Default;
13594 else
13595 AS = QT->getPointeeType().getAddressSpace();
13596
13598}
13599
13602}
13603
13604bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
13605 if (X == Y)
13606 return true;
13607 if (!X || !Y)
13608 return false;
13609 llvm::FoldingSetNodeID IDX, IDY;
13610 X->Profile(IDX, *this, /*Canonical=*/true);
13611 Y->Profile(IDY, *this, /*Canonical=*/true);
13612 return IDX == IDY;
13613}
13614
13615// The getCommon* helpers return, for given 'same' X and Y entities given as
13616// inputs, another entity which is also the 'same' as the inputs, but which
13617// is closer to the canonical form of the inputs, each according to a given
13618// criteria.
13619// The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
13620// the regular ones.
13621
13623 if (!declaresSameEntity(X, Y))
13624 return nullptr;
13625 for (const Decl *DX : X->redecls()) {
13626 // If we reach Y before reaching the first decl, that means X is older.
13627 if (DX == Y)
13628 return X;
13629 // If we reach the first decl, then Y is older.
13630 if (DX->isFirstDecl())
13631 return Y;
13632 }
13633 llvm_unreachable("Corrupt redecls chain");
13634}
13635
13636template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13637static T *getCommonDecl(T *X, T *Y) {
13638 return cast_or_null<T>(
13639 getCommonDecl(const_cast<Decl *>(cast_or_null<Decl>(X)),
13640 const_cast<Decl *>(cast_or_null<Decl>(Y))));
13641}
13642
13643template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13644static T *getCommonDeclChecked(T *X, T *Y) {
13645 return cast<T>(getCommonDecl(const_cast<Decl *>(cast<Decl>(X)),
13646 const_cast<Decl *>(cast<Decl>(Y))));
13647}
13648
13650 TemplateName Y,
13651 bool IgnoreDeduced = false) {
13652 if (X.getAsVoidPointer() == Y.getAsVoidPointer())
13653 return X;
13654 // FIXME: There are cases here where we could find a common template name
13655 // with more sugar. For example one could be a SubstTemplateTemplate*
13656 // replacing the other.
13657 TemplateName CX = Ctx.getCanonicalTemplateName(X, IgnoreDeduced);
13658 if (CX.getAsVoidPointer() !=
13660 return TemplateName();
13661 return CX;
13662}
13663
13666 bool IgnoreDeduced) {
13667 TemplateName R = getCommonTemplateName(Ctx, X, Y, IgnoreDeduced);
13668 assert(R.getAsVoidPointer() != nullptr);
13669 return R;
13670}
13671
13673 ArrayRef<QualType> Ys, bool Unqualified = false) {
13674 assert(Xs.size() == Ys.size());
13675 SmallVector<QualType, 8> Rs(Xs.size());
13676 for (size_t I = 0; I < Rs.size(); ++I)
13677 Rs[I] = Ctx.getCommonSugaredType(Xs[I], Ys[I], Unqualified);
13678 return Rs;
13679}
13680
13681template <class T>
13682static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
13683 return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
13684 : SourceLocation();
13685}
13686
13688 const TemplateArgument &X,
13689 const TemplateArgument &Y) {
13690 if (X.getKind() != Y.getKind())
13691 return TemplateArgument();
13692
13693 switch (X.getKind()) {
13695 if (!Ctx.hasSameType(X.getAsType(), Y.getAsType()))
13696 return TemplateArgument();
13697 return TemplateArgument(
13698 Ctx.getCommonSugaredType(X.getAsType(), Y.getAsType()));
13700 if (!Ctx.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
13701 return TemplateArgument();
13702 return TemplateArgument(
13703 Ctx.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
13704 /*Unqualified=*/true);
13706 if (!Ctx.hasSameType(X.getAsExpr()->getType(), Y.getAsExpr()->getType()))
13707 return TemplateArgument();
13708 // FIXME: Try to keep the common sugar.
13709 return X;
13711 TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
13712 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
13713 if (!CTN.getAsVoidPointer())
13714 return TemplateArgument();
13715 return TemplateArgument(CTN);
13716 }
13718 TemplateName TX = X.getAsTemplateOrTemplatePattern(),
13720 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
13721 if (!CTN.getAsVoidPointer())
13722 return TemplateName();
13723 auto NExpX = X.getNumTemplateExpansions();
13724 assert(NExpX == Y.getNumTemplateExpansions());
13725 return TemplateArgument(CTN, NExpX);
13726 }
13727 default:
13728 // FIXME: Handle the other argument kinds.
13729 return X;
13730 }
13731}
13732
13737 if (Xs.size() != Ys.size())
13738 return true;
13739 R.resize(Xs.size());
13740 for (size_t I = 0; I < R.size(); ++I) {
13741 R[I] = getCommonTemplateArgument(Ctx, Xs[I], Ys[I]);
13742 if (R[I].isNull())
13743 return true;
13744 }
13745 return false;
13746}
13747
13752 bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
13753 assert(!Different);
13754 (void)Different;
13755 return R;
13756}
13757
13758template <class T>
13760 bool IsSame) {
13761 ElaboratedTypeKeyword KX = X->getKeyword(), KY = Y->getKeyword();
13762 if (KX == KY)
13763 return KX;
13765 assert(!IsSame || KX == getCanonicalElaboratedTypeKeyword(KY));
13766 return KX;
13767}
13768
13769/// Returns a NestedNameSpecifier which has only the common sugar
13770/// present in both NNS1 and NNS2.
13773 NestedNameSpecifier NNS2, bool IsSame) {
13774 // If they are identical, all sugar is common.
13775 if (NNS1 == NNS2)
13776 return NNS1;
13777
13778 // IsSame implies both Qualifiers are equivalent.
13779 NestedNameSpecifier Canon = NNS1.getCanonical();
13780 if (Canon != NNS2.getCanonical()) {
13781 assert(!IsSame && "Should be the same NestedNameSpecifier");
13782 // If they are not the same, there is nothing to unify.
13783 return std::nullopt;
13784 }
13785
13786 NestedNameSpecifier R = std::nullopt;
13787 NestedNameSpecifier::Kind Kind = NNS1.getKind();
13788 assert(Kind == NNS2.getKind());
13789 switch (Kind) {
13791 auto [Namespace1, Prefix1] = NNS1.getAsNamespaceAndPrefix();
13792 auto [Namespace2, Prefix2] = NNS2.getAsNamespaceAndPrefix();
13793 auto Kind = Namespace1->getKind();
13794 if (Kind != Namespace2->getKind() ||
13795 (Kind == Decl::NamespaceAlias &&
13796 !declaresSameEntity(Namespace1, Namespace2))) {
13798 Ctx,
13799 ::getCommonDeclChecked(Namespace1->getNamespace(),
13800 Namespace2->getNamespace()),
13801 /*Prefix=*/std::nullopt);
13802 break;
13803 }
13804 // The prefixes for namespaces are not significant, its declaration
13805 // identifies it uniquely.
13806 NestedNameSpecifier Prefix = ::getCommonNNS(Ctx, Prefix1, Prefix2,
13807 /*IsSame=*/false);
13808 R = NestedNameSpecifier(Ctx, ::getCommonDeclChecked(Namespace1, Namespace2),
13809 Prefix);
13810 break;
13811 }
13813 const Type *T1 = NNS1.getAsType(), *T2 = NNS2.getAsType();
13814 const Type *T = Ctx.getCommonSugaredType(QualType(T1, 0), QualType(T2, 0),
13815 /*Unqualified=*/true)
13816 .getTypePtr();
13818 break;
13819 }
13821 // FIXME: Can __super even be used with data members?
13822 // If it's only usable in functions, we will never see it here,
13823 // unless we save the qualifiers used in function types.
13824 // In that case, it might be possible NNS2 is a type,
13825 // in which case we should degrade the result to
13826 // a CXXRecordType.
13828 NNS2.getAsMicrosoftSuper()));
13829 break;
13830 }
13833 // These are singletons.
13834 llvm_unreachable("singletons did not compare equal");
13835 }
13836 assert(R.getCanonical() == Canon);
13837 return R;
13838}
13839
13840template <class T>
13842 const T *Y, bool IsSame) {
13843 return ::getCommonNNS(Ctx, X->getQualifier(), Y->getQualifier(), IsSame);
13844}
13845
13846template <class T>
13847static QualType getCommonElementType(const ASTContext &Ctx, const T *X,
13848 const T *Y) {
13849 return Ctx.getCommonSugaredType(X->getElementType(), Y->getElementType());
13850}
13851
13852template <class T>
13854 Qualifiers &QX, const T *Y,
13855 Qualifiers &QY) {
13856 QualType EX = X->getElementType(), EY = Y->getElementType();
13857 QualType R = Ctx.getCommonSugaredType(EX, EY,
13858 /*Unqualified=*/true);
13859 // Qualifiers common to both element types.
13860 Qualifiers RQ = R.getQualifiers();
13861 // For each side, move to the top level any qualifiers which are not common to
13862 // both element types. The caller must assume top level qualifiers might
13863 // be different, even if they are the same type, and can be treated as sugar.
13864 QX += EX.getQualifiers() - RQ;
13865 QY += EY.getQualifiers() - RQ;
13866 return R;
13867}
13868
13869template <class T>
13870static QualType getCommonPointeeType(const ASTContext &Ctx, const T *X,
13871 const T *Y) {
13872 return Ctx.getCommonSugaredType(X->getPointeeType(), Y->getPointeeType());
13873}
13874
13875template <class T>
13876static auto *getCommonSizeExpr(const ASTContext &Ctx, T *X, T *Y) {
13877 assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
13878 return X->getSizeExpr();
13879}
13880
13881static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
13882 assert(X->getSizeModifier() == Y->getSizeModifier());
13883 return X->getSizeModifier();
13884}
13885
13887 const ArrayType *Y) {
13888 assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
13889 return X->getIndexTypeCVRQualifiers();
13890}
13891
13892// Merges two type lists such that the resulting vector will contain
13893// each type (in a canonical sense) only once, in the order they appear
13894// from X to Y. If they occur in both X and Y, the result will contain
13895// the common sugared type between them.
13896static void mergeTypeLists(const ASTContext &Ctx,
13899 llvm::DenseMap<QualType, unsigned> Found;
13900 for (auto Ts : {X, Y}) {
13901 for (QualType T : Ts) {
13902 auto Res = Found.try_emplace(Ctx.getCanonicalType(T), Out.size());
13903 if (!Res.second) {
13904 QualType &U = Out[Res.first->second];
13905 U = Ctx.getCommonSugaredType(U, T);
13906 } else {
13907 Out.emplace_back(T);
13908 }
13909 }
13910 }
13911}
13912
13913FunctionProtoType::ExceptionSpecInfo
13916 SmallVectorImpl<QualType> &ExceptionTypeStorage,
13917 bool AcceptDependent) const {
13918 ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
13919
13920 // If either of them can throw anything, that is the result.
13921 for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
13922 if (EST1 == I)
13923 return ESI1;
13924 if (EST2 == I)
13925 return ESI2;
13926 }
13927
13928 // If either of them is non-throwing, the result is the other.
13929 for (auto I :
13931 if (EST1 == I)
13932 return ESI2;
13933 if (EST2 == I)
13934 return ESI1;
13935 }
13936
13937 // If we're left with value-dependent computed noexcept expressions, we're
13938 // stuck. Before C++17, we can just drop the exception specification entirely,
13939 // since it's not actually part of the canonical type. And this should never
13940 // happen in C++17, because it would mean we were computing the composite
13941 // pointer type of dependent types, which should never happen.
13942 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
13943 assert(AcceptDependent &&
13944 "computing composite pointer type of dependent types");
13946 }
13947
13948 // Switch over the possibilities so that people adding new values know to
13949 // update this function.
13950 switch (EST1) {
13951 case EST_None:
13952 case EST_DynamicNone:
13953 case EST_MSAny:
13954 case EST_BasicNoexcept:
13956 case EST_NoexceptFalse:
13957 case EST_NoexceptTrue:
13958 case EST_NoThrow:
13959 llvm_unreachable("These ESTs should be handled above");
13960
13961 case EST_Dynamic: {
13962 // This is the fun case: both exception specifications are dynamic. Form
13963 // the union of the two lists.
13964 assert(EST2 == EST_Dynamic && "other cases should already be handled");
13965 mergeTypeLists(*this, ExceptionTypeStorage, ESI1.Exceptions,
13966 ESI2.Exceptions);
13968 Result.Exceptions = ExceptionTypeStorage;
13969 return Result;
13970 }
13971
13972 case EST_Unevaluated:
13973 case EST_Uninstantiated:
13974 case EST_Unparsed:
13975 llvm_unreachable("shouldn't see unresolved exception specifications here");
13976 }
13977
13978 llvm_unreachable("invalid ExceptionSpecificationType");
13979}
13980
13982 Qualifiers &QX, const Type *Y,
13983 Qualifiers &QY) {
13984 Type::TypeClass TC = X->getTypeClass();
13985 assert(TC == Y->getTypeClass());
13986 switch (TC) {
13987#define UNEXPECTED_TYPE(Class, Kind) \
13988 case Type::Class: \
13989 llvm_unreachable("Unexpected " Kind ": " #Class);
13990
13991#define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
13992#define TYPE(Class, Base)
13993#include "clang/AST/TypeNodes.inc"
13994
13995#define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
13997 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
13998 SUGAR_FREE_TYPE(DependentBitInt)
14000 SUGAR_FREE_TYPE(ObjCInterface)
14001 SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
14002 SUGAR_FREE_TYPE(SubstBuiltinTemplatePack)
14003 SUGAR_FREE_TYPE(UnresolvedUsing)
14004 SUGAR_FREE_TYPE(HLSLAttributedResource)
14005 SUGAR_FREE_TYPE(HLSLInlineSpirv)
14006#undef SUGAR_FREE_TYPE
14007#define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
14008 NON_UNIQUE_TYPE(TypeOfExpr)
14009 NON_UNIQUE_TYPE(VariableArray)
14010#undef NON_UNIQUE_TYPE
14011
14012 UNEXPECTED_TYPE(TypeOf, "sugar")
14013
14014#undef UNEXPECTED_TYPE
14015
14016 case Type::Auto: {
14017 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14018 assert(AX->getDeducedType().isNull());
14019 assert(AY->getDeducedType().isNull());
14020 assert(AX->getKeyword() == AY->getKeyword());
14021 assert(AX->isInstantiationDependentType() ==
14022 AY->isInstantiationDependentType());
14023 auto As = getCommonTemplateArguments(Ctx, AX->getTypeConstraintArguments(),
14024 AY->getTypeConstraintArguments());
14025 return Ctx.getAutoType(QualType(), AX->getKeyword(),
14027 AX->containsUnexpandedParameterPack(),
14028 getCommonDeclChecked(AX->getTypeConstraintConcept(),
14029 AY->getTypeConstraintConcept()),
14030 As);
14031 }
14032 case Type::IncompleteArray: {
14033 const auto *AX = cast<IncompleteArrayType>(X),
14035 return Ctx.getIncompleteArrayType(
14036 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14038 }
14039 case Type::DependentSizedArray: {
14040 const auto *AX = cast<DependentSizedArrayType>(X),
14042 return Ctx.getDependentSizedArrayType(
14043 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14044 getCommonSizeExpr(Ctx, AX, AY), getCommonSizeModifier(AX, AY),
14046 }
14047 case Type::ConstantArray: {
14048 const auto *AX = cast<ConstantArrayType>(X),
14049 *AY = cast<ConstantArrayType>(Y);
14050 assert(AX->getSize() == AY->getSize());
14051 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14052 ? AX->getSizeExpr()
14053 : nullptr;
14054 return Ctx.getConstantArrayType(
14055 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14057 }
14058 case Type::ArrayParameter: {
14059 const auto *AX = cast<ArrayParameterType>(X),
14060 *AY = cast<ArrayParameterType>(Y);
14061 assert(AX->getSize() == AY->getSize());
14062 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14063 ? AX->getSizeExpr()
14064 : nullptr;
14065 auto ArrayTy = Ctx.getConstantArrayType(
14066 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14068 return Ctx.getArrayParameterType(ArrayTy);
14069 }
14070 case Type::Atomic: {
14071 const auto *AX = cast<AtomicType>(X), *AY = cast<AtomicType>(Y);
14072 return Ctx.getAtomicType(
14073 Ctx.getCommonSugaredType(AX->getValueType(), AY->getValueType()));
14074 }
14075 case Type::Complex: {
14076 const auto *CX = cast<ComplexType>(X), *CY = cast<ComplexType>(Y);
14077 return Ctx.getComplexType(getCommonArrayElementType(Ctx, CX, QX, CY, QY));
14078 }
14079 case Type::Pointer: {
14080 const auto *PX = cast<PointerType>(X), *PY = cast<PointerType>(Y);
14081 return Ctx.getPointerType(getCommonPointeeType(Ctx, PX, PY));
14082 }
14083 case Type::BlockPointer: {
14084 const auto *PX = cast<BlockPointerType>(X), *PY = cast<BlockPointerType>(Y);
14085 return Ctx.getBlockPointerType(getCommonPointeeType(Ctx, PX, PY));
14086 }
14087 case Type::ObjCObjectPointer: {
14088 const auto *PX = cast<ObjCObjectPointerType>(X),
14090 return Ctx.getObjCObjectPointerType(getCommonPointeeType(Ctx, PX, PY));
14091 }
14092 case Type::MemberPointer: {
14093 const auto *PX = cast<MemberPointerType>(X),
14094 *PY = cast<MemberPointerType>(Y);
14095 assert(declaresSameEntity(PX->getMostRecentCXXRecordDecl(),
14096 PY->getMostRecentCXXRecordDecl()));
14097 return Ctx.getMemberPointerType(
14098 getCommonPointeeType(Ctx, PX, PY),
14099 getCommonQualifier(Ctx, PX, PY, /*IsSame=*/true),
14100 PX->getMostRecentCXXRecordDecl());
14101 }
14102 case Type::LValueReference: {
14103 const auto *PX = cast<LValueReferenceType>(X),
14105 // FIXME: Preserve PointeeTypeAsWritten.
14106 return Ctx.getLValueReferenceType(getCommonPointeeType(Ctx, PX, PY),
14107 PX->isSpelledAsLValue() ||
14108 PY->isSpelledAsLValue());
14109 }
14110 case Type::RValueReference: {
14111 const auto *PX = cast<RValueReferenceType>(X),
14113 // FIXME: Preserve PointeeTypeAsWritten.
14114 return Ctx.getRValueReferenceType(getCommonPointeeType(Ctx, PX, PY));
14115 }
14116 case Type::DependentAddressSpace: {
14117 const auto *PX = cast<DependentAddressSpaceType>(X),
14119 assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
14120 return Ctx.getDependentAddressSpaceType(getCommonPointeeType(Ctx, PX, PY),
14121 PX->getAddrSpaceExpr(),
14122 getCommonAttrLoc(PX, PY));
14123 }
14124 case Type::FunctionNoProto: {
14125 const auto *FX = cast<FunctionNoProtoType>(X),
14127 assert(FX->getExtInfo() == FY->getExtInfo());
14128 return Ctx.getFunctionNoProtoType(
14129 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType()),
14130 FX->getExtInfo());
14131 }
14132 case Type::FunctionProto: {
14133 const auto *FX = cast<FunctionProtoType>(X),
14134 *FY = cast<FunctionProtoType>(Y);
14135 FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
14136 EPIY = FY->getExtProtoInfo();
14137 assert(EPIX.ExtInfo == EPIY.ExtInfo);
14138 assert(!EPIX.ExtParameterInfos == !EPIY.ExtParameterInfos);
14139 assert(!EPIX.ExtParameterInfos ||
14140 llvm::equal(
14141 llvm::ArrayRef(EPIX.ExtParameterInfos, FX->getNumParams()),
14142 llvm::ArrayRef(EPIY.ExtParameterInfos, FY->getNumParams())));
14143 assert(EPIX.RefQualifier == EPIY.RefQualifier);
14144 assert(EPIX.TypeQuals == EPIY.TypeQuals);
14145 assert(EPIX.Variadic == EPIY.Variadic);
14146
14147 // FIXME: Can we handle an empty EllipsisLoc?
14148 // Use emtpy EllipsisLoc if X and Y differ.
14149
14150 EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
14151
14152 QualType R =
14153 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType());
14154 auto P = getCommonTypes(Ctx, FX->param_types(), FY->param_types(),
14155 /*Unqualified=*/true);
14156
14157 SmallVector<QualType, 8> Exceptions;
14159 EPIX.ExceptionSpec, EPIY.ExceptionSpec, Exceptions, true);
14160 return Ctx.getFunctionType(R, P, EPIX);
14161 }
14162 case Type::ObjCObject: {
14163 const auto *OX = cast<ObjCObjectType>(X), *OY = cast<ObjCObjectType>(Y);
14164 assert(
14165 std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
14166 OY->getProtocols().begin(), OY->getProtocols().end(),
14167 [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
14168 return P0->getCanonicalDecl() == P1->getCanonicalDecl();
14169 }) &&
14170 "protocol lists must be the same");
14171 auto TAs = getCommonTypes(Ctx, OX->getTypeArgsAsWritten(),
14172 OY->getTypeArgsAsWritten());
14173 return Ctx.getObjCObjectType(
14174 Ctx.getCommonSugaredType(OX->getBaseType(), OY->getBaseType()), TAs,
14175 OX->getProtocols(),
14176 OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
14177 }
14178 case Type::ConstantMatrix: {
14179 const auto *MX = cast<ConstantMatrixType>(X),
14180 *MY = cast<ConstantMatrixType>(Y);
14181 assert(MX->getNumRows() == MY->getNumRows());
14182 assert(MX->getNumColumns() == MY->getNumColumns());
14183 return Ctx.getConstantMatrixType(getCommonElementType(Ctx, MX, MY),
14184 MX->getNumRows(), MX->getNumColumns());
14185 }
14186 case Type::DependentSizedMatrix: {
14187 const auto *MX = cast<DependentSizedMatrixType>(X),
14189 assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
14190 assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
14191 return Ctx.getDependentSizedMatrixType(
14192 getCommonElementType(Ctx, MX, MY), MX->getRowExpr(),
14193 MX->getColumnExpr(), getCommonAttrLoc(MX, MY));
14194 }
14195 case Type::Vector: {
14196 const auto *VX = cast<VectorType>(X), *VY = cast<VectorType>(Y);
14197 assert(VX->getNumElements() == VY->getNumElements());
14198 assert(VX->getVectorKind() == VY->getVectorKind());
14199 return Ctx.getVectorType(getCommonElementType(Ctx, VX, VY),
14200 VX->getNumElements(), VX->getVectorKind());
14201 }
14202 case Type::ExtVector: {
14203 const auto *VX = cast<ExtVectorType>(X), *VY = cast<ExtVectorType>(Y);
14204 assert(VX->getNumElements() == VY->getNumElements());
14205 return Ctx.getExtVectorType(getCommonElementType(Ctx, VX, VY),
14206 VX->getNumElements());
14207 }
14208 case Type::DependentSizedExtVector: {
14209 const auto *VX = cast<DependentSizedExtVectorType>(X),
14212 getCommonSizeExpr(Ctx, VX, VY),
14213 getCommonAttrLoc(VX, VY));
14214 }
14215 case Type::DependentVector: {
14216 const auto *VX = cast<DependentVectorType>(X),
14218 assert(VX->getVectorKind() == VY->getVectorKind());
14219 return Ctx.getDependentVectorType(
14220 getCommonElementType(Ctx, VX, VY), getCommonSizeExpr(Ctx, VX, VY),
14221 getCommonAttrLoc(VX, VY), VX->getVectorKind());
14222 }
14223 case Type::Enum:
14224 case Type::Record:
14225 case Type::InjectedClassName: {
14226 const auto *TX = cast<TagType>(X), *TY = cast<TagType>(Y);
14227 return Ctx.getTagType(
14228 ::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14229 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false),
14230 ::getCommonDeclChecked(TX->getOriginalDecl(), TY->getOriginalDecl()),
14231 /*OwnedTag=*/false);
14232 }
14233 case Type::TemplateSpecialization: {
14234 const auto *TX = cast<TemplateSpecializationType>(X),
14236 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
14237 TY->template_arguments());
14239 getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14240 ::getCommonTemplateNameChecked(Ctx, TX->getTemplateName(),
14241 TY->getTemplateName(),
14242 /*IgnoreDeduced=*/true),
14243 As, /*CanonicalArgs=*/{}, X->getCanonicalTypeInternal());
14244 }
14245 case Type::Decltype: {
14246 const auto *DX = cast<DecltypeType>(X);
14247 [[maybe_unused]] const auto *DY = cast<DecltypeType>(Y);
14248 assert(DX->isDependentType());
14249 assert(DY->isDependentType());
14250 assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
14251 // As Decltype is not uniqued, building a common type would be wasteful.
14252 return QualType(DX, 0);
14253 }
14254 case Type::PackIndexing: {
14255 const auto *DX = cast<PackIndexingType>(X);
14256 [[maybe_unused]] const auto *DY = cast<PackIndexingType>(Y);
14257 assert(DX->isDependentType());
14258 assert(DY->isDependentType());
14259 assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr()));
14260 return QualType(DX, 0);
14261 }
14262 case Type::DependentName: {
14263 const auto *NX = cast<DependentNameType>(X),
14264 *NY = cast<DependentNameType>(Y);
14265 assert(NX->getIdentifier() == NY->getIdentifier());
14266 return Ctx.getDependentNameType(
14267 getCommonTypeKeyword(NX, NY, /*IsSame=*/true),
14268 getCommonQualifier(Ctx, NX, NY, /*IsSame=*/true), NX->getIdentifier());
14269 }
14270 case Type::UnaryTransform: {
14271 const auto *TX = cast<UnaryTransformType>(X),
14272 *TY = cast<UnaryTransformType>(Y);
14273 assert(TX->getUTTKind() == TY->getUTTKind());
14274 return Ctx.getUnaryTransformType(
14275 Ctx.getCommonSugaredType(TX->getBaseType(), TY->getBaseType()),
14276 Ctx.getCommonSugaredType(TX->getUnderlyingType(),
14277 TY->getUnderlyingType()),
14278 TX->getUTTKind());
14279 }
14280 case Type::PackExpansion: {
14281 const auto *PX = cast<PackExpansionType>(X),
14282 *PY = cast<PackExpansionType>(Y);
14283 assert(PX->getNumExpansions() == PY->getNumExpansions());
14284 return Ctx.getPackExpansionType(
14285 Ctx.getCommonSugaredType(PX->getPattern(), PY->getPattern()),
14286 PX->getNumExpansions(), false);
14287 }
14288 case Type::Pipe: {
14289 const auto *PX = cast<PipeType>(X), *PY = cast<PipeType>(Y);
14290 assert(PX->isReadOnly() == PY->isReadOnly());
14291 auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
14293 return (Ctx.*MP)(getCommonElementType(Ctx, PX, PY));
14294 }
14295 case Type::TemplateTypeParm: {
14296 const auto *TX = cast<TemplateTypeParmType>(X),
14298 assert(TX->getDepth() == TY->getDepth());
14299 assert(TX->getIndex() == TY->getIndex());
14300 assert(TX->isParameterPack() == TY->isParameterPack());
14301 return Ctx.getTemplateTypeParmType(
14302 TX->getDepth(), TX->getIndex(), TX->isParameterPack(),
14303 getCommonDecl(TX->getDecl(), TY->getDecl()));
14304 }
14305 }
14306 llvm_unreachable("Unknown Type Class");
14307}
14308
14310 const Type *Y,
14311 SplitQualType Underlying) {
14312 Type::TypeClass TC = X->getTypeClass();
14313 if (TC != Y->getTypeClass())
14314 return QualType();
14315 switch (TC) {
14316#define UNEXPECTED_TYPE(Class, Kind) \
14317 case Type::Class: \
14318 llvm_unreachable("Unexpected " Kind ": " #Class);
14319#define TYPE(Class, Base)
14320#define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
14321#include "clang/AST/TypeNodes.inc"
14322
14323#define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
14326 CANONICAL_TYPE(BlockPointer)
14329 CANONICAL_TYPE(ConstantArray)
14330 CANONICAL_TYPE(ArrayParameter)
14331 CANONICAL_TYPE(ConstantMatrix)
14333 CANONICAL_TYPE(ExtVector)
14334 CANONICAL_TYPE(FunctionNoProto)
14335 CANONICAL_TYPE(FunctionProto)
14336 CANONICAL_TYPE(IncompleteArray)
14337 CANONICAL_TYPE(HLSLAttributedResource)
14338 CANONICAL_TYPE(HLSLInlineSpirv)
14339 CANONICAL_TYPE(LValueReference)
14340 CANONICAL_TYPE(ObjCInterface)
14341 CANONICAL_TYPE(ObjCObject)
14342 CANONICAL_TYPE(ObjCObjectPointer)
14346 CANONICAL_TYPE(RValueReference)
14347 CANONICAL_TYPE(VariableArray)
14349#undef CANONICAL_TYPE
14350
14351#undef UNEXPECTED_TYPE
14352
14353 case Type::Adjusted: {
14354 const auto *AX = cast<AdjustedType>(X), *AY = cast<AdjustedType>(Y);
14355 QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
14356 if (!Ctx.hasSameType(OX, OY))
14357 return QualType();
14358 // FIXME: It's inefficient to have to unify the original types.
14359 return Ctx.getAdjustedType(Ctx.getCommonSugaredType(OX, OY),
14360 Ctx.getQualifiedType(Underlying));
14361 }
14362 case Type::Decayed: {
14363 const auto *DX = cast<DecayedType>(X), *DY = cast<DecayedType>(Y);
14364 QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
14365 if (!Ctx.hasSameType(OX, OY))
14366 return QualType();
14367 // FIXME: It's inefficient to have to unify the original types.
14368 return Ctx.getDecayedType(Ctx.getCommonSugaredType(OX, OY),
14369 Ctx.getQualifiedType(Underlying));
14370 }
14371 case Type::Attributed: {
14372 const auto *AX = cast<AttributedType>(X), *AY = cast<AttributedType>(Y);
14373 AttributedType::Kind Kind = AX->getAttrKind();
14374 if (Kind != AY->getAttrKind())
14375 return QualType();
14376 QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
14377 if (!Ctx.hasSameType(MX, MY))
14378 return QualType();
14379 // FIXME: It's inefficient to have to unify the modified types.
14380 return Ctx.getAttributedType(Kind, Ctx.getCommonSugaredType(MX, MY),
14381 Ctx.getQualifiedType(Underlying),
14382 AX->getAttr());
14383 }
14384 case Type::BTFTagAttributed: {
14385 const auto *BX = cast<BTFTagAttributedType>(X);
14386 const BTFTypeTagAttr *AX = BX->getAttr();
14387 // The attribute is not uniqued, so just compare the tag.
14388 if (AX->getBTFTypeTag() !=
14389 cast<BTFTagAttributedType>(Y)->getAttr()->getBTFTypeTag())
14390 return QualType();
14391 return Ctx.getBTFTagAttributedType(AX, Ctx.getQualifiedType(Underlying));
14392 }
14393 case Type::Auto: {
14394 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14395
14396 AutoTypeKeyword KW = AX->getKeyword();
14397 if (KW != AY->getKeyword())
14398 return QualType();
14399
14400 TemplateDecl *CD = ::getCommonDecl(AX->getTypeConstraintConcept(),
14401 AY->getTypeConstraintConcept());
14403 if (CD &&
14404 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
14405 AY->getTypeConstraintArguments())) {
14406 CD = nullptr; // The arguments differ, so make it unconstrained.
14407 As.clear();
14408 }
14409
14410 // Both auto types can't be dependent, otherwise they wouldn't have been
14411 // sugar. This implies they can't contain unexpanded packs either.
14412 return Ctx.getAutoType(Ctx.getQualifiedType(Underlying), AX->getKeyword(),
14413 /*IsDependent=*/false, /*IsPack=*/false, CD, As);
14414 }
14415 case Type::PackIndexing:
14416 case Type::Decltype:
14417 return QualType();
14418 case Type::DeducedTemplateSpecialization:
14419 // FIXME: Try to merge these.
14420 return QualType();
14421 case Type::MacroQualified: {
14422 const auto *MX = cast<MacroQualifiedType>(X),
14423 *MY = cast<MacroQualifiedType>(Y);
14424 const IdentifierInfo *IX = MX->getMacroIdentifier();
14425 if (IX != MY->getMacroIdentifier())
14426 return QualType();
14427 return Ctx.getMacroQualifiedType(Ctx.getQualifiedType(Underlying), IX);
14428 }
14429 case Type::SubstTemplateTypeParm: {
14430 const auto *SX = cast<SubstTemplateTypeParmType>(X),
14432 Decl *CD =
14433 ::getCommonDecl(SX->getAssociatedDecl(), SY->getAssociatedDecl());
14434 if (!CD)
14435 return QualType();
14436 unsigned Index = SX->getIndex();
14437 if (Index != SY->getIndex())
14438 return QualType();
14439 auto PackIndex = SX->getPackIndex();
14440 if (PackIndex != SY->getPackIndex())
14441 return QualType();
14442 return Ctx.getSubstTemplateTypeParmType(Ctx.getQualifiedType(Underlying),
14443 CD, Index, PackIndex,
14444 SX->getFinal() && SY->getFinal());
14445 }
14446 case Type::ObjCTypeParam:
14447 // FIXME: Try to merge these.
14448 return QualType();
14449 case Type::Paren:
14450 return Ctx.getParenType(Ctx.getQualifiedType(Underlying));
14451
14452 case Type::TemplateSpecialization: {
14453 const auto *TX = cast<TemplateSpecializationType>(X),
14455 TemplateName CTN =
14456 ::getCommonTemplateName(Ctx, TX->getTemplateName(),
14457 TY->getTemplateName(), /*IgnoreDeduced=*/true);
14458 if (!CTN.getAsVoidPointer())
14459 return QualType();
14461 if (getCommonTemplateArguments(Ctx, As, TX->template_arguments(),
14462 TY->template_arguments()))
14463 return QualType();
14465 getCommonTypeKeyword(TX, TY, /*IsSame=*/false), CTN, As,
14466 /*CanonicalArgs=*/{}, Ctx.getQualifiedType(Underlying));
14467 }
14468 case Type::Typedef: {
14469 const auto *TX = cast<TypedefType>(X), *TY = cast<TypedefType>(Y);
14470 const TypedefNameDecl *CD = ::getCommonDecl(TX->getDecl(), TY->getDecl());
14471 if (!CD)
14472 return QualType();
14473 return Ctx.getTypedefType(
14474 ::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14475 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false), CD,
14476 Ctx.getQualifiedType(Underlying));
14477 }
14478 case Type::TypeOf: {
14479 // The common sugar between two typeof expressions, where one is
14480 // potentially a typeof_unqual and the other is not, we unify to the
14481 // qualified type as that retains the most information along with the type.
14482 // We only return a typeof_unqual type when both types are unqual types.
14487 return Ctx.getTypeOfType(Ctx.getQualifiedType(Underlying), Kind);
14488 }
14489 case Type::TypeOfExpr:
14490 return QualType();
14491
14492 case Type::UnaryTransform: {
14493 const auto *UX = cast<UnaryTransformType>(X),
14494 *UY = cast<UnaryTransformType>(Y);
14495 UnaryTransformType::UTTKind KX = UX->getUTTKind();
14496 if (KX != UY->getUTTKind())
14497 return QualType();
14498 QualType BX = UX->getBaseType(), BY = UY->getBaseType();
14499 if (!Ctx.hasSameType(BX, BY))
14500 return QualType();
14501 // FIXME: It's inefficient to have to unify the base types.
14502 return Ctx.getUnaryTransformType(Ctx.getCommonSugaredType(BX, BY),
14503 Ctx.getQualifiedType(Underlying), KX);
14504 }
14505 case Type::Using: {
14506 const auto *UX = cast<UsingType>(X), *UY = cast<UsingType>(Y);
14507 const UsingShadowDecl *CD = ::getCommonDecl(UX->getDecl(), UY->getDecl());
14508 if (!CD)
14509 return QualType();
14510 return Ctx.getUsingType(::getCommonTypeKeyword(UX, UY, /*IsSame=*/false),
14511 ::getCommonQualifier(Ctx, UX, UY, /*IsSame=*/false),
14512 CD, Ctx.getQualifiedType(Underlying));
14513 }
14514 case Type::MemberPointer: {
14515 const auto *PX = cast<MemberPointerType>(X),
14516 *PY = cast<MemberPointerType>(Y);
14517 CXXRecordDecl *Cls = PX->getMostRecentCXXRecordDecl();
14518 assert(Cls == PY->getMostRecentCXXRecordDecl());
14519 return Ctx.getMemberPointerType(
14520 ::getCommonPointeeType(Ctx, PX, PY),
14521 ::getCommonQualifier(Ctx, PX, PY, /*IsSame=*/false), Cls);
14522 }
14523 case Type::CountAttributed: {
14524 const auto *DX = cast<CountAttributedType>(X),
14526 if (DX->isCountInBytes() != DY->isCountInBytes())
14527 return QualType();
14528 if (DX->isOrNull() != DY->isOrNull())
14529 return QualType();
14530 Expr *CEX = DX->getCountExpr();
14531 Expr *CEY = DY->getCountExpr();
14532 ArrayRef<clang::TypeCoupledDeclRefInfo> CDX = DX->getCoupledDecls();
14533 if (Ctx.hasSameExpr(CEX, CEY))
14534 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14535 DX->isCountInBytes(), DX->isOrNull(),
14536 CDX);
14537 if (!CEX->isIntegerConstantExpr(Ctx) || !CEY->isIntegerConstantExpr(Ctx))
14538 return QualType();
14539 // Two declarations with the same integer constant may still differ in their
14540 // expression pointers, so we need to evaluate them.
14541 llvm::APSInt VX = *CEX->getIntegerConstantExpr(Ctx);
14542 llvm::APSInt VY = *CEY->getIntegerConstantExpr(Ctx);
14543 if (VX != VY)
14544 return QualType();
14545 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14546 DX->isCountInBytes(), DX->isOrNull(),
14547 CDX);
14548 }
14549 case Type::PredefinedSugar:
14550 assert(cast<PredefinedSugarType>(X)->getKind() !=
14552 return QualType();
14553 }
14554 llvm_unreachable("Unhandled Type Class");
14555}
14556
14557static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
14559 while (true) {
14560 QTotal.addConsistentQualifiers(T.Quals);
14561 QualType NT = T.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
14562 if (NT == QualType(T.Ty, 0))
14563 break;
14564 R.push_back(T);
14565 T = NT.split();
14566 }
14567 return R;
14568}
14569
14571 bool Unqualified) const {
14572 assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
14573 if (X == Y)
14574 return X;
14575 if (!Unqualified) {
14576 if (X.isCanonical())
14577 return X;
14578 if (Y.isCanonical())
14579 return Y;
14580 }
14581
14582 SplitQualType SX = X.split(), SY = Y.split();
14583 Qualifiers QX, QY;
14584 // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
14585 // until we reach their underlying "canonical nodes". Note these are not
14586 // necessarily canonical types, as they may still have sugared properties.
14587 // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
14588 auto Xs = ::unwrapSugar(SX, QX), Ys = ::unwrapSugar(SY, QY);
14589
14590 // If this is an ArrayType, the element qualifiers are interchangeable with
14591 // the top level qualifiers.
14592 // * In case the canonical nodes are the same, the elements types are already
14593 // the same.
14594 // * Otherwise, the element types will be made the same, and any different
14595 // element qualifiers will be moved up to the top level qualifiers, per
14596 // 'getCommonArrayElementType'.
14597 // In both cases, this means there may be top level qualifiers which differ
14598 // between X and Y. If so, these differing qualifiers are redundant with the
14599 // element qualifiers, and can be removed without changing the canonical type.
14600 // The desired behaviour is the same as for the 'Unqualified' case here:
14601 // treat the redundant qualifiers as sugar, remove the ones which are not
14602 // common to both sides.
14603 bool KeepCommonQualifiers = Unqualified || isa<ArrayType>(SX.Ty);
14604
14605 if (SX.Ty != SY.Ty) {
14606 // The canonical nodes differ. Build a common canonical node out of the two,
14607 // unifying their sugar. This may recurse back here.
14608 SX.Ty =
14609 ::getCommonNonSugarTypeNode(*this, SX.Ty, QX, SY.Ty, QY).getTypePtr();
14610 } else {
14611 // The canonical nodes were identical: We may have desugared too much.
14612 // Add any common sugar back in.
14613 while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
14614 QX -= SX.Quals;
14615 QY -= SY.Quals;
14616 SX = Xs.pop_back_val();
14617 SY = Ys.pop_back_val();
14618 }
14619 }
14620 if (KeepCommonQualifiers)
14622 else
14623 assert(QX == QY);
14624
14625 // Even though the remaining sugar nodes in Xs and Ys differ, some may be
14626 // related. Walk up these nodes, unifying them and adding the result.
14627 while (!Xs.empty() && !Ys.empty()) {
14628 auto Underlying = SplitQualType(
14629 SX.Ty, Qualifiers::removeCommonQualifiers(SX.Quals, SY.Quals));
14630 SX = Xs.pop_back_val();
14631 SY = Ys.pop_back_val();
14632 SX.Ty = ::getCommonSugarTypeNode(*this, SX.Ty, SY.Ty, Underlying)
14634 // Stop at the first pair which is unrelated.
14635 if (!SX.Ty) {
14636 SX.Ty = Underlying.Ty;
14637 break;
14638 }
14639 QX -= Underlying.Quals;
14640 };
14641
14642 // Add back the missing accumulated qualifiers, which were stripped off
14643 // with the sugar nodes we could not unify.
14644 QualType R = getQualifiedType(SX.Ty, QX);
14645 assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
14646 return R;
14647}
14648
14650 assert(Ty->isFixedPointType());
14651
14653 return Ty;
14654
14655 switch (Ty->castAs<BuiltinType>()->getKind()) {
14656 default:
14657 llvm_unreachable("Not a saturated fixed point type!");
14658 case BuiltinType::SatShortAccum:
14659 return ShortAccumTy;
14660 case BuiltinType::SatAccum:
14661 return AccumTy;
14662 case BuiltinType::SatLongAccum:
14663 return LongAccumTy;
14664 case BuiltinType::SatUShortAccum:
14665 return UnsignedShortAccumTy;
14666 case BuiltinType::SatUAccum:
14667 return UnsignedAccumTy;
14668 case BuiltinType::SatULongAccum:
14669 return UnsignedLongAccumTy;
14670 case BuiltinType::SatShortFract:
14671 return ShortFractTy;
14672 case BuiltinType::SatFract:
14673 return FractTy;
14674 case BuiltinType::SatLongFract:
14675 return LongFractTy;
14676 case BuiltinType::SatUShortFract:
14677 return UnsignedShortFractTy;
14678 case BuiltinType::SatUFract:
14679 return UnsignedFractTy;
14680 case BuiltinType::SatULongFract:
14681 return UnsignedLongFractTy;
14682 }
14683}
14684
14686 assert(Ty->isFixedPointType());
14687
14688 if (Ty->isSaturatedFixedPointType()) return Ty;
14689
14690 switch (Ty->castAs<BuiltinType>()->getKind()) {
14691 default:
14692 llvm_unreachable("Not a fixed point type!");
14693 case BuiltinType::ShortAccum:
14694 return SatShortAccumTy;
14695 case BuiltinType::Accum:
14696 return SatAccumTy;
14697 case BuiltinType::LongAccum:
14698 return SatLongAccumTy;
14699 case BuiltinType::UShortAccum:
14701 case BuiltinType::UAccum:
14702 return SatUnsignedAccumTy;
14703 case BuiltinType::ULongAccum:
14705 case BuiltinType::ShortFract:
14706 return SatShortFractTy;
14707 case BuiltinType::Fract:
14708 return SatFractTy;
14709 case BuiltinType::LongFract:
14710 return SatLongFractTy;
14711 case BuiltinType::UShortFract:
14713 case BuiltinType::UFract:
14714 return SatUnsignedFractTy;
14715 case BuiltinType::ULongFract:
14717 }
14718}
14719
14721 if (LangOpts.OpenCL)
14723
14724 if (LangOpts.CUDA)
14726
14727 return getLangASFromTargetAS(AS);
14728}
14729
14730// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
14731// doesn't include ASTContext.h
14732template
14734 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
14736 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
14737 const clang::ASTContext &Ctx, Decl *Value);
14738
14740 assert(Ty->isFixedPointType());
14741
14742 const TargetInfo &Target = getTargetInfo();
14743 switch (Ty->castAs<BuiltinType>()->getKind()) {
14744 default:
14745 llvm_unreachable("Not a fixed point type!");
14746 case BuiltinType::ShortAccum:
14747 case BuiltinType::SatShortAccum:
14748 return Target.getShortAccumScale();
14749 case BuiltinType::Accum:
14750 case BuiltinType::SatAccum:
14751 return Target.getAccumScale();
14752 case BuiltinType::LongAccum:
14753 case BuiltinType::SatLongAccum:
14754 return Target.getLongAccumScale();
14755 case BuiltinType::UShortAccum:
14756 case BuiltinType::SatUShortAccum:
14757 return Target.getUnsignedShortAccumScale();
14758 case BuiltinType::UAccum:
14759 case BuiltinType::SatUAccum:
14760 return Target.getUnsignedAccumScale();
14761 case BuiltinType::ULongAccum:
14762 case BuiltinType::SatULongAccum:
14763 return Target.getUnsignedLongAccumScale();
14764 case BuiltinType::ShortFract:
14765 case BuiltinType::SatShortFract:
14766 return Target.getShortFractScale();
14767 case BuiltinType::Fract:
14768 case BuiltinType::SatFract:
14769 return Target.getFractScale();
14770 case BuiltinType::LongFract:
14771 case BuiltinType::SatLongFract:
14772 return Target.getLongFractScale();
14773 case BuiltinType::UShortFract:
14774 case BuiltinType::SatUShortFract:
14775 return Target.getUnsignedShortFractScale();
14776 case BuiltinType::UFract:
14777 case BuiltinType::SatUFract:
14778 return Target.getUnsignedFractScale();
14779 case BuiltinType::ULongFract:
14780 case BuiltinType::SatULongFract:
14781 return Target.getUnsignedLongFractScale();
14782 }
14783}
14784
14786 assert(Ty->isFixedPointType());
14787
14788 const TargetInfo &Target = getTargetInfo();
14789 switch (Ty->castAs<BuiltinType>()->getKind()) {
14790 default:
14791 llvm_unreachable("Not a fixed point type!");
14792 case BuiltinType::ShortAccum:
14793 case BuiltinType::SatShortAccum:
14794 return Target.getShortAccumIBits();
14795 case BuiltinType::Accum:
14796 case BuiltinType::SatAccum:
14797 return Target.getAccumIBits();
14798 case BuiltinType::LongAccum:
14799 case BuiltinType::SatLongAccum:
14800 return Target.getLongAccumIBits();
14801 case BuiltinType::UShortAccum:
14802 case BuiltinType::SatUShortAccum:
14803 return Target.getUnsignedShortAccumIBits();
14804 case BuiltinType::UAccum:
14805 case BuiltinType::SatUAccum:
14806 return Target.getUnsignedAccumIBits();
14807 case BuiltinType::ULongAccum:
14808 case BuiltinType::SatULongAccum:
14809 return Target.getUnsignedLongAccumIBits();
14810 case BuiltinType::ShortFract:
14811 case BuiltinType::SatShortFract:
14812 case BuiltinType::Fract:
14813 case BuiltinType::SatFract:
14814 case BuiltinType::LongFract:
14815 case BuiltinType::SatLongFract:
14816 case BuiltinType::UShortFract:
14817 case BuiltinType::SatUShortFract:
14818 case BuiltinType::UFract:
14819 case BuiltinType::SatUFract:
14820 case BuiltinType::ULongFract:
14821 case BuiltinType::SatULongFract:
14822 return 0;
14823 }
14824}
14825
14826llvm::FixedPointSemantics
14828 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
14829 "Can only get the fixed point semantics for a "
14830 "fixed point or integer type.");
14831 if (Ty->isIntegerType())
14832 return llvm::FixedPointSemantics::GetIntegerSemantics(
14833 getIntWidth(Ty), Ty->isSignedIntegerType());
14834
14835 bool isSigned = Ty->isSignedFixedPointType();
14836 return llvm::FixedPointSemantics(
14837 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
14839 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
14840}
14841
14842llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
14843 assert(Ty->isFixedPointType());
14844 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
14845}
14846
14847llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
14848 assert(Ty->isFixedPointType());
14849 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
14850}
14851
14853 assert(Ty->isUnsignedFixedPointType() &&
14854 "Expected unsigned fixed point type");
14855
14856 switch (Ty->castAs<BuiltinType>()->getKind()) {
14857 case BuiltinType::UShortAccum:
14858 return ShortAccumTy;
14859 case BuiltinType::UAccum:
14860 return AccumTy;
14861 case BuiltinType::ULongAccum:
14862 return LongAccumTy;
14863 case BuiltinType::SatUShortAccum:
14864 return SatShortAccumTy;
14865 case BuiltinType::SatUAccum:
14866 return SatAccumTy;
14867 case BuiltinType::SatULongAccum:
14868 return SatLongAccumTy;
14869 case BuiltinType::UShortFract:
14870 return ShortFractTy;
14871 case BuiltinType::UFract:
14872 return FractTy;
14873 case BuiltinType::ULongFract:
14874 return LongFractTy;
14875 case BuiltinType::SatUShortFract:
14876 return SatShortFractTy;
14877 case BuiltinType::SatUFract:
14878 return SatFractTy;
14879 case BuiltinType::SatULongFract:
14880 return SatLongFractTy;
14881 default:
14882 llvm_unreachable("Unexpected unsigned fixed point type");
14883 }
14884}
14885
14886// Given a list of FMV features, return a concatenated list of the
14887// corresponding backend features (which may contain duplicates).
14888static std::vector<std::string> getFMVBackendFeaturesFor(
14889 const llvm::SmallVectorImpl<StringRef> &FMVFeatStrings) {
14890 std::vector<std::string> BackendFeats;
14891 llvm::AArch64::ExtensionSet FeatureBits;
14892 for (StringRef F : FMVFeatStrings)
14893 if (auto FMVExt = llvm::AArch64::parseFMVExtension(F))
14894 if (FMVExt->ID)
14895 FeatureBits.enable(*FMVExt->ID);
14896 FeatureBits.toLLVMFeatureList(BackendFeats);
14897 return BackendFeats;
14898}
14899
14900ParsedTargetAttr
14901ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
14902 assert(TD != nullptr);
14903 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TD->getFeaturesStr());
14904
14905 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) {
14906 return !Target->isValidFeatureName(StringRef{Feat}.substr(1));
14907 });
14908 return ParsedAttr;
14909}
14910
14911void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
14912 const FunctionDecl *FD) const {
14913 if (FD)
14914 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
14915 else
14916 Target->initFeatureMap(FeatureMap, getDiagnostics(),
14917 Target->getTargetOpts().CPU,
14918 Target->getTargetOpts().Features);
14919}
14920
14921// Fills in the supplied string map with the set of target features for the
14922// passed in function.
14923void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
14924 GlobalDecl GD) const {
14925 StringRef TargetCPU = Target->getTargetOpts().CPU;
14926 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
14927 if (const auto *TD = FD->getAttr<TargetAttr>()) {
14929
14930 // Make a copy of the features as passed on the command line into the
14931 // beginning of the additional features from the function to override.
14932 // AArch64 handles command line option features in parseTargetAttr().
14933 if (!Target->getTriple().isAArch64())
14934 ParsedAttr.Features.insert(
14935 ParsedAttr.Features.begin(),
14936 Target->getTargetOpts().FeaturesAsWritten.begin(),
14937 Target->getTargetOpts().FeaturesAsWritten.end());
14938
14939 if (ParsedAttr.CPU != "" && Target->isValidCPUName(ParsedAttr.CPU))
14940 TargetCPU = ParsedAttr.CPU;
14941
14942 // Now populate the feature map, first with the TargetCPU which is either
14943 // the default or a new one from the target attribute string. Then we'll use
14944 // the passed in features (FeaturesAsWritten) along with the new ones from
14945 // the attribute.
14946 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
14947 ParsedAttr.Features);
14948 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
14950 Target->getCPUSpecificCPUDispatchFeatures(
14951 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
14952 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
14953 Features.insert(Features.begin(),
14954 Target->getTargetOpts().FeaturesAsWritten.begin(),
14955 Target->getTargetOpts().FeaturesAsWritten.end());
14956 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14957 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
14958 if (Target->getTriple().isAArch64()) {
14960 TC->getFeatures(Feats, GD.getMultiVersionIndex());
14961 std::vector<std::string> Features = getFMVBackendFeaturesFor(Feats);
14962 Features.insert(Features.begin(),
14963 Target->getTargetOpts().FeaturesAsWritten.begin(),
14964 Target->getTargetOpts().FeaturesAsWritten.end());
14965 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14966 } else if (Target->getTriple().isRISCV()) {
14967 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
14968 std::vector<std::string> Features;
14969 if (VersionStr != "default") {
14970 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(VersionStr);
14971 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
14972 ParsedAttr.Features.end());
14973 }
14974 Features.insert(Features.begin(),
14975 Target->getTargetOpts().FeaturesAsWritten.begin(),
14976 Target->getTargetOpts().FeaturesAsWritten.end());
14977 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14978 } else {
14979 std::vector<std::string> Features;
14980 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
14981 if (VersionStr.starts_with("arch="))
14982 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
14983 else if (VersionStr != "default")
14984 Features.push_back((StringRef{"+"} + VersionStr).str());
14985 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14986 }
14987 } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
14988 std::vector<std::string> Features;
14989 if (Target->getTriple().isRISCV()) {
14990 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TV->getName());
14991 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
14992 ParsedAttr.Features.end());
14993 } else {
14994 assert(Target->getTriple().isAArch64());
14996 TV->getFeatures(Feats);
14997 Features = getFMVBackendFeaturesFor(Feats);
14998 }
14999 Features.insert(Features.begin(),
15000 Target->getTargetOpts().FeaturesAsWritten.begin(),
15001 Target->getTargetOpts().FeaturesAsWritten.end());
15002 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15003 } else {
15004 FeatureMap = Target->getTargetOpts().FeatureMap;
15005 }
15006}
15007
15009 CanQualType KernelNameType,
15010 const FunctionDecl *FD) {
15011 // Host and device compilation may use different ABIs and different ABIs
15012 // may allocate name mangling discriminators differently. A discriminator
15013 // override is used to ensure consistent discriminator allocation across
15014 // host and device compilation.
15015 auto DeviceDiscriminatorOverrider =
15016 [](ASTContext &Ctx, const NamedDecl *ND) -> UnsignedOrNone {
15017 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
15018 if (RD->isLambda())
15019 return RD->getDeviceLambdaManglingNumber();
15020 return std::nullopt;
15021 };
15022 std::unique_ptr<MangleContext> MC{ItaniumMangleContext::create(
15023 Context, Context.getDiagnostics(), DeviceDiscriminatorOverrider)};
15024
15025 // Construct a mangled name for the SYCL kernel caller offload entry point.
15026 // FIXME: The Itanium typeinfo mangling (_ZTS<type>) is currently used to
15027 // name the SYCL kernel caller offload entry point function. This mangling
15028 // does not suffice to clearly identify symbols that correspond to SYCL
15029 // kernel caller functions, nor is this mangling natural for targets that
15030 // use a non-Itanium ABI.
15031 std::string Buffer;
15032 Buffer.reserve(128);
15033 llvm::raw_string_ostream Out(Buffer);
15034 MC->mangleCanonicalTypeName(KernelNameType, Out);
15035 std::string KernelName = Out.str();
15036
15037 return {KernelNameType, FD, KernelName};
15038}
15039
15041 // If the function declaration to register is invalid or dependent, the
15042 // registration attempt is ignored.
15043 if (FD->isInvalidDecl() || FD->isTemplated())
15044 return;
15045
15046 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
15047 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
15048
15049 // Be tolerant of multiple registration attempts so long as each attempt
15050 // is for the same entity. Callers are obligated to detect and diagnose
15051 // conflicting kernel names prior to calling this function.
15052 CanQualType KernelNameType = getCanonicalType(SKEPAttr->getKernelName());
15053 auto IT = SYCLKernels.find(KernelNameType);
15054 assert((IT == SYCLKernels.end() ||
15055 declaresSameEntity(FD, IT->second.getKernelEntryPointDecl())) &&
15056 "SYCL kernel name conflict");
15057 (void)IT;
15058 SYCLKernels.insert(std::make_pair(
15059 KernelNameType, BuildSYCLKernelInfo(*this, KernelNameType, FD)));
15060}
15061
15063 CanQualType KernelNameType = getCanonicalType(T);
15064 return SYCLKernels.at(KernelNameType);
15065}
15066
15068 CanQualType KernelNameType = getCanonicalType(T);
15069 auto IT = SYCLKernels.find(KernelNameType);
15070 if (IT != SYCLKernels.end())
15071 return &IT->second;
15072 return nullptr;
15073}
15074
15076 OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
15077 return *OMPTraitInfoVector.back();
15078}
15079
15082 const ASTContext::SectionInfo &Section) {
15083 if (Section.Decl)
15084 return DB << Section.Decl;
15085 return DB << "a prior #pragma section";
15086}
15087
15088bool ASTContext::mayExternalize(const Decl *D) const {
15089 bool IsInternalVar =
15090 isa<VarDecl>(D) &&
15092 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
15093 !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
15094 (D->hasAttr<CUDAConstantAttr>() &&
15095 !D->getAttr<CUDAConstantAttr>()->isImplicit());
15096 // CUDA/HIP: managed variables need to be externalized since it is
15097 // a declaration in IR, therefore cannot have internal linkage. Kernels in
15098 // anonymous name space needs to be externalized to avoid duplicate symbols.
15099 return (IsInternalVar &&
15100 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
15101 (D->hasAttr<CUDAGlobalAttr>() &&
15103 GVA_Internal);
15104}
15105
15107 return mayExternalize(D) &&
15108 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
15110}
15111
15112StringRef ASTContext::getCUIDHash() const {
15113 if (!CUIDHash.empty())
15114 return CUIDHash;
15115 if (LangOpts.CUID.empty())
15116 return StringRef();
15117 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
15118 return CUIDHash;
15119}
15120
15121const CXXRecordDecl *
15123 assert(ThisClass);
15124 assert(ThisClass->isPolymorphic());
15125 const CXXRecordDecl *PrimaryBase = ThisClass;
15126 while (1) {
15127 assert(PrimaryBase);
15128 assert(PrimaryBase->isPolymorphic());
15129 auto &Layout = getASTRecordLayout(PrimaryBase);
15130 auto Base = Layout.getPrimaryBase();
15131 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
15132 break;
15133 PrimaryBase = Base;
15134 }
15135 return PrimaryBase;
15136}
15137
15139 StringRef MangledName) {
15140 auto *Method = cast<CXXMethodDecl>(VirtualMethodDecl.getDecl());
15141 assert(Method->isVirtual());
15142 bool DefaultIncludesPointerAuth =
15143 LangOpts.PointerAuthCalls || LangOpts.PointerAuthIntrinsics;
15144
15145 if (!DefaultIncludesPointerAuth)
15146 return true;
15147
15148 auto Existing = ThunksToBeAbbreviated.find(VirtualMethodDecl);
15149 if (Existing != ThunksToBeAbbreviated.end())
15150 return Existing->second.contains(MangledName.str());
15151
15152 std::unique_ptr<MangleContext> Mangler(createMangleContext());
15153 llvm::StringMap<llvm::SmallVector<std::string, 2>> Thunks;
15154 auto VtableContext = getVTableContext();
15155 if (const auto *ThunkInfos = VtableContext->getThunkInfo(VirtualMethodDecl)) {
15156 auto *Destructor = dyn_cast<CXXDestructorDecl>(Method);
15157 for (const auto &Thunk : *ThunkInfos) {
15158 SmallString<256> ElidedName;
15159 llvm::raw_svector_ostream ElidedNameStream(ElidedName);
15160 if (Destructor)
15161 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15162 Thunk, /* elideOverrideInfo */ true,
15163 ElidedNameStream);
15164 else
15165 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ true,
15166 ElidedNameStream);
15167 SmallString<256> MangledName;
15168 llvm::raw_svector_ostream mangledNameStream(MangledName);
15169 if (Destructor)
15170 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15171 Thunk, /* elideOverrideInfo */ false,
15172 mangledNameStream);
15173 else
15174 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ false,
15175 mangledNameStream);
15176
15177 Thunks[ElidedName].push_back(std::string(MangledName));
15178 }
15179 }
15180 llvm::StringSet<> SimplifiedThunkNames;
15181 for (auto &ThunkList : Thunks) {
15182 llvm::sort(ThunkList.second);
15183 SimplifiedThunkNames.insert(ThunkList.second[0]);
15184 }
15185 bool Result = SimplifiedThunkNames.contains(MangledName);
15186 ThunksToBeAbbreviated[VirtualMethodDecl] = std::move(SimplifiedThunkNames);
15187 return Result;
15188}
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 getCanonicalTemplateArguments(const ASTContext &C, ArrayRef< TemplateArgument > Args, bool &AnyNonCanonArgs)
static char getObjCEncodingForPrimitiveType(const ASTContext *C, const BuiltinType *BT)
static bool isSameQualifier(const NestedNameSpecifier X, const NestedNameSpecifier Y)
static bool unionHasUniqueObjectRepresentations(const ASTContext &Context, const RecordDecl *RD, bool CheckIfTriviallyCopyable)
static TypedefDecl * CreateHexagonBuiltinVaListDecl(const ASTContext *Context)
#define CANONICAL_TYPE(Class)
static ElaboratedTypeKeyword getCommonTypeKeyword(const T *X, const T *Y, bool IsSame)
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 const TemplateArgument * getDefaultTemplateArgumentOrNone(const NamedDecl *P)
static QualType getCommonArrayElementType(const ASTContext &Ctx, const T *X, Qualifiers &QX, const T *Y, Qualifiers &QY)
#define SUGAR_FREE_TYPE(Class)
static SYCLKernelInfo BuildSYCLKernelInfo(ASTContext &Context, CanQualType KernelNameType, const FunctionDecl *FD)
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 bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B)
static const Decl & adjustDeclToTemplate(const Decl &D)
If we have a 'templated' declaration for a template, adjust 'D' to refer to the actual template.
static TemplateName getCommonTemplateName(const ASTContext &Ctx, TemplateName X, TemplateName Y, bool IgnoreDeduced=false)
static int CmpProtocolNames(ObjCProtocolDecl *const *LHS, ObjCProtocolDecl *const *RHS)
CmpProtocolNames - Comparison predicate for sorting protocols alphabetically.
static auto * getCommonSizeExpr(const ASTContext &Ctx, T *X, T *Y)
static TypedefDecl * CreatePowerABIBuiltinVaListDecl(const ASTContext *Context)
static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y)
static TemplateArgument getCommonTemplateArgument(const ASTContext &Ctx, const TemplateArgument &X, const TemplateArgument &Y)
static std::optional< int64_t > structHasUniqueObjectRepresentations(const ASTContext &Context, const RecordDecl *RD, bool CheckIfTriviallyCopyable)
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 NestedNameSpecifier getCommonNNS(const ASTContext &Ctx, NestedNameSpecifier NNS1, NestedNameSpecifier NNS2, bool IsSame)
Returns a NestedNameSpecifier which has only the common sugar present in both NNS1 and NNS2.
static TypedefDecl * CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context)
static int64_t getSubobjectOffset(const FieldDecl *Field, const ASTContext &Context, const clang::ASTRecordLayout &)
static QualType getCommonSugarTypeNode(const ASTContext &Ctx, const Type *X, const Type *Y, SplitQualType Underlying)
static TypedefDecl * CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context)
static QualType getCommonNonSugarTypeNode(const ASTContext &Ctx, const Type *X, Qualifiers &QX, const Type *Y, Qualifiers &QY)
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)
static ElaboratedTypeKeyword getCanonicalElaboratedTypeKeyword(ElaboratedTypeKeyword Keyword)
static QualType getCommonPointeeType(const ASTContext &Ctx, const T *X, const T *Y)
static auto getCommonIndexTypeCVRQualifiers(const ArrayType *X, const ArrayType *Y)
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
@ FloatRank
@ LongDoubleRank
@ Float16Rank
@ Ibm128Rank
@ Float128Rank
@ BFloat16Rank
@ HalfRank
@ DoubleRank
static TypedefDecl * CreateCharPtrBuiltinVaListDecl(const ASTContext *Context)
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 bool getCommonTemplateArguments(const ASTContext &Ctx, SmallVectorImpl< TemplateArgument > &R, ArrayRef< TemplateArgument > Xs, ArrayRef< TemplateArgument > Ys)
static TypedefDecl * CreateXtensaABIBuiltinVaListDecl(const ASTContext *Context)
static QualType getCommonElementType(const ASTContext &Ctx, const T *X, const T *Y)
static void mergeTypeLists(const ASTContext &Ctx, SmallVectorImpl< QualType > &Out, ArrayRef< QualType > X, ArrayRef< QualType > Y)
static void encodeTypeForFunctionPointerAuth(const ASTContext &Ctx, raw_ostream &OS, QualType QT)
Encode a function type for use in the discriminator of a function pointer type.
static std::optional< int64_t > structSubobjectsHaveUniqueObjectRepresentations(const RangeT &Subobjects, int64_t CurOffsetInBits, const ASTContext &Context, const clang::ASTRecordLayout &Layout, bool CheckIfTriviallyCopyable)
static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty)
getRVVTypeSize - Return RVV vector register size.
static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal)
static TemplateName getCommonTemplateNameChecked(const ASTContext &Ctx, TemplateName X, TemplateName Y, bool IgnoreDeduced)
static int compareObjCProtocolsByName(ObjCProtocolDecl *const *lhs, ObjCProtocolDecl *const *rhs)
Comparison routine for Objective-C protocols to be used with llvm::array_pod_sort.
static std::string charUnitsToString(const CharUnits &CU)
static const TagDecl * getNonInjectedClassName(const TagDecl *TD)
static bool hasAnyPackExpansions(ArrayRef< TemplateArgument > Args)
static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED)
static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod, SmallVectorImpl< const NamedDecl * > &Redeclared)
static SmallVector< SourceLocation, 2 > getDeclLocsForCommentSearch(const Decl *D, SourceManager &SourceMgr)
static auto getCommonTypes(const ASTContext &Ctx, ArrayRef< QualType > Xs, ArrayRef< QualType > Ys, bool Unqualified=false)
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)
static NestedNameSpecifier getCommonQualifier(const ASTContext &Ctx, const T *X, const T *Y, bool IsSame)
#define UNEXPECTED_TYPE(Class, Kind)
static TypedefDecl * CreateVaListDecl(const ASTContext *Context, TargetInfo::BuiltinVaListKind Kind)
static bool primaryBaseHaseAddressDiscriminatedVTableAuthentication(const ASTContext &Context, const CXXRecordDecl *Class)
static std::vector< std::string > getFMVBackendFeaturesFor(const llvm::SmallVectorImpl< StringRef > &FMVFeatStrings)
Defines the clang::ASTContext interface.
#define V(N, I)
#define BuiltinTemplate(BTName)
Definition ASTContext.h:419
Provides definitions for the various language-specific address spaces.
static bool isUnsigned(SValBuilder &SVB, NonLoc Value)
Defines enum values for all the target-independent builtin functions.
static bool CanThrow(Expr *E, ASTContext &Ctx)
Definition CFG.cpp:2777
Defines the clang::CommentOptions interface.
static Decl::Kind getKind(const Decl *D)
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.
FormatToken * Next
The next token in the unwrapped line.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
static const Decl * getCanonicalDecl(const Decl *D)
#define X(type, name)
Definition Value.h:97
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
llvm::MachO::Record Record
Definition MachO.h:31
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:95
Defines the clang::Module class, which describes a module in the source code.
Defines types useful for describing an Objective-C runtime.
#define SM(sm)
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.
static QualType getPointeeType(const MemRegion *R)
Defines the TargetCXXABI class, which abstracts details of the C++ ABI that we're targeting.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
__device__ __2f16 float c
QualType getReadPipeType(QualType T) const
Return a read_only pipe type for the specified type.
QualType getWritePipeType(QualType T) const
Return a write_only pipe type for the specified type.
@ GE_Missing_stdio
Missing a type from <stdio.h>
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
RawComment * getRawCommentForDeclNoCacheImpl(const Decl *D, const SourceLocation RepresentativeLocForDecl, const std::map< unsigned, RawComment * > &CommentsInFile) const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
bool isMemberPointerToDerivedMember() const
Definition APValue.cpp:1073
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1066
ArrayRef< const CXXRecordDecl * > getMemberPointerPath() const
Definition APValue.cpp:1080
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:188
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.
CanQualType AccumTy
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
TranslationUnitDecl * getTranslationUnitDecl() const
const ConstantArrayType * getAsConstantArrayType(QualType T) const
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.
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.
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
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.
QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr, QualType Wrapped) const
llvm::DenseMap< const Decl *, comments::FullComment * > ParsedComments
Mapping from declarations to parsed comments attached to any redeclaration.
Definition ASTContext.h:953
unsigned getManglingNumber(const NamedDecl *ND, bool ForAuxTarget=false) const
CanQualType LongTy
unsigned getIntWidth(QualType T) const
CanQualType getCanonicalParamType(QualType T) const
Return the canonical parameter type corresponding to the specific potentially non-canonical one.
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
TemplateOrSpecializationInfo getTemplateOrSpecializationInfo(const VarDecl *Var)
CanQualType WIntTy
@ 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
CanQualType SatUnsignedFractTy
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 areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
TypedefDecl * getObjCSelDecl() const
Retrieve the typedef corresponding to the predefined 'SEL' type in Objective-C.
CanQualType UnsignedShortAccumTy
TypedefDecl * getObjCInstanceTypeDecl()
Retrieve the typedef declaration corresponding to the Objective-C "instancetype" type.
QualType adjustFunctionResultType(QualType FunctionType, QualType NewResultType)
Change the result type of a function type, preserving sugar such as attributed types.
void setTemplateOrSpecializationInfo(VarDecl *Inst, TemplateOrSpecializationInfo TSI)
bool isTypeAwareOperatorNewOrDelete(const FunctionDecl *FD) const
bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, ObjCProtocolDecl *rProto) const
ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the inheritance hierarchy of 'rProto...
TypedefDecl * buildImplicitTypedef(QualType T, StringRef Name) const
Create a new implicit TU-level typedef declaration.
QualType getCanonicalTemplateSpecializationType(ElaboratedTypeKeyword Keyword, TemplateName T, ArrayRef< TemplateArgument > CanonicalArgs) const
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.
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:741
comments::FullComment * cloneFullComment(comments::FullComment *FC, const Decl *D) 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.
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType, const Attr *attr=nullptr) const
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.
std::unique_ptr< MangleNumberingContext > createMangleNumberingContext() const
CanQualType SatAccumTy
QualType getUnsignedPointerDiffType() const
Return the unique unsigned counterpart of "ptrdiff_t" integer type.
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 getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
CanQualType ShortAccumTy
ASTMutationListener * getASTMutationListener() const
Retrieve a pointer to the AST mutation listener associated with this AST context, if any.
unsigned NumImplicitCopyAssignmentOperatorsDeclared
The number of implicitly-declared copy assignment operators for which declarations were built.
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,...
unsigned char getFixedPointIBits(QualType Ty) const
QualType getSubstBuiltinTemplatePack(const TemplateArgument &ArgPack)
QualType getCorrespondingSignedFixedPointType(QualType Ty) const
IntrusiveRefCntPtr< ExternalASTSource > ExternalSource
Definition ASTContext.h:742
CanQualType FloatTy
QualType getArrayParameterType(QualType Ty) const
Return the uniqued reference to a specified array parameter type from the original array type.
QualType getCountAttributedType(QualType T, Expr *CountExpr, bool CountInBytes, bool OrNull, ArrayRef< TypeCoupledDeclRefInfo > DependentDecls) const
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 ...
unsigned NumImplicitDestructorsDeclared
The number of implicitly-declared destructors for which declarations were built.
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.
bool propertyTypesAreCompatible(QualType, QualType)
void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, UsingShadowDecl *Pattern)
CanQualType DoubleTy
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
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.
OpenCLTypeKind getOpenCLTypeKind(const Type *T) const
Map an AST Type to an OpenCLTypeKind enum value.
TemplateName getDependentTemplateName(const DependentTemplateStorage &Name) const
Retrieve the template name that represents a dependent template name such as MetaFun::template operat...
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.
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
CanQualType OMPArrayShapingTy
ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents, SelectorTable &sels, Builtin::Context &builtins, TranslationUnitKind TUKind)
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
TemplateName getCanonicalTemplateName(TemplateName Name, bool IgnoreDeduced=false) const
Retrieves the "canonical" template name that refers to a given template.
unsigned getStaticLocalNumber(const VarDecl *VD) const
void addComment(const RawComment &RC)
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...
void setRelocationInfoForCXXRecord(const CXXRecordDecl *, CXXRecordDeclRelocationInfo)
QualType getSubstTemplateTypeParmType(QualType Replacement, Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex, bool Final) const
Retrieve a substitution-result type.
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.
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...
CanQualType UnsignedLongFractTy
QualType mergeTagDefinitions(QualType, QualType)
overridden_method_range overridden_methods(const CXXMethodDecl *Method) const
void setIsTypeAwareOperatorNewOrDelete(const FunctionDecl *FD, bool IsTypeAware)
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
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
bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT, ObjCInterfaceDecl *IDecl)
QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in QT's qualified-id protocol list adopt...
FunctionProtoType::ExceptionSpecInfo mergeExceptionSpecs(FunctionProtoType::ExceptionSpecInfo ESI1, FunctionProtoType::ExceptionSpecInfo ESI2, SmallVectorImpl< QualType > &ExceptionTypeStorage, bool AcceptDependent) const
void addLazyModuleInitializers(Module *M, ArrayRef< GlobalDeclID > IDs)
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...
bool BlockRequiresCopying(QualType Ty, const VarDecl *D)
Returns true iff we need copy/dispose helpers for the given type.
CanQualType NullPtrTy
QualType getUsingType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UsingShadowDecl *D, QualType UnderlyingType=QualType()) const
CanQualType WideCharTy
CanQualType OMPIteratorTy
IdentifierTable & Idents
Definition ASTContext.h:737
Builtin::Context & BuiltinInfo
Definition ASTContext.h:739
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:891
QualType getFunctionTypeWithoutPtrSizes(QualType T)
Get a function type and produce the equivalent function type where pointer size address spaces in the...
uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID, const ObjCIvarDecl *Ivar) const
Get the offset of an ObjCIvarDecl in bits.
SelectorTable & Selectors
Definition ASTContext.h:738
bool isTypeIgnoredBySanitizer(const SanitizerMask &Mask, const QualType &Ty) const
Check if a type can have its sanitizer instrumentation elided based on its presence within an ignorel...
unsigned getMinGlobalAlignOfVar(uint64_t Size, const VarDecl *VD) const
Return the minimum alignment as specified by the target.
RawCommentList Comments
All comments in this translation unit.
Definition ASTContext.h:924
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
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod) const
Retrieves the default calling convention for the current context.
bool canBindObjCObjectType(QualType To, QualType From)
TemplateTemplateParmDecl * insertCanonicalTemplateTemplateParmDeclInternal(TemplateTemplateParmDecl *CanonTTP) const
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...
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier NNS, const IdentifierInfo *Name) const
Qualifiers::GC getObjCGCAttrKind(QualType Ty) const
Return one of the GCNone, Weak or Strong Objective-C garbage collection attributes.
CanQualType Ibm128Ty
bool hasUniqueObjectRepresentations(QualType Ty, bool CheckIfTriviallyCopyable=true) const
Return true if the specified type has unique object representations according to (C++17 [meta....
CanQualType getCanonicalSizeType() const
bool typesAreBlockPointerCompatible(QualType, QualType)
CanQualType SatUnsignedAccumTy
bool useAbbreviatedThunkName(GlobalDecl VirtualMethodDecl, StringRef MangledName)
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...
CanQualType ArraySectionTy
CanQualType ObjCBuiltinIdTy
overridden_cxx_method_iterator overridden_methods_end(const CXXMethodDecl *Method) const
VTableContextBase * getVTableContext()
ComparisonCategories CompCategories
Types and expressions required to build C++2a three-way comparisons using operator<=>,...
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
PointerAuthQualifier getObjCMemberSelTypePtrAuth()
QualType AutoDeductTy
CanQualType BoolTy
void cacheRawCommentForDecl(const Decl &OriginalD, const RawComment &Comment) const
Attaches Comment to OriginalD and to its redeclaration chain and removes the redeclaration chain from...
void attachCommentsToJustParsedDecls(ArrayRef< Decl * > Decls, const Preprocessor *PP)
Searches existing comments for doc comments that should be attached to Decls.
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.
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
std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const
Emit the encoded type for the function Decl into S.
TypeSourceInfo * getTemplateSpecializationTypeInfo(ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc, TemplateName T, SourceLocation TLoc, const TemplateArgumentListInfo &SpecifiedArgs, ArrayRef< TemplateArgument > CanonicalArgs, QualType Canon=QualType()) const
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
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
void addOverriddenMethod(const CXXMethodDecl *Method, const CXXMethodDecl *Overridden)
Note that the given C++ Method overrides the given Overridden method.
TemplateTemplateParmDecl * findCanonicalTemplateTemplateParmDeclInternal(TemplateTemplateParmDecl *TTP) const
CanQualType Float128Ty
CanQualType ObjCBuiltinClassTy
unsigned NumImplicitDefaultConstructorsDeclared
The number of implicitly-declared default constructors for which declarations were built.
CanQualType UnresolvedTemplateTy
OMPTraitInfo & getNewOMPTraitInfo()
Return a new OMPTraitInfo object owned by this context.
friend class CXXRecordDecl
Definition ASTContext.h:520
CanQualType UnsignedLongTy
void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass, SmallVectorImpl< const ObjCIvarDecl * > &Ivars) const
DeepCollectObjCIvars - This routine first collects all declared, but not synthesized,...
bool computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits, unsigned NumPositiveBits, QualType &BestType, QualType &BestPromotionType)
Compute BestType and BestPromotionType for an enum based on the highest number of negative and positi...
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,...
QualType adjustType(QualType OldType, llvm::function_ref< QualType(QualType)> Adjust) const
Rebuild a type, preserving any existing type sugar.
void addedLocalImportDecl(ImportDecl *Import)
Notify the AST context that a new import declaration has been parsed or implicitly created within thi...
const TranslationUnitKind TUKind
Definition ASTContext.h:740
CanQualType UnsignedLongAccumTy
QualType AutoRRefDeductTy
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
CanQualType ShortFractTy
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.
QualType getSubstTemplateTypeParmPackType(Decl *AssociatedDecl, unsigned Index, bool Final, const TemplateArgument &ArgPack)
CanQualType BoundMemberTy
CanQualType SatUnsignedShortFractTy
CanQualType CharTy
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
bool hasSameFunctionTypeIgnoringParamABI(QualType T, QualType U) const
Determine if two function types are the same, ignoring parameter ABI annotations.
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:927
BlockVarCopyInit getBlockVarCopyInit(const VarDecl *VD) const
Get the copy initialization expression of the VarDecl VD, or nullptr if none exists.
QualType getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size, uint32_t Alignment, ArrayRef< SpirvOperand > Operands)
unsigned NumImplicitMoveConstructorsDeclared
The number of implicitly-declared move constructors for which declarations were built.
bool isInSameModule(const Module *M1, const Module *M2) const
If the two module M1 and M2 are in the same module.
unsigned NumImplicitCopyConstructorsDeclared
The number of implicitly-declared copy constructors for which declarations were built.
CanQualType IntTy
llvm::DenseSet< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
CanQualType PseudoObjectTy
QualType getWebAssemblyExternrefType() const
Return a WebAssembly externref type.
void setTraversalScope(const std::vector< Decl * > &)
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.
friend class NestedNameSpecifier
Definition ASTContext.h:189
void PrintStats() const
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.
unsigned NumImplicitDestructors
The number of implicitly-declared destructors.
CanQualType Float16Ty
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
bool isAlignmentRequired(const Type *T) const
Determine if the alignment the type has was required using an alignment attribute.
TagDecl * MSGuidTagDecl
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.
CanQualType SignedCharTy
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
ASTMutationListener * Listener
Definition ASTContext.h:743
CanQualType ObjCBuiltinBoolTy
TypeInfoChars getTypeInfoInChars(const Type *T) const
QualType getPredefinedSugarType(PredefinedSugarType::Kind KD) 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
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.
TemplateTemplateParmDecl * getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const
Canonicalize the given TemplateTemplateParmDecl.
CanQualType OCLClkEventTy
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:790
void ResetObjCLayout(const ObjCInterfaceDecl *D)
ArrayRef< Module * > getModulesWithMergedDefinition(const NamedDecl *Def)
Get the additional modules in which the definition Def has been merged.
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
CanQualType SatUnsignedShortAccumTy
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.
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.
QualType getPackIndexingType(QualType Pattern, Expr *IndexExpr, bool FullySubstituted=false, ArrayRef< QualType > Expansions={}, UnsignedOrNone Index=std::nullopt) const
static bool isObjCNSObjectType(QualType Ty)
Return true if this is an NSObject object with its NSObject attribute set.
GVALinkage GetGVALinkageForVariable(const VarDecl *VD) const
llvm::PointerUnion< VarTemplateDecl *, MemberSpecializationInfo * > TemplateOrSpecializationInfo
A type synonym for the TemplateOrInstantiation mapping.
Definition ASTContext.h:512
UsingShadowDecl * getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst)
QualType getVariableArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a non-unique reference to the type for a variable array of the specified element type.
QualType getObjCIdType() const
Represents the Objective-CC id type.
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".
QualType getFunctionTypeWithoutParamABIs(QualType T) const
Get or construct a function type that is equivalent to the input type except that the parameter ABI a...
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
QualType getCorrespondingUnsaturatedType(QualType Ty) const
comments::FullComment * getCommentForDecl(const Decl *D, const Preprocessor *PP) const
Return parsed documentation comment attached to a given declaration.
TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl) const
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.
llvm::DenseMap< CanQualType, SYCLKernelInfo > SYCLKernels
Map of SYCL kernels indexed by the unique type used to name the kernel.
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.
QualType getTypeDeclType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypeDecl *Decl) const
bool isDestroyingOperatorDelete(const FunctionDecl *FD) const
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CanQualType UnsignedInt128Ty
CanQualType BuiltinFnTy
ObjCInterfaceDecl * getObjCProtocolDecl() const
Retrieve the Objective-C class declaration corresponding to the predefined Protocol class.
unsigned NumImplicitDefaultConstructors
The number of implicitly-declared default constructors.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
llvm::iterator_range< overridden_cxx_method_iterator > overridden_method_range
unsigned NumImplicitMoveAssignmentOperatorsDeclared
The number of implicitly-declared move assignment operators for which declarations were built.
void setManglingNumber(const NamedDecl *ND, unsigned Number)
llvm::DenseMap< const Decl *, const RawComment * > DeclRawComments
Mapping from declaration to directly attached comment.
Definition ASTContext.h:933
CanQualType OCLSamplerTy
QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent, bool IsPack=false, TemplateDecl *TypeConstraintConcept=nullptr, ArrayRef< TemplateArgument > TypeConstraintArgs={}) const
C++11 deduced auto type.
TypedefDecl * getBuiltinVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_va_list type.
CanQualType getCanonicalTypeDeclType(const TypeDecl *TD) const
CanQualType VoidTy
QualType getPackExpansionType(QualType Pattern, UnsignedOrNone NumExpansions, bool ExpectPackInType=true) const
Form a pack expansion type with the given pattern.
CanQualType UnsignedCharTy
CanQualType UnsignedShortFractTy
BuiltinTemplateDecl * buildBuiltinTemplateDecl(BuiltinTemplateKind BTK, const IdentifierInfo *II) const
void * Allocate(size_t Size, unsigned Align=8) const
Definition ASTContext.h:811
bool canBuiltinBeRedeclared(const FunctionDecl *) const
Return whether a declaration to a builtin is allowed to be overloaded/redeclared.
CanQualType UnsignedIntTy
unsigned NumImplicitMoveConstructors
The number of implicitly-declared move constructors.
QualType getTypedefType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType UnderlyingType=QualType(), std::optional< bool > TypeMatchesDeclOrNone=std::nullopt) const
Return the unique reference to the type for the specified typedef-name decl.
QualType getObjCTypeParamType(const ObjCTypeParamDecl *Decl, ArrayRef< ObjCProtocolDecl * > protocols) const
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.
QualType getTemplateSpecializationType(ElaboratedTypeKeyword Keyword, TemplateName T, ArrayRef< TemplateArgument > SpecifiedArgs, ArrayRef< TemplateArgument > CanonicalArgs, QualType Underlying=QualType()) const
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
TemplateName getQualifiedTemplateName(NestedNameSpecifier Qualifier, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
bool isSameAssociatedConstraint(const AssociatedConstraint &ACX, const AssociatedConstraint &ACY) const
Determine whether two 'requires' expressions are similar enough that they may be used in re-declarati...
QualType getExceptionObjectType(QualType T) const
CanQualType UnknownAnyTy
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 ...
FieldDecl * getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) const
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
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
CanQualType OCLReserveIDTy
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...
void registerSYCLEntryPointFunction(FunctionDecl *FD)
Generates and stores SYCL kernel metadata for the provided SYCL kernel entry point function.
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
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...
void UnwrapSimilarArrayTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true) const
Attempt to unwrap two types that may both be array types with the same bound (or both be array types ...
bool isRepresentableIntegerValue(llvm::APSInt &Value, QualType T)
Determine whether the given integral value is representable within the given type T.
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.
const SYCLKernelInfo & getSYCLKernelInfo(QualType T) const
Given a type used as a SYCL kernel name, returns a reference to the metadata generated from the corre...
bool canAssignObjCInterfacesInBlockPointer(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT, bool BlockReturnType)
canAssignObjCInterfacesInBlockPointer - This routine is specifically written for providing type-safet...
CanQualType SatUnsignedLongFractTy
QualType getMemberPointerType(QualType T, NestedNameSpecifier Qualifier, const CXXRecordDecl *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
const CXXConstructorDecl * getCopyConstructorForExceptionObject(CXXRecordDecl *RD)
QualType getDependentAddressSpaceType(QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttrLoc) const
RawComment * getRawCommentForDeclNoCache(const Decl *D) const
Return the documentation comment attached to a given declaration, without looking into cache.
QualType getTagType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TagDecl *TD, bool OwnsTag) const
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
CanQualType getMSGuidType() const
Retrieve the implicitly-predeclared 'struct _GUID' type.
const VariableArrayType * getAsVariableArrayType(QualType T) const
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.
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
StringLiteral * getPredefinedStringLiteralFromCache(StringRef Key) const
Return a string representing the human readable name for the specified function declaration or file n...
CanQualType getCanonicalUnresolvedUsingType(const UnresolvedUsingTypenameDecl *D) const
bool hasSimilarType(QualType T1, QualType T2) const
Determine if two types are similar, according to the C++ rules.
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 hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
CanQualType FractTy
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)
void deduplicateMergedDefinitionsFor(NamedDecl *ND)
Clean up the merged definition list.
DiagnosticsEngine & getDiagnostics() const
QualType getAdjustedParameterType(QualType T) const
Perform adjustment on the parameter type of a function.
CanQualType LongAccumTy
interp::Context & getInterpContext()
Returns the clang bytecode interpreter context.
CanQualType Char32Ty
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
UnnamedGlobalConstantDecl * getUnnamedGlobalConstantDecl(QualType Ty, const APValue &Value) const
Return a declaration for a uniquified anonymous global constant corresponding to a given APValue.
CanQualType SatFractTy
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
QualType getUnresolvedUsingType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UnresolvedUsingTypenameDecl *D) const
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
bool hasSameTemplateName(const TemplateName &X, const TemplateName &Y, bool IgnoreDeduced=false) const
Determine whether the given template names refer to the same template.
CanQualType SatLongFractTy
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:856
void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl)
CanQualType OCLQueueTy
CanQualType LongFractTy
CanQualType SatShortAccumTy
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
CanQualType BFloat16Ty
unsigned NumImplicitCopyConstructors
The number of implicitly-declared copy constructors.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType IncompleteMatrixIdxTy
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
QualType getDeducedTemplateSpecializationType(ElaboratedTypeKeyword Keyword, TemplateName Template, QualType DeducedType, bool IsDependent) const
C++17 deduced class template specialization type.
TargetCXXABI::Kind getCXXABIKind() const
Return the C++ ABI kind that should be used.
QualType getHLSLAttributedResourceType(QualType Wrapped, QualType Contained, const HLSLAttributedResourceType::Attributes &Attrs)
bool UnwrapSimilarTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true) const
Attempt to unwrap two types that may be similar (C++ [conv.qual]).
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
QualType getSignedSizeType() const
Return the unique signed counterpart of the integer type corresponding to size_t.
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const
Return number of constant array elements.
CanQualType SatUnsignedLongAccumTy
QualType getUnconstrainedType(QualType T) const
Remove any type constraints from a template parameter type, for equivalence comparison of template pa...
CanQualType LongLongTy
CanQualType getCanonicalTagType(const TagDecl *TD) const
bool isSameTemplateArgument(const TemplateArgument &Arg1, const TemplateArgument &Arg2) const
Determine whether the given template arguments Arg1 and Arg2 are equivalent.
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:949
uint64_t getArrayInitLoopExprElementCount(const ArrayInitLoopExpr *AILE) const
Return number of elements initialized in an ArrayInitLoopExpr.
unsigned getTargetAddressSpace(LangAS AS) const
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...
QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a non-unique reference to the type for a dependently-sized array of the specified element type...
void addTranslationUnitDecl()
CanQualType WCharTy
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.
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:940
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.
std::optional< CXXRecordDeclRelocationInfo > getRelocationInfoForCXXRecord(const CXXRecordDecl *) const
InlineVariableDefinitionKind getInlineVariableDefinitionKind(const VarDecl *VD) const
Determine whether a definition of this inline variable should be treated as a weak or strong definiti...
TemplateName getSubstTemplateTemplateParm(TemplateName replacement, Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex, bool Final) const
CanQualType getUIntMaxType() const
Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in <stdint.h>.
friend class DeclContext
uint16_t getPointerAuthVTablePointerDiscriminator(const CXXRecordDecl *RD)
Return the "other" discriminator used for the pointer auth schema used for vtable pointers in instanc...
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.
@ GE_Missing_type
Missing a type.
QualType adjustStringLiteralBaseType(QualType StrLTy) const
uint16_t getPointerAuthTypeDiscriminator(QualType T)
Return the "other" type-specific discriminator for the given type.
bool canonicalizeTemplateArguments(MutableArrayRef< TemplateArgument > Args) const
Canonicalize the given template argument list.
QualType getTypeOfExprType(Expr *E, TypeOfKind Kind) const
C23 feature and GCC extension.
CanQualType Char8Ty
QualType getSignedWCharType() const
Return the type of "signed wchar_t".
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
bool hasCvrSimilarType(QualType T1, QualType T2)
Determine if two types are similar, ignoring only CVR qualifiers.
TemplateName getDeducedTemplateName(TemplateName Underlying, DefaultArguments DefaultArgs) const
Represents a TemplateName which had some of its default arguments deduced.
ObjCImplementationDecl * getObjCImplementation(ObjCInterfaceDecl *D)
Get the implementation of the ObjCInterfaceDecl D, or nullptr if none exists.
CanQualType HalfTy
CanQualType UnsignedAccumTy
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.
const CXXRecordDecl * baseForVTableAuthentication(const CXXRecordDecl *ThisClass) const
Resolve the root record to be used to derive the vtable pointer authentication policy for the specifi...
QualType getVariableArrayDecayedType(QualType Ty) const
Returns a vla type where known sizes are replaced with [*].
void setCFConstantStringType(QualType T)
const SYCLKernelInfo * findSYCLKernelInfo(QualType T) const
Returns a pointer to the metadata generated from the corresponding SYCLkernel entry point if the prov...
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...
QualType getCommonSugaredType(QualType X, QualType Y, bool Unqualified=false) const
CanQualType OCLEventTy
void AddDeallocation(void(*Callback)(void *), void *Data) const
Add a deallocation callback that will be invoked when the ASTContext is destroyed.
AttrVec & getDeclAttrs(const Decl *D)
Retrieve the attributes for the given declaration.
CXXMethodVector::const_iterator overridden_cxx_method_iterator
RawComment * getRawCommentForDeclNoCacheImpl(const Decl *D, const SourceLocation RepresentativeLocForDecl, const std::map< unsigned, RawComment * > &CommentsInFile) const
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
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
void setIsDestroyingOperatorDelete(const FunctionDecl *FD, bool IsDestroying)
uint64_t getCharWidth() const
Return the size of the character type, in bits.
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.
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
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/...
CharUnits getAlignment() const
getAlignment - Get the record alignment in characters.
const CXXRecordDecl * getBaseSharingVBPtr() const
CharUnits getSize() const
getSize - Get the record size in characters.
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
CharUnits getDataSize() const
getDataSize() - Get the record data size, which is the record size without tail padding,...
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
CharUnits getNonVirtualSize() const
getNonVirtualSize - Get the non-virtual size (in chars) of an object, which is the size of the object...
CharUnits getUnadjustedAlignment() const
getUnadjustedAlignment - Get the record alignment in characters, before alignment adjustment.
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons.
Definition TypeBase.h:3489
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3508
Represents a loop initializing the elements of an array.
Definition Expr.h:5904
llvm::APInt getArraySize() const
Definition Expr.h:5926
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:5924
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition TypeBase.h:3890
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3720
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3734
Qualifiers getIndexTypeQualifiers() const
Definition TypeBase.h:3738
QualType getElementType() const
Definition TypeBase.h:3732
unsigned getIndexTypeCVRQualifiers() const
Definition TypeBase.h:3742
A structure for storing the information associated with a name that has been assumed to be a template...
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition Expr.h:6816
Expr * getPtr() const
Definition Expr.h:6847
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:8089
Attr - This represents one attribute.
Definition Attr.h:44
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8137
void Profile(llvm::FoldingSetNodeID &ID) const
Definition TypeBase.h:8154
unsigned getNumBits() const
Definition TypeBase.h:8149
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4634
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6560
Pointer to a block type.
Definition TypeBase.h:3540
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3557
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 TypeBase.h:3164
Kind getKind() const
Definition TypeBase.h:3212
StringRef getName(const PrintingPolicy &Policy) const
Definition Type.cpp:3363
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition Builtins.h:228
Implements C++ ABI-specific semantic analysis functions.
Definition CXXABI.h:29
virtual ~CXXABI()
Represents a C++ constructor within a class.
Definition DeclCXX.h:2604
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2225
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)
Definition DeclCXX.cpp:132
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:548
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition DeclCXX.h:1214
bool isDynamicClass() const
Definition DeclCXX.h:574
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1186
SplitQualType split() const
static CanQual< Type > CreateUnsafe(QualType Other)
QualType withConst() const
Retrieves a version of this type with const applied.
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
Qualifiers getQualifiers() const
Retrieve all qualifiers.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
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 TypeBase.h:3275
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3290
bool hasExplicitTemplateArgs() const
Whether or not template arguments were explicitly specified in the concept reference (they might not ...
Definition ASTConcept.h:205
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Definition ASTConcept.h:199
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3758
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition TypeBase.h:3854
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3814
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition TypeBase.h:3873
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3834
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4371
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4392
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4409
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4389
static constexpr bool isDimensionValid(size_t NumElements)
Returns true if NumElements is a valid matrix dimension.
Definition TypeBase.h:4400
Represents a sugar type with __counted_by or __sized_by annotations, including their _or_null variant...
Definition TypeBase.h:3436
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3472
Represents a pointer type decayed from an array or function type.
Definition TypeBase.h:3523
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
bool isFileContext() const
Definition DeclBase.h:2180
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition DeclBase.h:2125
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
void addDecl(Decl *D)
Add the declaration D into this context.
Decl::Kind getDeclKind() const
Definition DeclBase.h:2102
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1272
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
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:319
bool isModuleLocal() const
Whether this declaration was a local declaration to a C++20 named module.
T * getAttr() const
Definition DeclBase.h:573
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:524
void addAttr(Attr *A)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:593
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition DeclBase.cpp:538
bool isUnconditionallyVisible() const
Determine whether this declaration is definitely visible to name lookup, independent of whether the o...
Definition DeclBase.h:859
static Decl * castFromDeclContext(const DeclContext *)
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition DeclBase.cpp:286
bool isCanonicalDecl() const
Whether this particular Decl is a canonical one.
Definition DeclBase.h:984
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:842
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:251
ObjCDeclQualifier
ObjCDeclQualifier - 'Qualifiers' written next to the return and parameter types in method declaration...
Definition DeclBase.h:198
bool isInvalidDecl() const
Definition DeclBase.h:588
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:559
SourceLocation getLocation() const
Definition DeclBase.h:439
void setImplicit(bool I=true)
Definition DeclBase.h:594
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:448
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:431
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition DeclBase.cpp:360
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:918
bool hasAttr() const
Definition DeclBase.h:577
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:978
Kind getKind() const
Definition DeclBase.h:442
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.
The name of a declaration.
static int compare(DeclarationName LHS, DeclarationName RHS)
Represents a ValueDecl that came out of a declarator.
Definition Decl.h:779
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:808
TemplateName getUnderlying() const
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) const
DefaultArguments getDefaultArguments() const
Represents an extended address space qualifier where the input address space value is dependent.
Definition TypeBase.h:4059
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4081
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:8182
Represents an array type in C++ whose size is a value-dependent expression.
Definition TypeBase.h:4009
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4038
Represents an extended vector type where either the type or size is dependent.
Definition TypeBase.h:4099
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4124
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition TypeBase.h:4430
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4450
Represents a dependent template name that cannot be resolved prior to template instantiation.
void Profile(llvm::FoldingSetNodeID &ID) const
IdentifierOrOverloadedOperator getName() const
NestedNameSpecifier getQualifier() const
Return the nested name specifier that qualifies this name.
bool hasTemplateKeyword() const
Was this template name was preceeded by the template keyword?
Internal representation of canonical, dependent typeof(expr) types.
Definition TypeBase.h:6209
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:6214
Represents a vector type where either the type or size is dependent.
Definition TypeBase.h:4225
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4250
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:231
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition Diagnostic.h:904
Represents an enum.
Definition Decl.h:4004
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4213
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4227
EnumDecl * getDefinitionOrSelf() const
Definition Decl.h:4111
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4168
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition Decl.cpp:5033
This represents one expression.
Definition Expr.h:112
bool isIntegerConstantExpr(const ASTContext &Ctx) const
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3078
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:444
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4164
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:833
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition Expr.h:223
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3053
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:4001
QualType getType() const
Definition Expr.h:144
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition Expr.h:434
We can encode up to four bits in the low bits of a type pointer, but there are many more type qualifi...
Definition TypeBase.h:1717
void Profile(llvm::FoldingSetNodeID &ID) const
Definition TypeBase.h:1764
ExtVectorType - Extended vector type.
Definition TypeBase.h:4265
Declaration context for names declared as extern "C" in C++.
Definition Decl.h:246
static ExternCContextDecl * Create(const ASTContext &C, TranslationUnitDecl *TU)
Definition Decl.cpp:5416
Abstract interface for external sources of AST nodes.
virtual void CompleteRedeclChain(const Decl *D)
Gives the external AST source an opportunity to complete the redeclaration chain for a declaration.
Represents a member of a struct/union/class.
Definition Decl.h:3157
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3260
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4693
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3242
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3393
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
Definition Decl.cpp:4641
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:1999
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2686
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3703
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2918
bool isMSExternInline() const
The combination of the extern and inline keywords under MSVC forces the function to be required.
Definition Decl.cpp:3832
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3688
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4358
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition Decl.h:2409
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4106
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:4019
FunctionDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5232
static FunctionEffectSet getIntersection(FunctionEffectsRef LHS, FunctionEffectsRef RHS)
Definition Type.cpp:5641
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition Type.cpp:5679
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5064
ArrayRef< EffectConditionExpr > conditions() const
Definition TypeBase.h:5098
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition TypeBase.h:4842
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4858
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5264
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5768
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5571
unsigned getNumParams() const
Definition TypeBase.h:5542
QualType getParamType(unsigned i) const
Definition TypeBase.h:5544
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition Type.cpp:3956
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5577
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5668
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5553
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5549
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
Definition TypeBase.h:5737
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition TypeBase.h:5733
Declaration of a template function.
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4571
CallingConv getCC() const
Definition TypeBase.h:4630
unsigned getRegParm() const
Definition TypeBase.h:4623
bool getNoCallerSavedRegs() const
Definition TypeBase.h:4619
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4642
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition TypeBase.h:4486
ExtParameterInfo withIsNoEscape(bool NoEscape) const
Definition TypeBase.h:4526
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4460
ExtInfo getExtInfo() const
Definition TypeBase.h:4816
QualType getReturnType() const
Definition TypeBase.h:4800
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:57
unsigned getMultiVersionIndex() const
Definition GlobalDecl.h:125
CXXDtorType getDtorType() const
Definition GlobalDecl.h:113
const Decl * getDecl() const
Definition GlobalDecl.h:106
One of these records is kept for each identifier that is lexed.
unsigned getLength() const
Efficiently return the length of this identifier info.
StringRef getName() const
Return the actual identifier string.
Implements an efficient mapping from strings to IdentifierInfo nodes.
Describes a module import declaration, which makes the contents of the named module visible in the cu...
Definition Decl.h:5015
Represents a C array with an unspecified size.
Definition TypeBase.h:3907
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3924
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 TypeBase.h:3615
@ 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...
std::optional< TargetCXXABI::Kind > CXXABI
C++ ABI to compile with, if specified by the frontend through -fc++-abi=.
clang::ObjCRuntime ObjCRuntime
CoreFoundationABI CFRuntime
A global _GUID constant.
Definition DeclCXX.h:4392
static void Profile(llvm::FoldingSetNodeID &ID, Parts P)
Definition DeclCXX.h:4429
MSGuidDeclParts Parts
Definition DeclCXX.h:4394
Sugar type that represents a type that was qualified by a qualifier written as a macro invocation.
Definition TypeBase.h:6143
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
Definition Mangle.h:52
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 TypeBase.h:4349
static bool isValidElementType(QualType T)
Valid elements types are the following:
Definition TypeBase.h:4356
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3651
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3694
Provides information a specialization of a member of a class template, which may be a member function...
static MicrosoftMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
Describes a module or submodule.
Definition Module.h:144
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition Module.h:224
This represents a decl that may have a name.
Definition Decl.h:273
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:486
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:294
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition Decl.cpp:1095
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:339
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:316
bool isExternallyVisible() const
Definition Decl.h:432
Represent a C++ namespace.
Definition Decl.h:591
static NamespaceDecl * Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl, bool Nested)
Definition DeclCXX.cpp:3245
A C++ nested-name-specifier augmented with source location information.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NestedNameSpecifier getCanonical() const
Retrieves the "canonical" nested name specifier for a given nested name specifier.
CXXRecordDecl * getAsMicrosoftSuper() const
NamespaceAndPrefix getAsNamespaceAndPrefix() const
bool isCanonical() const
Whether this nested name specifier is canonical.
Kind
The kind of specifier that completes this nested name specifier.
@ MicrosoftSuper
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace-like entity, stored as a NamespaceBaseDecl*.
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, const 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:2329
ObjCCategoryImplDecl - An object of this class encapsulates a category @implementation declaration.
Definition DeclObjC.h:2545
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition DeclObjC.h:2597
Represents an ObjC class declaration.
Definition DeclObjC.h:1154
ObjCTypeParamList * getTypeParamList() const
Retrieve the type parameters of this class.
Definition DeclObjC.cpp:319
static ObjCInterfaceDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation atLoc, const IdentifierInfo *Id, ObjCTypeParamList *typeParamList, ObjCInterfaceDecl *PrevDecl, SourceLocation ClassLoc=SourceLocation(), bool isInternal=false)
bool hasDefinition() const
Determine whether this class has been defined.
Definition DeclObjC.h:1528
ivar_range ivars() const
Definition DeclObjC.h:1451
bool ClassImplementsProtocol(ObjCProtocolDecl *lProto, bool lookupCategory, bool RHSIsQualifiedID=false)
ClassImplementsProtocol - Checks that 'lProto' protocol has been implemented in IDecl class,...
StringRef getObjCRuntimeNameAsString() const
Produce a name to be used for class's metadata.
ObjCImplementationDecl * getImplementation() const
ObjCInterfaceDecl * getSuperClass() const
Definition DeclObjC.cpp:349
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:1810
known_extensions_range known_extensions() const
Definition DeclObjC.h:1762
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:7847
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
Definition Type.cpp:951
ObjCIvarDecl - Represents an ObjC instance variable.
Definition DeclObjC.h:1952
ObjCIvarDecl * getNextIvar()
Definition DeclObjC.h:1987
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 TypeBase.h:7903
bool isObjCQualifiedClassType() const
True if this is equivalent to 'Class.
Definition TypeBase.h:7984
const ObjCObjectPointerType * stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const
Strip off the Objective-C "kindof" type and (with it) any protocol qualifiers.
Definition Type.cpp:958
bool isObjCQualifiedIdType() const
True if this is equivalent to 'id.
Definition TypeBase.h:7978
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:8060
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:7940
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition TypeBase.h:7961
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:7915
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:7955
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:1840
qual_range quals() const
Definition TypeBase.h:8022
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition TypeBase.h:7967
Represents one property declaration in an Objective-C interface.
Definition DeclObjC.h:731
bool isReadOnly() const
isReadOnly - Return true iff the property has a setter.
Definition DeclObjC.h:838
static ObjCPropertyDecl * findPropertyDecl(const DeclContext *DC, const IdentifierInfo *propertyID, ObjCPropertyQueryKind queryKind)
Lookup a property by name in the specified DeclContext.
Definition DeclObjC.cpp:176
bool isOptional() const
Definition DeclObjC.h:916
SetterKind getSetterKind() const
getSetterKind - Return the method used for doing assignment in the property setter.
Definition DeclObjC.h:873
Selector getSetterName() const
Definition DeclObjC.h:893
QualType getType() const
Definition DeclObjC.h:804
Selector getGetterName() const
Definition DeclObjC.h:885
ObjCPropertyAttribute::Kind getPropertyAttributes() const
Definition DeclObjC.h:815
ObjCPropertyImplDecl - Represents implementation declaration of a property in a class or category imp...
Definition DeclObjC.h:2805
ObjCIvarDecl * getPropertyIvarDecl() const
Definition DeclObjC.h:2879
Represents an Objective-C protocol declaration.
Definition DeclObjC.h:2084
protocol_range protocols() const
Definition DeclObjC.h:2161
bool isGNUFamily() const
Is this runtime basically of the GNU family of runtimes?
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:623
Stores a list of Objective-C type parameters for a parameterized class or a category/extension thereo...
Definition DeclObjC.h:662
A structure for storing the information associated with an overloaded template name.
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition ExprCXX.h:4357
Sugar for parentheses used when specifying types.
Definition TypeBase.h:3302
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3316
void clear()
Clear parent maps.
Represents a parameter to a function.
Definition Decl.h:1789
ObjCDeclQualifier getObjCDeclQualifier() const
Definition Decl.h:1853
QualType getOriginalType() const
Definition Decl.cpp:2955
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:8120
Pointer-authentication qualifiers.
Definition TypeBase.h:152
static PointerAuthQualifier Create(unsigned Key, bool IsAddressDiscriminated, unsigned ExtraDiscriminator, PointerAuthenticationMode AuthenticationMode, bool IsIsaPointer, bool AuthenticatesNullValues)
Definition TypeBase.h:239
bool isEquivalent(PointerAuthQualifier Other) const
Definition TypeBase.h:301
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3328
QualType getPointeeType() const
Definition TypeBase.h:3338
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3343
PredefinedSugarKind Kind
Definition TypeBase.h:8196
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
A (possibly-)qualified type.
Definition TypeBase.h:937
bool hasAddressDiscriminatedPointerAuth() const
Definition TypeBase.h:1457
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8369
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:2867
Qualifiers::GC getObjCGCAttr() const
Returns gc attribute of this type.
Definition TypeBase.h:8416
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8374
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition TypeBase.h:1296
QualType withConst() const
Definition TypeBase.h:1159
bool hasLocalQualifiers() const
Determine whether this particular QualType instance has any qualifiers, without looking through any t...
Definition TypeBase.h:1064
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8285
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8411
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8325
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1438
QualType getCanonicalType() const
Definition TypeBase.h:8337
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8379
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition TypeBase.h:8306
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8358
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1545
bool isCanonical() const
Definition TypeBase.h:8342
const Type * getTypePtrOrNull() const
Definition TypeBase.h:8289
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1332
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:2990
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8317
Represents a template name as written in source code.
void Profile(llvm::FoldingSetNodeID &ID)
A qualifier set is used to build a set of qualifiers.
Definition TypeBase.h:8225
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8232
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
unsigned getCVRQualifiers() const
Definition TypeBase.h:488
void removeCVRQualifiers(unsigned mask)
Definition TypeBase.h:495
GC getObjCGCAttr() const
Definition TypeBase.h:519
void addAddressSpace(LangAS space)
Definition TypeBase.h:597
static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R)
Returns the common set of qualifiers while removing them from the given sets.
Definition TypeBase.h:384
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:361
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:354
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:350
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:364
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:367
void removeObjCLifetime()
Definition TypeBase.h:551
bool hasNonFastQualifiers() const
Return true if the set contains any qualifiers which require an ExtQuals node to be allocated.
Definition TypeBase.h:638
void addConsistentQualifiers(Qualifiers qs)
Add the qualifiers from the given set to this set, given that they don't conflict.
Definition TypeBase.h:689
void removeFastQualifiers(unsigned mask)
Definition TypeBase.h:624
bool hasUnaligned() const
Definition TypeBase.h:511
bool hasAddressSpace() const
Definition TypeBase.h:570
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B, const ASTContext &Ctx)
Returns true if address space A is equal to or a superset of B.
Definition TypeBase.h:708
unsigned getFastQualifiers() const
Definition TypeBase.h:619
void removeAddressSpace()
Definition TypeBase.h:596
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:603
bool hasObjCGCAttr() const
Definition TypeBase.h:518
uint64_t getAsOpaqueValue() const
Definition TypeBase.h:455
bool hasObjCLifetime() const
Definition TypeBase.h:544
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:545
bool empty() const
Definition TypeBase.h:647
void addObjCGCAttr(GC type)
Definition TypeBase.h:524
LangAS getAddressSpace() const
Definition TypeBase.h:571
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3633
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:4309
bool isLambda() const
Determine whether this record is a class describing a lambda function object.
Definition Decl.cpp:5125
bool hasFlexibleArrayMember() const
Definition Decl.h:4342
field_range fields() const
Definition Decl.h:4512
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition Decl.cpp:5111
RecordDecl * getMostRecentDecl()
Definition Decl.h:4335
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition Decl.cpp:5166
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4493
bool field_empty() const
Definition Decl.h:4520
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3571
QualType getPointeeType() const
Definition TypeBase.h:3589
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3597
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.
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.
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1801
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, ArrayRef< SourceLocation > Locs)
This is the "fully general" constructor that allows representation of strings formed from one or more...
Definition Expr.cpp:1184
A structure for storing an already-substituted template template parameter pack.
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.
A structure for storing the information associated with a substituted template template parameter.
void Profile(llvm::FoldingSetNodeID &ID)
TemplateTemplateParmDecl * getParameter() const
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3714
TagTypeKind TagKind
Definition Decl.h:3719
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition Decl.h:3945
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:4847
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:4840
bool isUnion() const
Definition Decl.h:3919
TagKind getTagKind() const
Definition Decl.h:3908
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Kind
The basic C++ ABI kind.
static Kind getKind(StringRef Name)
Exposes information about the current target.
Definition TargetInfo.h:226
TargetOptions & getTargetOpts() const
Retrieve the target options.
Definition TargetInfo.h:323
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
unsigned getMaxAtomicInlineWidth() const
Return the maximum width lock-free atomic operation which can be inlined given the supported features...
Definition TargetInfo.h:853
virtual LangAS getCUDABuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space.
virtual LangAS getOpenCLBuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space.
unsigned getDefaultAlignForAttributeAligned() const
Return the default alignment for attribute((aligned)) on this target, to be used if no alignment valu...
Definition TargetInfo.h:746
BuiltinVaListKind
The different kinds of __builtin_va_list types defined by the target implementation.
Definition TargetInfo.h:330
@ AArch64ABIBuiltinVaList
__builtin_va_list as defined by the AArch64 ABI http://infocenter.arm.com/help/topic/com....
Definition TargetInfo.h:339
@ PowerABIBuiltinVaList
__builtin_va_list as defined by the Power ABI: https://www.power.org /resources/downloads/Power-Arch-...
Definition TargetInfo.h:344
@ AAPCSABIBuiltinVaList
__builtin_va_list as defined by ARM AAPCS ABI http://infocenter.arm.com
Definition TargetInfo.h:353
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition TargetInfo.h:332
@ VoidPtrBuiltinVaList
typedef void* __builtin_va_list;
Definition TargetInfo.h:335
@ X86_64ABIBuiltinVaList
__builtin_va_list as defined by the x86-64 ABI: http://refspecs.linuxbase.org/elf/x86_64-abi-0....
Definition TargetInfo.h:348
virtual uint64_t getNullPointerValue(LangAS AddrSpace) const
Get integer value for null pointer.
Definition TargetInfo.h:502
static bool isTypeSigned(IntType T)
Returns true if the type is signed; false otherwise.
IntType getPtrDiffType(LangAS AddrSpace) const
Definition TargetInfo.h:404
IntType getSizeType() const
Definition TargetInfo.h:385
FloatModeKind getRealTypeByWidth(unsigned BitWidth, FloatModeKind ExplicitType) const
Return floating point type with specified width.
virtual IntType getIntTypeByWidth(unsigned BitWidth, bool IsSigned) const
Return integer type with specified width.
unsigned getMaxAlignedAttribute() const
Get the maximum alignment in bits for a static variable with aligned attribute.
Definition TargetInfo.h:970
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:754
unsigned getTargetAddressSpace(LangAS AS) const
IntType getSignedSizeType() const
Definition TargetInfo.h:386
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
bool useAddressSpaceMapMangling() const
Specify if mangling based on address space map should be used or not for language specific address sp...
llvm::StringMap< bool > FeatureMap
The map of which features have been enabled disabled based on the command line.
A convenient class for passing around template argument information.
ArrayRef< TemplateArgumentLoc > arguments() const
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Location wrapper for a TemplateArgument.
Represents a template argument.
ArrayRef< TemplateArgument > getPackAsArray() const
Return the array of arguments in this template argument pack.
QualType getStructuralValueType() const
Get the type of a StructuralValue.
QualType getParamTypeForDecl() const
Expr * getAsExpr() const
Retrieve the template argument as an expression.
UnsignedOrNone 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.
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
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.
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.
bool getIsDefaulted() const
If returns 'true', this TemplateArgument corresponds to a default template parameter.
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
ArrayRef< TemplateArgument > pack_elements() const
Iterator range referencing all of the elements of a template argument pack.
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
@ Template
The template argument is a template name that was provided for a template template parameter.
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
@ Pack
The template argument is actually a parameter pack.
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
@ Type
The template argument is a type.
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
ArgKind getKind() const
Return the kind of stored template argument.
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion,...
const APValue & getAsStructuralValue() const
Get the value of a StructuralValue.
The base class of all kinds of template declarations (e.g., class, function, etc.).
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
DeducedTemplateStorage * getAsDeducedTemplateName() const
Retrieve the deduced template info, if any.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
std::optional< TemplateName > desugar(bool IgnoreDeduced) const
OverloadedTemplateStorage * getAsOverloadedTemplate() const
Retrieve the underlying, overloaded function template declarations that this template name refers to,...
AssumedTemplateStorage * getAsAssumedTemplateName() const
Retrieve information on a name that has been assumed to be a template-name in order to permit a call ...
NameKind getKind() const
void * getAsVoidPointer() const
Retrieve the template name as a void pointer.
@ UsingTemplate
A template name that refers to a template declaration found through a specific using shadow declarati...
@ OverloadedTemplate
A set of overloaded template declarations.
@ Template
A single template declaration.
@ DependentTemplate
A dependent template name that has not been resolved to a template (or set of templates).
@ SubstTemplateTemplateParm
A template template parameter that has been substituted for some other template name.
@ SubstTemplateTemplateParmPack
A template template parameter pack that has been substituted for a template template argument pack,...
@ DeducedTemplate
A template name that refers to another TemplateName with deduced default arguments.
@ QualifiedTemplate
A qualified template name, where the qualification is kept to describe the source code as written.
@ AssumedTemplate
An unqualified-id that has been assumed to name a function template that will be found by ADL.
UsingShadowDecl * getAsUsingShadowDecl() const
Retrieve the using shadow declaration through which the underlying template declaration is introduced...
SubstTemplateTemplateParmPackStorage * getAsSubstTemplateTemplateParmPack() const
Retrieve the substituted template template parameter pack, if known.
SubstTemplateTemplateParmStorage * getAsSubstTemplateTemplateParm() const
Retrieve the substituted template template parameter, if known.
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.
NamedDecl * getParam(unsigned Idx)
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.
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
ArrayRef< NamedDecl * > asArray()
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
TemplateNameKind templateParameterKind() const
unsigned getPosition() const
Get the position of the template parameter within its parameter list.
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, bool ParameterPack, IdentifierInfo *Id, TemplateNameKind ParameterKind, bool Typename, TemplateParameterList *Params)
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.
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, UnsignedOrNone NumExpanded=std::nullopt)
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition ASTConcept.h:223
Expr * getImmediatelyDeclaredConstraint() const
Get the immediately-declared constraint expression introduced by this type-constraint,...
Definition ASTConcept.h:240
TemplateDecl * getNamedConcept() const
Definition ASTConcept.h:250
ConceptReference * getConceptReference() const
Definition ASTConcept.h:244
Represents a declaration of a type.
Definition Decl.h:3510
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:95
void initialize(ASTContext &Context, SourceLocation Loc) const
Initializes this to state that every location in this type is the given location.
Definition TypeLoc.h:216
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition TypeBase.h:6175
A container of type source information.
Definition TypeBase.h:8256
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:272
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isBlockPointerType() const
Definition TypeBase.h:8542
bool isVoidType() const
Definition TypeBase.h:8878
bool isObjCBuiltinType() const
Definition TypeBase.h:8742
QualType getRVVEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an RVV builtin type.
Definition Type.cpp:2678
bool isIncompleteArrayType() const
Definition TypeBase.h:8629
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2205
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isConstantArrayType() const
Definition TypeBase.h:8625
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2426
bool isArrayType() const
Definition TypeBase.h:8621
bool isCharType() const
Definition Type.cpp:2132
bool isPointerType() const
Definition TypeBase.h:8522
bool isArrayParameterType() const
Definition TypeBase.h:8637
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8922
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9168
bool isSignedFixedPointType() const
Return true if this is a fixed point type that is signed according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8962
bool isEnumeralType() const
Definition TypeBase.h:8653
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8712
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:752
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:8996
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2899
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2790
bool isBitIntType() const
Definition TypeBase.h:8787
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8645
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2782
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8934
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8950
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2405
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3119
@ PtrdiffT
The "ptrdiff_t" type.
Definition TypeBase.h:2281
@ SizeT
The "size_t" type.
Definition TypeBase.h:2275
@ SignedSizeT
The signed integer type corresponding to "size_t".
Definition TypeBase.h:2278
bool isObjCIdType() const
Definition TypeBase.h:8724
bool isUnsaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8958
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9154
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2436
bool isFunctionType() const
Definition TypeBase.h:8518
bool isObjCObjectPointerType() const
Definition TypeBase.h:8691
bool isUnsignedFixedPointType() const
Return true if this is a fixed point type that is unsigned according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8976
bool isVectorType() const
Definition TypeBase.h:8661
bool isObjCClassType() const
Definition TypeBase.h:8730
bool isRVVVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'riscv_rvv_vector_bits' type attribute,...
Definition Type.cpp:2660
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2595
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2921
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:2253
bool isAnyPointerType() const
Definition TypeBase.h:8530
TypeClass getTypeClass() const
Definition TypeBase.h:2385
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2411
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9101
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:653
bool isNullPtrType() const
Definition TypeBase.h:8915
bool isRecordType() const
Definition TypeBase.h:8649
bool isObjCRetainableType() const
Definition Type.cpp:5291
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5022
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3664
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5629
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3559
QualType getUnderlyingType() const
Definition Decl.h:3614
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType Underlying)
Definition TypeBase.h:6119
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition DeclCXX.h:4449
static void Profile(llvm::FoldingSetNodeID &ID, QualType Ty, const APValue &APVal)
Definition DeclCXX.h:4477
The iterator over UnresolvedSets.
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition TypeBase.h:5980
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UnresolvedUsingTypenameDecl *D)
Definition TypeBase.h:6017
Represents a dependent using declaration which was marked with typename.
Definition DeclCXX.h:4031
UnresolvedUsingTypenameDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this declaration.
Definition DeclCXX.h:4096
Represents a C++ using-enum-declaration.
Definition DeclCXX.h:3786
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3393
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3457
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition DeclCXX.cpp:3358
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UsingShadowDecl *D, QualType UnderlyingType)
Definition TypeBase.h:6057
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:711
void setType(QualType newType)
Definition Decl.h:723
QualType getType() const
Definition Decl.h:722
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5449
void clear()
Definition Value.cpp:216
Represents a variable declaration or definition.
Definition Decl.h:925
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2810
bool hasInit() const
Definition Decl.cpp:2398
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:2461
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1282
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1207
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition Decl.cpp:2772
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1550
@ DeclarationOnly
This declaration is only a declaration.
Definition Decl.h:1294
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition Decl.cpp:2375
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:2779
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:3964
Expr * getSizeExpr() const
Definition TypeBase.h:3978
Represents a GCC generic vector type.
Definition TypeBase.h:4173
unsigned getNumElements() const
Definition TypeBase.h:4188
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4197
VectorKind getVectorKind() const
Definition TypeBase.h:4193
QualType getElementType() const
Definition TypeBase.h:4187
A full comment attached to a declaration, contains block content.
Definition Comment.h:1104
ArrayRef< BlockContentComment * > getBlocks() const
Definition Comment.h:1142
const DeclInfo * getDeclInfo() const LLVM_READONLY
Definition Comment.h:1136
const Decl * getDecl() const LLVM_READONLY
Definition Comment.h:1132
Holds all information required to evaluate constexpr code in a module.
Definition Context.h:41
Defines the Linkage enumeration and various utility functions.
Defines the clang::TargetInfo interface.
Definition SPIR.cpp:47
mlir::Type getBaseType(mlir::Value varPtr)
const AstTypeMatcher< TagType > tagType
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
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus17
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 TypeBase.h:1792
OpenCLTypeKind
OpenCL type kinds.
Definition TargetInfo.h:212
@ OCLTK_ReserveID
Definition TargetInfo.h:219
@ OCLTK_Sampler
Definition TargetInfo.h:220
@ OCLTK_Pipe
Definition TargetInfo.h:217
@ OCLTK_ClkEvent
Definition TargetInfo.h:214
@ OCLTK_Event
Definition TargetInfo.h:215
@ OCLTK_Default
Definition TargetInfo.h:213
@ OCLTK_Queue
Definition TargetInfo.h:218
FunctionType::ExtInfo getFunctionExtInfo(const Type &t)
Definition TypeBase.h:8420
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
NullabilityKind
Describes the nullability of a particular type.
Definition Specifiers.h:348
@ Nullable
Values of this type can be null.
Definition Specifiers.h:352
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
Definition Specifiers.h:357
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:350
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:272
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
std::pair< FileID, unsigned > FileIDAndOffset
CXXABI * CreateMicrosoftCXXABI(ASTContext &Ctx)
@ Vector
'vector' clause, allowed on 'loop', Combined, and 'routine' directives.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
TypeOfKind
The kind of 'typeof' expression we're after.
Definition TypeBase.h:918
@ AS_public
Definition Specifiers.h:124
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ SC_Register
Definition Specifiers.h:257
@ SC_Static
Definition Specifiers.h:252
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.
Definition Linkage.h:58
@ Result
The result type of a method or function.
Definition TypeBase.h:905
@ TypeAlignment
Definition TypeBase.h:76
ArraySizeModifier
Capture whether this is a normal array (e.g.
Definition TypeBase.h:3717
const FunctionProtoType * T
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
@ Template
We are parsing a template declaration.
Definition Parser.h:81
@ Interface
The "__interface" keyword.
Definition TypeBase.h:5893
@ Struct
The "struct" keyword.
Definition TypeBase.h:5890
@ Class
The "class" keyword.
Definition TypeBase.h:5899
constexpr uint16_t SelPointerConstantDiscriminator
Constant discriminator to be used with objective-c sel pointers.
bool isDiscardableGVALinkage(GVALinkage L)
Definition Linkage.h:80
BuiltinTemplateKind
Kinds of BuiltinTemplateDecl.
Definition Builtins.h:462
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:560
LangAS
Defines the address space values used by the address space qualifier of QualType.
TranslationUnitKind
Describes the kind of translation unit being processed.
FloatModeKind
Definition TargetInfo.h:75
bool isPtrSizeAddressSpace(LangAS AS)
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:139
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1288
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:202
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:191
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:278
@ CC_M68kRTD
Definition Specifiers.h:299
@ CC_X86RegCall
Definition Specifiers.h:287
@ CC_X86VectorCall
Definition Specifiers.h:283
@ CC_X86StdCall
Definition Specifiers.h:280
@ CC_X86FastCall
Definition Specifiers.h:281
@ Invariant
The parameter is invariant: must match exactly.
Definition DeclObjC.h:555
@ Contravariant
The parameter is contravariant, e.g., X<T> is a subtype of X when the type parameter is covariant and...
Definition DeclObjC.h:563
@ Covariant
The parameter is covariant, e.g., X<T> is a subtype of X when the type parameter is covariant and T i...
Definition DeclObjC.h:559
@ AltiVecBool
is AltiVec 'vector bool ...'
Definition TypeBase.h:4143
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
Definition TypeBase.h:4152
@ AltiVecPixel
is AltiVec 'vector Pixel'
Definition TypeBase.h:4140
@ Generic
not a target-specific vector type
Definition TypeBase.h:4134
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
Definition TypeBase.h:4158
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
Definition TypeBase.h:4161
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
Definition TypeBase.h:4155
U cast(CodeGen::Address addr)
Definition Address.h:327
LangAS getLangASFromTargetAS(unsigned TargetAS)
AlignRequirementKind
Definition ASTContext.h:144
@ None
The alignment was not explicit in code.
Definition ASTContext.h:146
@ RequiredByEnum
The alignment comes from an alignment attribute on a enum type.
Definition ASTContext.h:155
@ RequiredByTypedef
The alignment comes from an alignment attribute on a typedef.
Definition ASTContext.h:149
@ RequiredByRecord
The alignment comes from an alignment attribute on a record type.
Definition ASTContext.h:152
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition TypeBase.h:5863
@ Interface
The "__interface" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5868
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5884
@ Struct
The "struct" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5865
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5874
@ Union
The "union" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5871
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5877
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:5881
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
@ EST_DependentNoexcept
noexcept(expression), value-dependent
@ 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)
unsigned long uint64_t
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
unsigned NumTemplateArgs
The number of template arguments in TemplateArgs.
const Expr * ConstraintExpr
Definition Decl.h:87
UnsignedOrNone ArgPackSubstIndex
Definition Decl.h:88
Copy initialization expr of a __block variable and a boolean flag that indicates whether the expressi...
Definition Expr.h:6606
Expr * getCopyExpr() const
Definition Expr.h:6613
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
ArrayRef< TemplateArgument > Args
Holds information about the various types of exception specification.
Definition TypeBase.h:5321
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5323
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition TypeBase.h:5326
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition TypeBase.h:5329
Extra information about a function prototype.
Definition TypeBase.h:5349
bool requiresFunctionProtoTypeArmAttributes() const
Definition TypeBase.h:5395
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5354
bool requiresFunctionProtoTypeExtraAttributeInfo() const
Definition TypeBase.h:5399
bool requiresFunctionProtoTypeExtraBitfields() const
Definition TypeBase.h:5388
const IdentifierInfo * getIdentifier() const
Returns the identifier to which this template name refers.
OverloadedOperatorKind getOperator() const
Return the overloaded operator to which this template name refers.
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition Type.cpp:3259
A lazy value (of type T) that is within an AST node of type Owner, where the value might change in la...
Contains information gathered from parsing the contents of TargetAttr.
Definition TargetInfo.h:60
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition TypeBase.h:870
const Type * Ty
The locally-unqualified type.
Definition TypeBase.h:872
Qualifiers Quals
The local qualifiers.
Definition TypeBase.h:875
llvm::DenseSet< std::tuple< Decl *, Decl *, int > > NonEquivalentDeclSet
Store declaration pairs already found to be non-equivalent.
bool IsEquivalent(Decl *D1, Decl *D2)
Determine whether the two declarations are structurally equivalent.
A this pointer adjustment.
Definition Thunk.h:92
IntType
===-— Target Data Type Query Methods ----------------------------—===//
Definition TargetInfo.h:146
AlignRequirementKind AlignRequirement
Definition ASTContext.h:175
bool isAlignRequired()
Definition ASTContext.h:167
AlignRequirementKind AlignRequirement
Definition ASTContext.h:161
Information about the declaration, useful to clients of FullComment.
Definition Comment.h:983
const TemplateParameterList * TemplateParameters
Template parameters that can be referenced by \tparam if CommentDecl is a template (IsTemplateDecl or...
Definition Comment.h:1009
const Decl * CommentDecl
Declaration the comment is actually attached to (in the source).
Definition Comment.h:986
static bool isEqual(const FoldingSetNodeID &LHS, const FoldingSetNodeID &RHS)
static unsigned getHashValue(const FoldingSetNodeID &Val)