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.
188 if (isa<TemplateTypeParmDecl>(D) ||
189 isa<NonTypeTemplateParmDecl>(D) ||
190 isa<TemplateTemplateParmDecl>(D))
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;
201 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
202 isa<ObjCPropertyDecl>(D) || isa<RedeclarableTemplateDecl>(D) ||
203 isa<ClassTemplateSpecializationDecl>(D) ||
204 // Allow association with Y across {} in `typedef struct X {} Y`.
205 isa<TypedefDecl>(D))
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() &&
265 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
266 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
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
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 *>(
403 cast<ClassTemplatePartialSpecializationDecl *>(PU));
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
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
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
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);
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;
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) {
638 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
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
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(
828 cast<TemplateTemplateParmDecl>(*P)));
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,
938 Builtin::Context &builtins, TranslationUnitKind TUKind)
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 *,
974 const ASTRecordLayout *>::iterator
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
1015 ExternalSource = std::move(Source);
1016}
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";
1074 }
1075
1076 BumpAlloc.PrintStats();
1077}
1078
1080 bool NotifyListeners) {
1081 if (NotifyListeners)
1082 if (auto *Listener = getASTMutationListener();
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
1214 const IdentifierInfo *II) const {
1215 auto *BuiltinTemplate =
1217 BuiltinTemplate->setImplicit();
1219
1220 return BuiltinTemplate;
1221}
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 {
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();
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) ||
1590 isa<UnresolvedUsingValueDecl>(Pattern) ||
1591 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1592 "pattern decl is not a using decl");
1593 assert((isa<UsingDecl>(Inst) ||
1594 isa<UnresolvedUsingValueDecl>(Inst) ||
1595 isa<UnresolvedUsingTypenameDecl>(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
1643 return overridden_methods(Method).begin();
1644}
1645
1648 return overridden_methods(Method).end();
1649}
1650
1651unsigned
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) {
1863 if (isa<VariableArrayType>(arrayType))
1864 Align = std::max(Align, Target->getLargeArrayAlign());
1865 else if (isa<ConstantArrayType>(arrayType) &&
1866 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
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() ||
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
1975 return getTypeInfoInChars(T.getTypePtr());
1976}
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
2018}
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>()
2501 break;
2502 }
2503
2504 case Type::SubstTemplateTypeParm:
2505 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
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(
2521 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
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.
2651 return getTypeInfoInChars(T).Width;
2652}
2654 return getTypeInfoInChars(T).Width;
2655}
2656
2657/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2658/// characters. This method does not work on incomplete types.
2661}
2664}
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.
2671}
2674}
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
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.
2735}
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.
2748 const VarDecl *VD) const {
2750}
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();
2775 const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext());
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";
3359 cast<ReferenceType>(T)->getPointeeType());
3360 return;
3361 case Type::RValueReference:
3362 OS << "O";
3364 cast<ReferenceType>(T)->getPointeeType());
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)
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
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
3813 QualType U) const {
3814 return hasSameType(T, U) ||
3815 (getLangOpts().CPlusPlus17 &&
3818}
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
3838 return hasSameType(T, U) ||
3841}
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
3853 QualType U) const {
3856}
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::DependentTemplateSpecialization:
4290 case Type::TemplateTypeParm:
4291 case Type::SubstTemplateTypeParmPack:
4292 case Type::SubstBuiltinTemplatePack:
4293 case Type::Auto:
4294 case Type::DeducedTemplateSpecialization:
4295 case Type::PackExpansion:
4296 case Type::PackIndexing:
4297 case Type::BitInt:
4298 case Type::DependentBitInt:
4299 case Type::ArrayParameter:
4300 case Type::HLSLAttributedResource:
4301 case Type::HLSLInlineSpirv:
4302 llvm_unreachable("type should never be variably-modified");
4303
4304 // These types can be variably-modified but should never need to
4305 // further decay.
4306 case Type::FunctionNoProto:
4307 case Type::FunctionProto:
4308 case Type::BlockPointer:
4309 case Type::MemberPointer:
4310 case Type::Pipe:
4311 return type;
4312
4313 // These types can be variably-modified. All these modifications
4314 // preserve structure except as noted by comments.
4315 // TODO: if we ever care about optimizing VLAs, there are no-op
4316 // optimizations available here.
4317 case Type::Pointer:
4319 cast<PointerType>(ty)->getPointeeType()));
4320 break;
4321
4322 case Type::LValueReference: {
4323 const auto *lv = cast<LValueReferenceType>(ty);
4324 result = getLValueReferenceType(
4325 getVariableArrayDecayedType(lv->getPointeeType()),
4326 lv->isSpelledAsLValue());
4327 break;
4328 }
4329
4330 case Type::RValueReference: {
4331 const auto *lv = cast<RValueReferenceType>(ty);
4332 result = getRValueReferenceType(
4333 getVariableArrayDecayedType(lv->getPointeeType()));
4334 break;
4335 }
4336
4337 case Type::Atomic: {
4338 const auto *at = cast<AtomicType>(ty);
4339 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
4340 break;
4341 }
4342
4343 case Type::ConstantArray: {
4344 const auto *cat = cast<ConstantArrayType>(ty);
4345 result = getConstantArrayType(
4346 getVariableArrayDecayedType(cat->getElementType()),
4347 cat->getSize(),
4348 cat->getSizeExpr(),
4349 cat->getSizeModifier(),
4350 cat->getIndexTypeCVRQualifiers());
4351 break;
4352 }
4353
4354 case Type::DependentSizedArray: {
4355 const auto *dat = cast<DependentSizedArrayType>(ty);
4357 getVariableArrayDecayedType(dat->getElementType()), dat->getSizeExpr(),
4358 dat->getSizeModifier(), dat->getIndexTypeCVRQualifiers());
4359 break;
4360 }
4361
4362 // Turn incomplete types into [*] types.
4363 case Type::IncompleteArray: {
4364 const auto *iat = cast<IncompleteArrayType>(ty);
4365 result =
4367 /*size*/ nullptr, ArraySizeModifier::Normal,
4368 iat->getIndexTypeCVRQualifiers());
4369 break;
4370 }
4371
4372 // Turn VLA types into [*] types.
4373 case Type::VariableArray: {
4374 const auto *vat = cast<VariableArrayType>(ty);
4375 result =
4377 /*size*/ nullptr, ArraySizeModifier::Star,
4378 vat->getIndexTypeCVRQualifiers());
4379 break;
4380 }
4381 }
4382
4383 // Apply the top-level qualifiers from the original.
4384 return getQualifiedType(result, split.Quals);
4385}
4386
4387/// getVariableArrayType - Returns a non-unique reference to the type for a
4388/// variable array of the specified element type.
4391 unsigned IndexTypeQuals) const {
4392 // Since we don't unique expressions, it isn't possible to unique VLA's
4393 // that have an expression provided for their size.
4394 QualType Canon;
4395
4396 // Be sure to pull qualifiers off the element type.
4397 // FIXME: Check below should look for qualifiers behind sugar.
4398 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
4399 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4400 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
4401 IndexTypeQuals);
4402 Canon = getQualifiedType(Canon, canonSplit.Quals);
4403 }
4404
4405 auto *New = new (*this, alignof(VariableArrayType))
4406 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals);
4407
4408 VariableArrayTypes.push_back(New);
4409 Types.push_back(New);
4410 return QualType(New, 0);
4411}
4412
4413/// getDependentSizedArrayType - Returns a non-unique reference to
4414/// the type for a dependently-sized array of the specified element
4415/// type.
4419 unsigned elementTypeQuals) const {
4420 assert((!numElements || numElements->isTypeDependent() ||
4421 numElements->isValueDependent()) &&
4422 "Size must be type- or value-dependent!");
4423
4424 SplitQualType canonElementType = getCanonicalType(elementType).split();
4425
4426 void *insertPos = nullptr;
4427 llvm::FoldingSetNodeID ID;
4429 ID, *this, numElements ? QualType(canonElementType.Ty, 0) : elementType,
4430 ASM, elementTypeQuals, numElements);
4431
4432 // Look for an existing type with these properties.
4433 DependentSizedArrayType *canonTy =
4434 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4435
4436 // Dependently-sized array types that do not have a specified number
4437 // of elements will have their sizes deduced from a dependent
4438 // initializer.
4439 if (!numElements) {
4440 if (canonTy)
4441 return QualType(canonTy, 0);
4442
4443 auto *newType = new (*this, alignof(DependentSizedArrayType))
4444 DependentSizedArrayType(elementType, QualType(), numElements, ASM,
4445 elementTypeQuals);
4446 DependentSizedArrayTypes.InsertNode(newType, insertPos);
4447 Types.push_back(newType);
4448 return QualType(newType, 0);
4449 }
4450
4451 // If we don't have one, build one.
4452 if (!canonTy) {
4453 canonTy = new (*this, alignof(DependentSizedArrayType))
4454 DependentSizedArrayType(QualType(canonElementType.Ty, 0), QualType(),
4455 numElements, ASM, elementTypeQuals);
4456 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
4457 Types.push_back(canonTy);
4458 }
4459
4460 // Apply qualifiers from the element type to the array.
4461 QualType canon = getQualifiedType(QualType(canonTy,0),
4462 canonElementType.Quals);
4463
4464 // If we didn't need extra canonicalization for the element type or the size
4465 // expression, then just use that as our result.
4466 if (QualType(canonElementType.Ty, 0) == elementType &&
4467 canonTy->getSizeExpr() == numElements)
4468 return canon;
4469
4470 // Otherwise, we need to build a type which follows the spelling
4471 // of the element type.
4472 auto *sugaredType = new (*this, alignof(DependentSizedArrayType))
4473 DependentSizedArrayType(elementType, canon, numElements, ASM,
4474 elementTypeQuals);
4475 Types.push_back(sugaredType);
4476 return QualType(sugaredType, 0);
4477}
4478
4481 unsigned elementTypeQuals) const {
4482 llvm::FoldingSetNodeID ID;
4483 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
4484
4485 void *insertPos = nullptr;
4486 if (IncompleteArrayType *iat =
4487 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
4488 return QualType(iat, 0);
4489
4490 // If the element type isn't canonical, this won't be a canonical type
4491 // either, so fill in the canonical type field. We also have to pull
4492 // qualifiers off the element type.
4493 QualType canon;
4494
4495 // FIXME: Check below should look for qualifiers behind sugar.
4496 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
4497 SplitQualType canonSplit = getCanonicalType(elementType).split();
4498 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
4499 ASM, elementTypeQuals);
4500 canon = getQualifiedType(canon, canonSplit.Quals);
4501
4502 // Get the new insert position for the node we care about.
4503 IncompleteArrayType *existing =
4504 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4505 assert(!existing && "Shouldn't be in the map!"); (void) existing;
4506 }
4507
4508 auto *newType = new (*this, alignof(IncompleteArrayType))
4509 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
4510
4511 IncompleteArrayTypes.InsertNode(newType, insertPos);
4512 Types.push_back(newType);
4513 return QualType(newType, 0);
4514}
4515
4518#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
4519 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
4520 NUMVECTORS};
4521
4522#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
4523 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
4524
4525 switch (Ty->getKind()) {
4526 default:
4527 llvm_unreachable("Unsupported builtin vector type");
4528
4529#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4530 ElBits, NF, IsSigned) \
4531 case BuiltinType::Id: \
4532 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4533 llvm::ElementCount::getScalable(NumEls), NF};
4534#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4535 ElBits, NF) \
4536 case BuiltinType::Id: \
4537 return {ElBits == 16 ? HalfTy : (ElBits == 32 ? FloatTy : DoubleTy), \
4538 llvm::ElementCount::getScalable(NumEls), NF};
4539#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4540 ElBits, NF) \
4541 case BuiltinType::Id: \
4542 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4543#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4544 ElBits, NF) \
4545 case BuiltinType::Id: \
4546 return {MFloat8Ty, llvm::ElementCount::getScalable(NumEls), NF};
4547#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4548 case BuiltinType::Id: \
4549 return {BoolTy, llvm::ElementCount::getScalable(NumEls), NF};
4550#include "clang/Basic/AArch64ACLETypes.def"
4551
4552#define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
4553 IsSigned) \
4554 case BuiltinType::Id: \
4555 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4556 llvm::ElementCount::getScalable(NumEls), NF};
4557#define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4558 case BuiltinType::Id: \
4559 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
4560 llvm::ElementCount::getScalable(NumEls), NF};
4561#define RVV_VECTOR_TYPE_BFLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4562 case BuiltinType::Id: \
4563 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4564#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4565 case BuiltinType::Id: \
4566 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
4567#include "clang/Basic/RISCVVTypes.def"
4568 }
4569}
4570
4571/// getExternrefType - Return a WebAssembly externref type, which represents an
4572/// opaque reference to a host value.
4574 if (Target->getTriple().isWasm() && Target->hasFeature("reference-types")) {
4575#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
4576 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
4577 return SingletonId;
4578#include "clang/Basic/WebAssemblyReferenceTypes.def"
4579 }
4580 llvm_unreachable(
4581 "shouldn't try to generate type externref outside WebAssembly target");
4582}
4583
4584/// getScalableVectorType - Return the unique reference to a scalable vector
4585/// type of the specified element type and size. VectorType must be a built-in
4586/// type.
4588 unsigned NumFields) const {
4589 if (Target->hasAArch64ACLETypes()) {
4590 uint64_t EltTySize = getTypeSize(EltTy);
4591
4592#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4593 ElBits, NF, IsSigned) \
4594 if (EltTy->hasIntegerRepresentation() && !EltTy->isBooleanType() && \
4595 EltTy->hasSignedIntegerRepresentation() == IsSigned && \
4596 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4597 return SingletonId; \
4598 }
4599#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4600 ElBits, NF) \
4601 if (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4602 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4603 return SingletonId; \
4604 }
4605#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4606 ElBits, NF) \
4607 if (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4608 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4609 return SingletonId; \
4610 }
4611#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4612 ElBits, NF) \
4613 if (EltTy->isMFloat8Type() && EltTySize == ElBits && \
4614 NumElts == (NumEls * NF) && NumFields == 1) { \
4615 return SingletonId; \
4616 }
4617#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4618 if (EltTy->isBooleanType() && NumElts == (NumEls * NF) && NumFields == 1) \
4619 return SingletonId;
4620#include "clang/Basic/AArch64ACLETypes.def"
4621 } else if (Target->hasRISCVVTypes()) {
4622 uint64_t EltTySize = getTypeSize(EltTy);
4623#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
4624 IsFP, IsBF) \
4625 if (!EltTy->isBooleanType() && \
4626 ((EltTy->hasIntegerRepresentation() && \
4627 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4628 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4629 IsFP && !IsBF) || \
4630 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4631 IsBF && !IsFP)) && \
4632 EltTySize == ElBits && NumElts == NumEls && NumFields == NF) \
4633 return SingletonId;
4634#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4635 if (EltTy->isBooleanType() && NumElts == NumEls) \
4636 return SingletonId;
4637#include "clang/Basic/RISCVVTypes.def"
4638 }
4639 return QualType();
4640}
4641
4642/// getVectorType - Return the unique reference to a vector type of
4643/// the specified element type and size. VectorType must be a built-in type.
4645 VectorKind VecKind) const {
4646 assert(vecType->isBuiltinType() ||
4647 (vecType->isBitIntType() &&
4648 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4649 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4650
4651 // Check if we've already instantiated a vector of this type.
4652 llvm::FoldingSetNodeID ID;
4653 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
4654
4655 void *InsertPos = nullptr;
4656 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4657 return QualType(VTP, 0);
4658
4659 // If the element type isn't canonical, this won't be a canonical type either,
4660 // so fill in the canonical type field.
4661 QualType Canonical;
4662 if (!vecType.isCanonical()) {
4663 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
4664
4665 // Get the new insert position for the node we care about.
4666 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4667 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4668 }
4669 auto *New = new (*this, alignof(VectorType))
4670 VectorType(vecType, NumElts, Canonical, VecKind);
4671 VectorTypes.InsertNode(New, InsertPos);
4672 Types.push_back(New);
4673 return QualType(New, 0);
4674}
4675
4677 SourceLocation AttrLoc,
4678 VectorKind VecKind) const {
4679 llvm::FoldingSetNodeID ID;
4680 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
4681 VecKind);
4682 void *InsertPos = nullptr;
4683 DependentVectorType *Canon =
4684 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4686
4687 if (Canon) {
4688 New = new (*this, alignof(DependentVectorType)) DependentVectorType(
4689 VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4690 } else {
4691 QualType CanonVecTy = getCanonicalType(VecType);
4692 if (CanonVecTy == VecType) {
4693 New = new (*this, alignof(DependentVectorType))
4694 DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4695
4696 DependentVectorType *CanonCheck =
4697 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4698 assert(!CanonCheck &&
4699 "Dependent-sized vector_size canonical type broken");
4700 (void)CanonCheck;
4701 DependentVectorTypes.InsertNode(New, InsertPos);
4702 } else {
4703 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
4704 SourceLocation(), VecKind);
4705 New = new (*this, alignof(DependentVectorType))
4706 DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4707 }
4708 }
4709
4710 Types.push_back(New);
4711 return QualType(New, 0);
4712}
4713
4714/// getExtVectorType - Return the unique reference to an extended vector type of
4715/// the specified element type and size. VectorType must be a built-in type.
4717 unsigned NumElts) const {
4718 assert(vecType->isBuiltinType() || vecType->isDependentType() ||
4719 (vecType->isBitIntType() &&
4720 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4721 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4722
4723 // Check if we've already instantiated a vector of this type.
4724 llvm::FoldingSetNodeID ID;
4725 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
4727 void *InsertPos = nullptr;
4728 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4729 return QualType(VTP, 0);
4730
4731 // If the element type isn't canonical, this won't be a canonical type either,
4732 // so fill in the canonical type field.
4733 QualType Canonical;
4734 if (!vecType.isCanonical()) {
4735 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
4736
4737 // Get the new insert position for the node we care about.
4738 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4739 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4740 }
4741 auto *New = new (*this, alignof(ExtVectorType))
4742 ExtVectorType(vecType, NumElts, Canonical);
4743 VectorTypes.InsertNode(New, InsertPos);
4744 Types.push_back(New);
4745 return QualType(New, 0);
4746}
4747
4750 Expr *SizeExpr,
4751 SourceLocation AttrLoc) const {
4752 llvm::FoldingSetNodeID ID;
4754 SizeExpr);
4755
4756 void *InsertPos = nullptr;
4758 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4760 if (Canon) {
4761 // We already have a canonical version of this array type; use it as
4762 // the canonical type for a newly-built type.
4763 New = new (*this, alignof(DependentSizedExtVectorType))
4764 DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr,
4765 AttrLoc);
4766 } else {
4767 QualType CanonVecTy = getCanonicalType(vecType);
4768 if (CanonVecTy == vecType) {
4769 New = new (*this, alignof(DependentSizedExtVectorType))
4770 DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
4771
4772 DependentSizedExtVectorType *CanonCheck
4773 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4774 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4775 (void)CanonCheck;
4776 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
4777 } else {
4778 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4779 SourceLocation());
4780 New = new (*this, alignof(DependentSizedExtVectorType))
4781 DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc);
4782 }
4783 }
4784
4785 Types.push_back(New);
4786 return QualType(New, 0);
4787}
4788
4790 unsigned NumColumns) const {
4791 llvm::FoldingSetNodeID ID;
4792 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
4793 Type::ConstantMatrix);
4794
4795 assert(MatrixType::isValidElementType(ElementTy) &&
4796 "need a valid element type");
4797 assert(ConstantMatrixType::isDimensionValid(NumRows) &&
4799 "need valid matrix dimensions");
4800 void *InsertPos = nullptr;
4801 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
4802 return QualType(MTP, 0);
4803
4804 QualType Canonical;
4805 if (!ElementTy.isCanonical()) {
4806 Canonical =
4807 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
4808
4809 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4810 assert(!NewIP && "Matrix type shouldn't already exist in the map");
4811 (void)NewIP;
4812 }
4813
4814 auto *New = new (*this, alignof(ConstantMatrixType))
4815 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4816 MatrixTypes.InsertNode(New, InsertPos);
4817 Types.push_back(New);
4818 return QualType(New, 0);
4819}
4820
4822 Expr *RowExpr,
4823 Expr *ColumnExpr,
4824 SourceLocation AttrLoc) const {
4825 QualType CanonElementTy = getCanonicalType(ElementTy);
4826 llvm::FoldingSetNodeID ID;
4827 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4828 ColumnExpr);
4829
4830 void *InsertPos = nullptr;
4832 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4833
4834 if (!Canon) {
4835 Canon = new (*this, alignof(DependentSizedMatrixType))
4836 DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr,
4837 ColumnExpr, AttrLoc);
4838#ifndef NDEBUG
4839 DependentSizedMatrixType *CanonCheck =
4840 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4841 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4842#endif
4843 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
4844 Types.push_back(Canon);
4845 }
4846
4847 // Already have a canonical version of the matrix type
4848 //
4849 // If it exactly matches the requested type, use it directly.
4850 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4851 Canon->getRowExpr() == ColumnExpr)
4852 return QualType(Canon, 0);
4853
4854 // Use Canon as the canonical type for newly-built type.
4856 DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr,
4857 ColumnExpr, AttrLoc);
4858 Types.push_back(New);
4859 return QualType(New, 0);
4860}
4861
4863 Expr *AddrSpaceExpr,
4864 SourceLocation AttrLoc) const {
4865 assert(AddrSpaceExpr->isInstantiationDependent());
4866
4867 QualType canonPointeeType = getCanonicalType(PointeeType);
4868
4869 void *insertPos = nullptr;
4870 llvm::FoldingSetNodeID ID;
4871 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4872 AddrSpaceExpr);
4873
4874 DependentAddressSpaceType *canonTy =
4875 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
4876
4877 if (!canonTy) {
4878 canonTy = new (*this, alignof(DependentAddressSpaceType))
4879 DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr,
4880 AttrLoc);
4881 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
4882 Types.push_back(canonTy);
4883 }
4884
4885 if (canonPointeeType == PointeeType &&
4886 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4887 return QualType(canonTy, 0);
4888
4889 auto *sugaredType = new (*this, alignof(DependentAddressSpaceType))
4890 DependentAddressSpaceType(PointeeType, QualType(canonTy, 0),
4891 AddrSpaceExpr, AttrLoc);
4892 Types.push_back(sugaredType);
4893 return QualType(sugaredType, 0);
4894}
4895
4896/// Determine whether \p T is canonical as the result type of a function.
4898 return T.isCanonical() &&
4899 (T.getObjCLifetime() == Qualifiers::OCL_None ||
4900 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4901}
4902
4903/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4906 const FunctionType::ExtInfo &Info) const {
4907 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
4908 // functionality creates a function without a prototype regardless of
4909 // language mode (so it makes them even in C++). Once the rewriter has been
4910 // fixed, this assertion can be enabled again.
4911 //assert(!LangOpts.requiresStrictPrototypes() &&
4912 // "strict prototypes are disabled");
4913
4914 // Unique functions, to guarantee there is only one function of a particular
4915 // structure.
4916 llvm::FoldingSetNodeID ID;
4917 FunctionNoProtoType::Profile(ID, ResultTy, Info);
4918
4919 void *InsertPos = nullptr;
4920 if (FunctionNoProtoType *FT =
4921 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
4922 return QualType(FT, 0);
4923
4924 QualType Canonical;
4925 if (!isCanonicalResultType(ResultTy)) {
4926 Canonical =
4928
4929 // Get the new insert position for the node we care about.
4930 FunctionNoProtoType *NewIP =
4931 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4932 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4933 }
4934
4935 auto *New = new (*this, alignof(FunctionNoProtoType))
4936 FunctionNoProtoType(ResultTy, Canonical, Info);
4937 Types.push_back(New);
4938 FunctionNoProtoTypes.InsertNode(New, InsertPos);
4939 return QualType(New, 0);
4940}
4941
4944 CanQualType CanResultType = getCanonicalType(ResultType);
4945
4946 // Canonical result types do not have ARC lifetime qualifiers.
4947 if (CanResultType.getQualifiers().hasObjCLifetime()) {
4948 Qualifiers Qs = CanResultType.getQualifiers();
4949 Qs.removeObjCLifetime();
4951 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
4952 }
4953
4954 return CanResultType;
4955}
4956
4958 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
4959 if (ESI.Type == EST_None)
4960 return true;
4961 if (!NoexceptInType)
4962 return false;
4963
4964 // C++17 onwards: exception specification is part of the type, as a simple
4965 // boolean "can this function type throw".
4966 if (ESI.Type == EST_BasicNoexcept)
4967 return true;
4968
4969 // A noexcept(expr) specification is (possibly) canonical if expr is
4970 // value-dependent.
4971 if (ESI.Type == EST_DependentNoexcept)
4972 return true;
4973
4974 // A dynamic exception specification is canonical if it only contains pack
4975 // expansions (so we can't tell whether it's non-throwing) and all its
4976 // contained types are canonical.
4977 if (ESI.Type == EST_Dynamic) {
4978 bool AnyPackExpansions = false;
4979 for (QualType ET : ESI.Exceptions) {
4980 if (!ET.isCanonical())
4981 return false;
4982 if (ET->getAs<PackExpansionType>())
4983 AnyPackExpansions = true;
4984 }
4985 return AnyPackExpansions;
4986 }
4987
4988 return false;
4989}
4990
4991QualType ASTContext::getFunctionTypeInternal(
4992 QualType ResultTy, ArrayRef<QualType> ArgArray,
4993 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
4994 size_t NumArgs = ArgArray.size();
4995
4996 // Unique functions, to guarantee there is only one function of a particular
4997 // structure.
4998 llvm::FoldingSetNodeID ID;
4999 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
5000 *this, true);
5001
5002 QualType Canonical;
5003 bool Unique = false;
5004
5005 void *InsertPos = nullptr;
5006 if (FunctionProtoType *FPT =
5007 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
5008 QualType Existing = QualType(FPT, 0);
5009
5010 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
5011 // it so long as our exception specification doesn't contain a dependent
5012 // noexcept expression, or we're just looking for a canonical type.
5013 // Otherwise, we're going to need to create a type
5014 // sugar node to hold the concrete expression.
5015 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
5016 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
5017 return Existing;
5018
5019 // We need a new type sugar node for this one, to hold the new noexcept
5020 // expression. We do no canonicalization here, but that's OK since we don't
5021 // expect to see the same noexcept expression much more than once.
5022 Canonical = getCanonicalType(Existing);
5023 Unique = true;
5024 }
5025
5026 bool NoexceptInType = getLangOpts().CPlusPlus17;
5027 bool IsCanonicalExceptionSpec =
5029
5030 // Determine whether the type being created is already canonical or not.
5031 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
5032 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
5033 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
5034 if (!ArgArray[i].isCanonicalAsParam())
5035 isCanonical = false;
5036
5037 if (OnlyWantCanonical)
5038 assert(isCanonical &&
5039 "given non-canonical parameters constructing canonical type");
5040
5041 // If this type isn't canonical, get the canonical version of it if we don't
5042 // already have it. The exception spec is only partially part of the
5043 // canonical type, and only in C++17 onwards.
5044 if (!isCanonical && Canonical.isNull()) {
5045 SmallVector<QualType, 16> CanonicalArgs;
5046 CanonicalArgs.reserve(NumArgs);
5047 for (unsigned i = 0; i != NumArgs; ++i)
5048 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
5049
5050 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
5051 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
5052 CanonicalEPI.HasTrailingReturn = false;
5053
5054 if (IsCanonicalExceptionSpec) {
5055 // Exception spec is already OK.
5056 } else if (NoexceptInType) {
5057 switch (EPI.ExceptionSpec.Type) {
5059 // We don't know yet. It shouldn't matter what we pick here; no-one
5060 // should ever look at this.
5061 [[fallthrough]];
5062 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
5063 CanonicalEPI.ExceptionSpec.Type = EST_None;
5064 break;
5065
5066 // A dynamic exception specification is almost always "not noexcept",
5067 // with the exception that a pack expansion might expand to no types.
5068 case EST_Dynamic: {
5069 bool AnyPacks = false;
5070 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
5071 if (ET->getAs<PackExpansionType>())
5072 AnyPacks = true;
5073 ExceptionTypeStorage.push_back(getCanonicalType(ET));
5074 }
5075 if (!AnyPacks)
5076 CanonicalEPI.ExceptionSpec.Type = EST_None;
5077 else {
5078 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
5079 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
5080 }
5081 break;
5082 }
5083
5084 case EST_DynamicNone:
5085 case EST_BasicNoexcept:
5086 case EST_NoexceptTrue:
5087 case EST_NoThrow:
5088 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
5089 break;
5090
5092 llvm_unreachable("dependent noexcept is already canonical");
5093 }
5094 } else {
5096 }
5097
5098 // Adjust the canonical function result type.
5099 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
5100 Canonical =
5101 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
5102
5103 // Get the new insert position for the node we care about.
5104 FunctionProtoType *NewIP =
5105 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
5106 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5107 }
5108
5109 // Compute the needed size to hold this FunctionProtoType and the
5110 // various trailing objects.
5111 auto ESH = FunctionProtoType::getExceptionSpecSize(
5112 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
5113 size_t Size = FunctionProtoType::totalSizeToAlloc<
5121 EPI.requiresFunctionProtoTypeArmAttributes(), ESH.NumExceptionType,
5122 ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
5123 EPI.ExtParameterInfos ? NumArgs : 0,
5125 EPI.FunctionEffects.conditions().size());
5126
5127 auto *FTP = (FunctionProtoType *)Allocate(Size, alignof(FunctionProtoType));
5129 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
5130 Types.push_back(FTP);
5131 if (!Unique)
5132 FunctionProtoTypes.InsertNode(FTP, InsertPos);
5133 if (!EPI.FunctionEffects.empty())
5134 AnyFunctionEffects = true;
5135 return QualType(FTP, 0);
5136}
5137
5138QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
5139 llvm::FoldingSetNodeID ID;
5140 PipeType::Profile(ID, T, ReadOnly);
5141
5142 void *InsertPos = nullptr;
5143 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
5144 return QualType(PT, 0);
5145
5146 // If the pipe element type isn't canonical, this won't be a canonical type
5147 // either, so fill in the canonical type field.
5148 QualType Canonical;
5149 if (!T.isCanonical()) {
5150 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
5151
5152 // Get the new insert position for the node we care about.
5153 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
5154 assert(!NewIP && "Shouldn't be in the map!");
5155 (void)NewIP;
5156 }
5157 auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly);
5158 Types.push_back(New);
5159 PipeTypes.InsertNode(New, InsertPos);
5160 return QualType(New, 0);
5161}
5162
5164 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
5165 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
5166 : Ty;
5167}
5168
5170 return getPipeType(T, true);
5171}
5172
5174 return getPipeType(T, false);
5175}
5176
5177QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
5178 llvm::FoldingSetNodeID ID;
5179 BitIntType::Profile(ID, IsUnsigned, NumBits);
5180
5181 void *InsertPos = nullptr;
5182 if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5183 return QualType(EIT, 0);
5184
5185 auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits);
5186 BitIntTypes.InsertNode(New, InsertPos);
5187 Types.push_back(New);
5188 return QualType(New, 0);
5189}
5190
5192 Expr *NumBitsExpr) const {
5193 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
5194 llvm::FoldingSetNodeID ID;
5195 DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
5196
5197 void *InsertPos = nullptr;
5198 if (DependentBitIntType *Existing =
5199 DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5200 return QualType(Existing, 0);
5201
5202 auto *New = new (*this, alignof(DependentBitIntType))
5203 DependentBitIntType(IsUnsigned, NumBitsExpr);
5204 DependentBitIntTypes.InsertNode(New, InsertPos);
5205
5206 Types.push_back(New);
5207 return QualType(New, 0);
5208}
5209
5212 using Kind = PredefinedSugarType::Kind;
5213
5214 if (auto *Target = PredefinedSugarTypes[llvm::to_underlying(KD)];
5215 Target != nullptr)
5216 return QualType(Target, 0);
5217
5218 auto getCanonicalType = [](const ASTContext &Ctx, Kind KDI) -> QualType {
5219 switch (KDI) {
5220 // size_t (C99TC3 6.5.3.4), signed size_t (C++23 5.13.2) and
5221 // ptrdiff_t (C99TC3 6.5.6) Although these types are not built-in, they
5222 // are part of the core language and are widely used. Using
5223 // PredefinedSugarType makes these types as named sugar types rather than
5224 // standard integer types, enabling better hints and diagnostics.
5225 case Kind::SizeT:
5226 return Ctx.getFromTargetType(Ctx.Target->getSizeType());
5227 case Kind::SignedSizeT:
5228 return Ctx.getFromTargetType(Ctx.Target->getSignedSizeType());
5229 case Kind::PtrdiffT:
5230 return Ctx.getFromTargetType(Ctx.Target->getPtrDiffType(LangAS::Default));
5231 }
5232 llvm_unreachable("unexpected kind");
5233 };
5234 auto *New = new (*this, alignof(PredefinedSugarType))
5235 PredefinedSugarType(KD, &Idents.get(PredefinedSugarType::getName(KD)),
5236 getCanonicalType(*this, static_cast<Kind>(KD)));
5237 Types.push_back(New);
5238 PredefinedSugarTypes[llvm::to_underlying(KD)] = New;
5239 return QualType(New, 0);
5240}
5241
5243 NestedNameSpecifier Qualifier,
5244 const TypeDecl *Decl) const {
5245 if (auto *Tag = dyn_cast<TagDecl>(Decl))
5246 return getTagType(Keyword, Qualifier, Tag,
5247 /*OwnsTag=*/false);
5248 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
5249 return getTypedefType(Keyword, Qualifier, Typedef);
5250 if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5251 return getUnresolvedUsingType(Keyword, Qualifier, UD);
5252
5254 assert(!Qualifier);
5255 return QualType(Decl->TypeForDecl, 0);
5256}
5257
5259 if (auto *Tag = dyn_cast<TagDecl>(TD))
5260 return getCanonicalTagType(Tag);
5261 if (auto *TN = dyn_cast<TypedefNameDecl>(TD))
5262 return getCanonicalType(TN->getUnderlyingType());
5263 if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TD))
5265 assert(TD->TypeForDecl);
5266 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5267}
5268
5270 if (const auto *TD = dyn_cast<TagDecl>(Decl))
5271 return getCanonicalTagType(TD);
5272 if (const auto *TD = dyn_cast<TypedefNameDecl>(Decl);
5273 isa_and_nonnull<TypedefDecl, TypeAliasDecl>(TD))
5275 /*Qualifier=*/std::nullopt, TD);
5276 if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5277 return getCanonicalUnresolvedUsingType(Using);
5278
5279 assert(Decl->TypeForDecl);
5280 return QualType(Decl->TypeForDecl, 0);
5281}
5282
5283/// getTypedefType - Return the unique reference to the type for the
5284/// specified typedef name decl.
5287 NestedNameSpecifier Qualifier,
5288 const TypedefNameDecl *Decl, QualType UnderlyingType,
5289 std::optional<bool> TypeMatchesDeclOrNone) const {
5290 if (!TypeMatchesDeclOrNone) {
5291 QualType DeclUnderlyingType = Decl->getUnderlyingType();
5292 assert(!DeclUnderlyingType.isNull());
5293 if (UnderlyingType.isNull())
5294 UnderlyingType = DeclUnderlyingType;
5295 else
5296 assert(hasSameType(UnderlyingType, DeclUnderlyingType));
5297 TypeMatchesDeclOrNone = UnderlyingType == DeclUnderlyingType;
5298 } else {
5299 // FIXME: This is a workaround for a serialization cycle: assume the decl
5300 // underlying type is not available; don't touch it.
5301 assert(!UnderlyingType.isNull());
5302 }
5303
5304 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier &&
5305 *TypeMatchesDeclOrNone) {
5306 if (Decl->TypeForDecl)
5307 return QualType(Decl->TypeForDecl, 0);
5308
5309 auto *NewType = new (*this, alignof(TypedefType))
5310 TypedefType(Type::Typedef, Keyword, Qualifier, Decl, UnderlyingType,
5311 !*TypeMatchesDeclOrNone);
5312
5313 Types.push_back(NewType);
5314 Decl->TypeForDecl = NewType;
5315 return QualType(NewType, 0);
5316 }
5317
5318 llvm::FoldingSetNodeID ID;
5319 TypedefType::Profile(ID, Keyword, Qualifier, Decl, 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(
5364 hasSameType(getCanonicalTypeDeclType(cast<TypeDecl>(D->getTargetDecl())),
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(
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;
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()) {
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;
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,
5765
5766 llvm::FoldingSetNodeID ID;
5767 HLSLAttributedResourceType::Profile(ID, Wrapped, Contained, Attrs);
5768
5769 void *InsertPos = nullptr;
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;
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;
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
5935 ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc,
5936 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc,
5937 TemplateName Name, SourceLocation NameLoc,
5938 const TemplateArgumentListInfo &SpecifiedArgs,
5939 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
5941 Keyword, Name, SpecifiedArgs.arguments(), CanonicalArgs, Underlying);
5942
5945 ElaboratedKeywordLoc, QualifierLoc, TemplateKeywordLoc, NameLoc,
5946 SpecifiedArgs);
5947 return DI;
5948}
5949
5952 ArrayRef<TemplateArgumentLoc> SpecifiedArgs,
5953 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
5954 SmallVector<TemplateArgument, 4> SpecifiedArgVec;
5955 SpecifiedArgVec.reserve(SpecifiedArgs.size());
5956 for (const TemplateArgumentLoc &Arg : SpecifiedArgs)
5957 SpecifiedArgVec.push_back(Arg.getArgument());
5958
5959 return getTemplateSpecializationType(Keyword, Template, SpecifiedArgVec,
5960 CanonicalArgs, Underlying);
5961}
5962
5963[[maybe_unused]] static bool
5965 for (const TemplateArgument &Arg : Args)
5966 if (Arg.isPackExpansion())
5967 return true;
5968 return false;
5969}
5970
5973 assert(Template ==
5974 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true));
5975 assert(!Args.empty());
5976#ifndef NDEBUG
5977 for (const auto &Arg : Args)
5978 assert(Arg.structurallyEquals(getCanonicalTemplateArgument(Arg)));
5979#endif
5980
5981 llvm::FoldingSetNodeID ID;
5983 void *InsertPos = nullptr;
5984 if (auto *T = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
5985 return QualType(T, 0);
5986
5987 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
5988 sizeof(TemplateArgument) * Args.size(),
5990 auto *Spec = new (Mem)
5992 /*IsAlias=*/false, Args, QualType());
5993 assert(Spec->isDependentType() &&
5994 "canonical template specialization must be dependent");
5995 Types.push_back(Spec);
5996 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
5997 return QualType(Spec, 0);
5998}
5999
6002 ArrayRef<TemplateArgument> SpecifiedArgs,
6003 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6004 assert(!Template.getUnderlying().getAsDependentTemplateName() &&
6005 "No dependent template names here!");
6006
6007 const auto *TD = Template.getAsTemplateDecl(/*IgnoreDeduced=*/true);
6008 bool IsTypeAlias = TD && TD->isTypeAlias();
6009 if (Underlying.isNull()) {
6010 TemplateName CanonTemplate =
6011 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true);
6012 bool NonCanonical =
6013 Template != CanonTemplate || Keyword != ElaboratedTypeKeyword::None;
6015 if (CanonicalArgs.empty()) {
6016 CanonArgsVec = SmallVector<TemplateArgument, 4>(SpecifiedArgs);
6017 NonCanonical |= canonicalizeTemplateArguments(CanonArgsVec);
6018 CanonicalArgs = CanonArgsVec;
6019 } else {
6020 NonCanonical |= !llvm::equal(
6021 SpecifiedArgs, CanonicalArgs,
6022 [](const TemplateArgument &A, const TemplateArgument &B) {
6023 return A.structurallyEquals(B);
6024 });
6025 }
6026
6027 // We can get here with an alias template when the specialization
6028 // contains a pack expansion that does not match up with a parameter
6029 // pack, or a builtin template which cannot be resolved due to dependency.
6030 assert((!isa_and_nonnull<TypeAliasTemplateDecl>(TD) ||
6031 hasAnyPackExpansions(CanonicalArgs)) &&
6032 "Caller must compute aliased type");
6033 IsTypeAlias = false;
6034
6035 Underlying =
6036 getCanonicalTemplateSpecializationType(CanonTemplate, CanonicalArgs);
6037 if (!NonCanonical)
6038 return Underlying;
6039 }
6040 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
6041 sizeof(TemplateArgument) * SpecifiedArgs.size() +
6042 (IsTypeAlias ? sizeof(QualType) : 0),
6044 auto *Spec = new (Mem) TemplateSpecializationType(
6045 Keyword, Template, IsTypeAlias, SpecifiedArgs, Underlying);
6046 Types.push_back(Spec);
6047 return QualType(Spec, 0);
6048}
6049
6052 llvm::FoldingSetNodeID ID;
6053 ParenType::Profile(ID, InnerType);
6054
6055 void *InsertPos = nullptr;
6056 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6057 if (T)
6058 return QualType(T, 0);
6059
6060 QualType Canon = InnerType;
6061 if (!Canon.isCanonical()) {
6062 Canon = getCanonicalType(InnerType);
6063 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6064 assert(!CheckT && "Paren canonical type broken");
6065 (void)CheckT;
6066 }
6067
6068 T = new (*this, alignof(ParenType)) ParenType(InnerType, Canon);
6069 Types.push_back(T);
6070 ParenTypes.InsertNode(T, InsertPos);
6071 return QualType(T, 0);
6072}
6073
6076 const IdentifierInfo *MacroII) const {
6077 QualType Canon = UnderlyingTy;
6078 if (!Canon.isCanonical())
6079 Canon = getCanonicalType(UnderlyingTy);
6080
6081 auto *newType = new (*this, alignof(MacroQualifiedType))
6082 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
6083 Types.push_back(newType);
6084 return QualType(newType, 0);
6085}
6086
6089 switch (Keyword) {
6090 // These are just themselves.
6096 return Keyword;
6097
6098 // These are equivalent.
6101
6102 // These are functionally equivalent, so relying on their equivalence is
6103 // IFNDR. By making them equivalent, we disallow overloading, which at least
6104 // can produce a diagnostic.
6107 }
6108 llvm_unreachable("unexpected keyword kind");
6109}
6110
6113 const IdentifierInfo *Name) const {
6114 llvm::FoldingSetNodeID ID;
6115 DependentNameType::Profile(ID, Keyword, NNS, Name);
6116
6117 void *InsertPos = nullptr;
6118 if (DependentNameType *T =
6119 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos))
6120 return QualType(T, 0);
6121
6122 ElaboratedTypeKeyword CanonKeyword =
6124 NestedNameSpecifier CanonNNS = NNS.getCanonical();
6125
6126 QualType Canon;
6127 if (CanonKeyword != Keyword || CanonNNS != NNS) {
6128 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
6129 [[maybe_unused]] DependentNameType *T =
6130 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
6131 assert(!T && "broken canonicalization");
6132 assert(Canon.isCanonical());
6133 }
6134
6135 DependentNameType *T = new (*this, alignof(DependentNameType))
6136 DependentNameType(Keyword, NNS, Name, Canon);
6137 Types.push_back(T);
6138 DependentNameTypes.InsertNode(T, InsertPos);
6139 return QualType(T, 0);
6140}
6141
6144 ArrayRef<TemplateArgumentLoc> Args) const {
6145 // TODO: avoid this copy
6147 for (unsigned I = 0, E = Args.size(); I != E; ++I)
6148 ArgCopy.push_back(Args[I].getArgument());
6149 return getDependentTemplateSpecializationType(Keyword, Name, ArgCopy);
6150}
6151
6154 ArrayRef<TemplateArgument> Args, bool IsCanonical) const {
6155 llvm::FoldingSetNodeID ID;
6157
6158 if (auto const T_iter = DependentTemplateSpecializationTypes.find(ID);
6159 T_iter != DependentTemplateSpecializationTypes.end())
6160 return QualType(T_iter->getSecond(), 0);
6161
6162 NestedNameSpecifier NNS = Name.getQualifier();
6163
6164 QualType Canon;
6165 if (!IsCanonical) {
6166 ElaboratedTypeKeyword CanonKeyword =
6168 NestedNameSpecifier CanonNNS = NNS.getCanonical();
6169 bool AnyNonCanonArgs = false;
6170 auto CanonArgs =
6171 ::getCanonicalTemplateArguments(*this, Args, AnyNonCanonArgs);
6172
6173 if (CanonKeyword != Keyword || AnyNonCanonArgs || CanonNNS != NNS ||
6174 !Name.hasTemplateKeyword()) {
6176 CanonKeyword, {CanonNNS, Name.getName(), /*HasTemplateKeyword=*/true},
6177 CanonArgs,
6178 /*IsCanonical=*/true);
6179 }
6180 } else {
6182 assert(Name.hasTemplateKeyword());
6183 assert(NNS.isCanonical());
6184#ifndef NDEBUG
6185 for (const auto &Arg : Args)
6186 assert(Arg.structurallyEquals(getCanonicalTemplateArgument(Arg)));
6187#endif
6188 }
6189 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
6190 sizeof(TemplateArgument) * Args.size()),
6192 auto *T =
6193 new (Mem) DependentTemplateSpecializationType(Keyword, Name, Args, Canon);
6194#ifndef NDEBUG
6195 llvm::FoldingSetNodeID InsertedID;
6196 T->Profile(InsertedID, *this);
6197 assert(InsertedID == ID && "ID does not match");
6198#endif
6199 Types.push_back(T);
6200 DependentTemplateSpecializationTypes.try_emplace(ID, T);
6201 return QualType(T, 0);
6202}
6203
6205 TemplateArgument Arg;
6206 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6207 QualType ArgType = getTypeDeclType(TTP);
6208 if (TTP->isParameterPack())
6209 ArgType = getPackExpansionType(ArgType, std::nullopt);
6210
6211 Arg = TemplateArgument(ArgType);
6212 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6213 QualType T =
6214 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
6215 // For class NTTPs, ensure we include the 'const' so the type matches that
6216 // of a real template argument.
6217 // FIXME: It would be more faithful to model this as something like an
6218 // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
6220 if (T->isRecordType()) {
6221 // C++ [temp.param]p8: An id-expression naming a non-type
6222 // template-parameter of class type T denotes a static storage duration
6223 // object of type const T.
6224 T.addConst();
6225 VK = VK_LValue;
6226 } else {
6227 VK = Expr::getValueKindForType(NTTP->getType());
6228 }
6229 Expr *E = new (*this)
6230 DeclRefExpr(*this, NTTP, /*RefersToEnclosingVariableOrCapture=*/false,
6231 T, VK, NTTP->getLocation());
6232
6233 if (NTTP->isParameterPack())
6234 E = new (*this) PackExpansionExpr(E, NTTP->getLocation(), std::nullopt);
6235 Arg = TemplateArgument(E, /*IsCanonical=*/false);
6236 } else {
6237 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
6239 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
6240 TemplateName(TTP));
6241 if (TTP->isParameterPack())
6242 Arg = TemplateArgument(Name, /*NumExpansions=*/std::nullopt);
6243 else
6244 Arg = TemplateArgument(Name);
6245 }
6246
6247 if (Param->isTemplateParameterPack())
6248 Arg =
6249 TemplateArgument::CreatePackCopy(const_cast<ASTContext &>(*this), Arg);
6250
6251 return Arg;
6252}
6253
6255 UnsignedOrNone NumExpansions,
6256 bool ExpectPackInType) const {
6257 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
6258 "Pack expansions must expand one or more parameter packs");
6259
6260 llvm::FoldingSetNodeID ID;
6261 PackExpansionType::Profile(ID, Pattern, NumExpansions);
6262
6263 void *InsertPos = nullptr;
6264 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6265 if (T)
6266 return QualType(T, 0);
6267
6268 QualType Canon;
6269 if (!Pattern.isCanonical()) {
6270 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
6271 /*ExpectPackInType=*/false);
6272
6273 // Find the insert position again, in case we inserted an element into
6274 // PackExpansionTypes and invalidated our insert position.
6275 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6276 }
6277
6278 T = new (*this, alignof(PackExpansionType))
6279 PackExpansionType(Pattern, Canon, NumExpansions);
6280 Types.push_back(T);
6281 PackExpansionTypes.InsertNode(T, InsertPos);
6282 return QualType(T, 0);
6283}
6284
6285/// CmpProtocolNames - Comparison predicate for sorting protocols
6286/// alphabetically.
6287static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
6288 ObjCProtocolDecl *const *RHS) {
6289 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
6290}
6291
6293 if (Protocols.empty()) return true;
6294
6295 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
6296 return false;
6297
6298 for (unsigned i = 1; i != Protocols.size(); ++i)
6299 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
6300 Protocols[i]->getCanonicalDecl() != Protocols[i])
6301 return false;
6302 return true;
6303}
6304
6305static void
6307 // Sort protocols, keyed by name.
6308 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
6309
6310 // Canonicalize.
6311 for (ObjCProtocolDecl *&P : Protocols)
6312 P = P->getCanonicalDecl();
6313
6314 // Remove duplicates.
6315 auto ProtocolsEnd = llvm::unique(Protocols);
6316 Protocols.erase(ProtocolsEnd, Protocols.end());
6317}
6318
6320 ObjCProtocolDecl * const *Protocols,
6321 unsigned NumProtocols) const {
6322 return getObjCObjectType(BaseType, {}, ArrayRef(Protocols, NumProtocols),
6323 /*isKindOf=*/false);
6324}
6325
6327 QualType baseType,
6328 ArrayRef<QualType> typeArgs,
6330 bool isKindOf) const {
6331 // If the base type is an interface and there aren't any protocols or
6332 // type arguments to add, then the interface type will do just fine.
6333 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
6334 isa<ObjCInterfaceType>(baseType))
6335 return baseType;
6336
6337 // Look in the folding set for an existing type.
6338 llvm::FoldingSetNodeID ID;
6339 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
6340 void *InsertPos = nullptr;
6341 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
6342 return QualType(QT, 0);
6343
6344 // Determine the type arguments to be used for canonicalization,
6345 // which may be explicitly specified here or written on the base
6346 // type.
6347 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
6348 if (effectiveTypeArgs.empty()) {
6349 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
6350 effectiveTypeArgs = baseObject->getTypeArgs();
6351 }
6352
6353 // Build the canonical type, which has the canonical base type and a
6354 // sorted-and-uniqued list of protocols and the type arguments
6355 // canonicalized.
6356 QualType canonical;
6357 bool typeArgsAreCanonical = llvm::all_of(
6358 effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); });
6359 bool protocolsSorted = areSortedAndUniqued(protocols);
6360 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
6361 // Determine the canonical type arguments.
6362 ArrayRef<QualType> canonTypeArgs;
6363 SmallVector<QualType, 4> canonTypeArgsVec;
6364 if (!typeArgsAreCanonical) {
6365 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
6366 for (auto typeArg : effectiveTypeArgs)
6367 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
6368 canonTypeArgs = canonTypeArgsVec;
6369 } else {
6370 canonTypeArgs = effectiveTypeArgs;
6371 }
6372
6373 ArrayRef<ObjCProtocolDecl *> canonProtocols;
6374 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
6375 if (!protocolsSorted) {
6376 canonProtocolsVec.append(protocols.begin(), protocols.end());
6377 SortAndUniqueProtocols(canonProtocolsVec);
6378 canonProtocols = canonProtocolsVec;
6379 } else {
6380 canonProtocols = protocols;
6381 }
6382
6383 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
6384 canonProtocols, isKindOf);
6385
6386 // Regenerate InsertPos.
6387 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
6388 }
6389
6390 unsigned size = sizeof(ObjCObjectTypeImpl);
6391 size += typeArgs.size() * sizeof(QualType);
6392 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6393 void *mem = Allocate(size, alignof(ObjCObjectTypeImpl));
6394 auto *T =
6395 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
6396 isKindOf);
6397
6398 Types.push_back(T);
6399 ObjCObjectTypes.InsertNode(T, InsertPos);
6400 return QualType(T, 0);
6401}
6402
6403/// Apply Objective-C protocol qualifiers to the given type.
6404/// If this is for the canonical type of a type parameter, we can apply
6405/// protocol qualifiers on the ObjCObjectPointerType.
6408 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
6409 bool allowOnPointerType) const {
6410 hasError = false;
6411
6412 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
6413 return getObjCTypeParamType(objT->getDecl(), protocols);
6414 }
6415
6416 // Apply protocol qualifiers to ObjCObjectPointerType.
6417 if (allowOnPointerType) {
6418 if (const auto *objPtr =
6419 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
6420 const ObjCObjectType *objT = objPtr->getObjectType();
6421 // Merge protocol lists and construct ObjCObjectType.
6423 protocolsVec.append(objT->qual_begin(),
6424 objT->qual_end());
6425 protocolsVec.append(protocols.begin(), protocols.end());
6426 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
6428 objT->getBaseType(),
6429 objT->getTypeArgsAsWritten(),
6430 protocols,
6431 objT->isKindOfTypeAsWritten());
6433 }
6434 }
6435
6436 // Apply protocol qualifiers to ObjCObjectType.
6437 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
6438 // FIXME: Check for protocols to which the class type is already
6439 // known to conform.
6440
6441 return getObjCObjectType(objT->getBaseType(),
6442 objT->getTypeArgsAsWritten(),
6443 protocols,
6444 objT->isKindOfTypeAsWritten());
6445 }
6446
6447 // If the canonical type is ObjCObjectType, ...
6448 if (type->isObjCObjectType()) {
6449 // Silently overwrite any existing protocol qualifiers.
6450 // TODO: determine whether that's the right thing to do.
6451
6452 // FIXME: Check for protocols to which the class type is already
6453 // known to conform.
6454 return getObjCObjectType(type, {}, protocols, false);
6455 }
6456
6457 // id<protocol-list>
6458 if (type->isObjCIdType()) {
6459 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6460 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
6461 objPtr->isKindOfType());
6463 }
6464
6465 // Class<protocol-list>
6466 if (type->isObjCClassType()) {
6467 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6468 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
6469 objPtr->isKindOfType());
6471 }
6472
6473 hasError = true;
6474 return type;
6475}
6476
6479 ArrayRef<ObjCProtocolDecl *> protocols) const {
6480 // Look in the folding set for an existing type.
6481 llvm::FoldingSetNodeID ID;
6482 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
6483 void *InsertPos = nullptr;
6484 if (ObjCTypeParamType *TypeParam =
6485 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
6486 return QualType(TypeParam, 0);
6487
6488 // We canonicalize to the underlying type.
6489 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
6490 if (!protocols.empty()) {
6491 // Apply the protocol qualifers.
6492 bool hasError;
6494 Canonical, protocols, hasError, true /*allowOnPointerType*/));
6495 assert(!hasError && "Error when apply protocol qualifier to bound type");
6496 }
6497
6498 unsigned size = sizeof(ObjCTypeParamType);
6499 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6500 void *mem = Allocate(size, alignof(ObjCTypeParamType));
6501 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
6502
6503 Types.push_back(newType);
6504 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
6505 return QualType(newType, 0);
6506}
6507
6509 ObjCTypeParamDecl *New) const {
6510 New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType()));
6511 // Update TypeForDecl after updating TypeSourceInfo.
6512 auto *NewTypeParamTy = cast<ObjCTypeParamType>(New->TypeForDecl);
6514 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
6515 QualType UpdatedTy = getObjCTypeParamType(New, protocols);
6516 New->TypeForDecl = UpdatedTy.getTypePtr();
6517}
6518
6519/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
6520/// protocol list adopt all protocols in QT's qualified-id protocol
6521/// list.
6523 ObjCInterfaceDecl *IC) {
6524 if (!QT->isObjCQualifiedIdType())
6525 return false;
6526
6527 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
6528 // If both the right and left sides have qualifiers.
6529 for (auto *Proto : OPT->quals()) {
6530 if (!IC->ClassImplementsProtocol(Proto, false))
6531 return false;
6532 }
6533 return true;
6534 }
6535 return false;
6536}
6537
6538/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
6539/// QT's qualified-id protocol list adopt all protocols in IDecl's list
6540/// of protocols.
6542 ObjCInterfaceDecl *IDecl) {
6543 if (!QT->isObjCQualifiedIdType())
6544 return false;
6545 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
6546 if (!OPT)
6547 return false;
6548 if (!IDecl->hasDefinition())
6549 return false;
6551 CollectInheritedProtocols(IDecl, InheritedProtocols);
6552 if (InheritedProtocols.empty())
6553 return false;
6554 // Check that if every protocol in list of id<plist> conforms to a protocol
6555 // of IDecl's, then bridge casting is ok.
6556 bool Conforms = false;
6557 for (auto *Proto : OPT->quals()) {
6558 Conforms = false;
6559 for (auto *PI : InheritedProtocols) {
6560 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
6561 Conforms = true;
6562 break;
6563 }
6564 }
6565 if (!Conforms)
6566 break;
6567 }
6568 if (Conforms)
6569 return true;
6570
6571 for (auto *PI : InheritedProtocols) {
6572 // If both the right and left sides have qualifiers.
6573 bool Adopts = false;
6574 for (auto *Proto : OPT->quals()) {
6575 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
6576 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
6577 break;
6578 }
6579 if (!Adopts)
6580 return false;
6581 }
6582 return true;
6583}
6584
6585/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
6586/// the given object type.
6588 llvm::FoldingSetNodeID ID;
6589 ObjCObjectPointerType::Profile(ID, ObjectT);
6590
6591 void *InsertPos = nullptr;
6592 if (ObjCObjectPointerType *QT =
6593 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
6594 return QualType(QT, 0);
6595
6596 // Find the canonical object type.
6597 QualType Canonical;
6598 if (!ObjectT.isCanonical()) {
6599 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
6600
6601 // Regenerate InsertPos.
6602 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
6603 }
6604
6605 // No match.
6606 void *Mem =
6608 auto *QType =
6609 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
6610
6611 Types.push_back(QType);
6612 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
6613 return QualType(QType, 0);
6614}
6615
6616/// getObjCInterfaceType - Return the unique reference to the type for the
6617/// specified ObjC interface decl. The list of protocols is optional.
6619 ObjCInterfaceDecl *PrevDecl) const {
6620 if (Decl->TypeForDecl)
6621 return QualType(Decl->TypeForDecl, 0);
6622
6623 if (PrevDecl) {
6624 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
6625 Decl->TypeForDecl = PrevDecl->TypeForDecl;
6626 return QualType(PrevDecl->TypeForDecl, 0);
6627 }
6628
6629 // Prefer the definition, if there is one.
6630 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
6631 Decl = Def;
6632
6633 void *Mem = Allocate(sizeof(ObjCInterfaceType), alignof(ObjCInterfaceType));
6634 auto *T = new (Mem) ObjCInterfaceType(Decl);
6635 Decl->TypeForDecl = T;
6636 Types.push_back(T);
6637 return QualType(T, 0);
6638}
6639
6640/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
6641/// TypeOfExprType AST's (since expression's are never shared). For example,
6642/// multiple declarations that refer to "typeof(x)" all contain different
6643/// DeclRefExpr's. This doesn't effect the type checker, since it operates
6644/// on canonical type's (which are always unique).
6646 TypeOfExprType *toe;
6647 if (tofExpr->isTypeDependent()) {
6648 llvm::FoldingSetNodeID ID;
6649 DependentTypeOfExprType::Profile(ID, *this, tofExpr,
6650 Kind == TypeOfKind::Unqualified);
6651
6652 void *InsertPos = nullptr;
6654 DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
6655 if (Canon) {
6656 // We already have a "canonical" version of an identical, dependent
6657 // typeof(expr) type. Use that as our canonical type.
6658 toe = new (*this, alignof(TypeOfExprType)) TypeOfExprType(
6659 *this, tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
6660 } else {
6661 // Build a new, canonical typeof(expr) type.
6662 Canon = new (*this, alignof(DependentTypeOfExprType))
6663 DependentTypeOfExprType(*this, tofExpr, Kind);
6664 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
6665 toe = Canon;
6666 }
6667 } else {
6668 QualType Canonical = getCanonicalType(tofExpr->getType());
6669 toe = new (*this, alignof(TypeOfExprType))
6670 TypeOfExprType(*this, tofExpr, Kind, Canonical);
6671 }
6672 Types.push_back(toe);
6673 return QualType(toe, 0);
6674}
6675
6676/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
6677/// TypeOfType nodes. The only motivation to unique these nodes would be
6678/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
6679/// an issue. This doesn't affect the type checker, since it operates
6680/// on canonical types (which are always unique).
6682 QualType Canonical = getCanonicalType(tofType);
6683 auto *tot = new (*this, alignof(TypeOfType))
6684 TypeOfType(*this, tofType, Canonical, Kind);
6685 Types.push_back(tot);
6686 return QualType(tot, 0);
6687}
6688
6689/// getReferenceQualifiedType - Given an expr, will return the type for
6690/// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
6691/// and class member access into account.
6693 // C++11 [dcl.type.simple]p4:
6694 // [...]
6695 QualType T = E->getType();
6696 switch (E->getValueKind()) {
6697 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6698 // type of e;
6699 case VK_XValue:
6700 return getRValueReferenceType(T);
6701 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6702 // type of e;
6703 case VK_LValue:
6704 return getLValueReferenceType(T);
6705 // - otherwise, decltype(e) is the type of e.
6706 case VK_PRValue:
6707 return T;
6708 }
6709 llvm_unreachable("Unknown value kind");
6710}
6711
6712/// Unlike many "get<Type>" functions, we don't unique DecltypeType
6713/// nodes. This would never be helpful, since each such type has its own
6714/// expression, and would not give a significant memory saving, since there
6715/// is an Expr tree under each such type.
6717 // C++11 [temp.type]p2:
6718 // If an expression e involves a template parameter, decltype(e) denotes a
6719 // unique dependent type. Two such decltype-specifiers refer to the same
6720 // type only if their expressions are equivalent (14.5.6.1).
6721 QualType CanonType;
6722 if (!E->isInstantiationDependent()) {
6723 CanonType = getCanonicalType(UnderlyingType);
6724 } else if (!UnderlyingType.isNull()) {
6725 CanonType = getDecltypeType(E, QualType());
6726 } else {
6727 llvm::FoldingSetNodeID ID;
6729
6730 void *InsertPos = nullptr;
6731 if (DependentDecltypeType *Canon =
6732 DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos))
6733 return QualType(Canon, 0);
6734
6735 // Build a new, canonical decltype(expr) type.
6736 auto *DT =
6737 new (*this, alignof(DependentDecltypeType)) DependentDecltypeType(E);
6738 DependentDecltypeTypes.InsertNode(DT, InsertPos);
6739 Types.push_back(DT);
6740 return QualType(DT, 0);
6741 }
6742 auto *DT = new (*this, alignof(DecltypeType))
6743 DecltypeType(E, UnderlyingType, CanonType);
6744 Types.push_back(DT);
6745 return QualType(DT, 0);
6746}
6747
6749 bool FullySubstituted,
6750 ArrayRef<QualType> Expansions,
6751 UnsignedOrNone Index) const {
6752 QualType Canonical;
6753 if (FullySubstituted && Index) {
6754 Canonical = getCanonicalType(Expansions[*Index]);
6755 } else {
6756 llvm::FoldingSetNodeID ID;
6757 PackIndexingType::Profile(ID, *this, Pattern.getCanonicalType(), IndexExpr,
6758 FullySubstituted, Expansions);
6759 void *InsertPos = nullptr;
6760 PackIndexingType *Canon =
6761 DependentPackIndexingTypes.FindNodeOrInsertPos(ID, InsertPos);
6762 if (!Canon) {
6763 void *Mem = Allocate(
6764 PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6766 Canon =
6767 new (Mem) PackIndexingType(QualType(), Pattern.getCanonicalType(),
6768 IndexExpr, FullySubstituted, Expansions);
6769 DependentPackIndexingTypes.InsertNode(Canon, InsertPos);
6770 }
6771 Canonical = QualType(Canon, 0);
6772 }
6773
6774 void *Mem =
6775 Allocate(PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6777 auto *T = new (Mem) PackIndexingType(Canonical, Pattern, IndexExpr,
6778 FullySubstituted, Expansions);
6779 Types.push_back(T);
6780 return QualType(T, 0);
6781}
6782
6783/// getUnaryTransformationType - We don't unique these, since the memory
6784/// savings are minimal and these are rare.
6787 UnaryTransformType::UTTKind Kind) const {
6788
6789 llvm::FoldingSetNodeID ID;
6790 UnaryTransformType::Profile(ID, BaseType, UnderlyingType, Kind);
6791
6792 void *InsertPos = nullptr;
6793 if (UnaryTransformType *UT =
6794 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos))
6795 return QualType(UT, 0);
6796
6797 QualType CanonType;
6798 if (!BaseType->isDependentType()) {
6799 CanonType = UnderlyingType.getCanonicalType();
6800 } else {
6801 assert(UnderlyingType.isNull() || BaseType == UnderlyingType);
6802 UnderlyingType = QualType();
6803 if (QualType CanonBase = BaseType.getCanonicalType();
6804 BaseType != CanonBase) {
6805 CanonType = getUnaryTransformType(CanonBase, QualType(), Kind);
6806 assert(CanonType.isCanonical());
6807
6808 // Find the insertion position again.
6809 [[maybe_unused]] UnaryTransformType *UT =
6810 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
6811 assert(!UT && "broken canonicalization");
6812 }
6813 }
6814
6815 auto *UT = new (*this, alignof(UnaryTransformType))
6816 UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType);
6817 UnaryTransformTypes.InsertNode(UT, InsertPos);
6818 Types.push_back(UT);
6819 return QualType(UT, 0);
6820}
6821
6822QualType ASTContext::getAutoTypeInternal(
6823 QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent,
6824 bool IsPack, TemplateDecl *TypeConstraintConcept,
6825 ArrayRef<TemplateArgument> TypeConstraintArgs, bool IsCanon) const {
6826 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto &&
6827 !TypeConstraintConcept && !IsDependent)
6828 return getAutoDeductType();
6829
6830 // Look in the folding set for an existing type.
6831 llvm::FoldingSetNodeID ID;
6832 bool IsDeducedDependent =
6833 isa_and_nonnull<TemplateTemplateParmDecl>(TypeConstraintConcept) ||
6834 (!DeducedType.isNull() && DeducedType->isDependentType());
6836 IsDependent || IsDeducedDependent, TypeConstraintConcept,
6837 TypeConstraintArgs);
6838 if (auto const AT_iter = AutoTypes.find(ID); AT_iter != AutoTypes.end())
6839 return QualType(AT_iter->getSecond(), 0);
6840
6841 QualType Canon;
6842 if (!IsCanon) {
6843 if (!DeducedType.isNull()) {
6844 Canon = DeducedType.getCanonicalType();
6845 } else if (TypeConstraintConcept) {
6846 bool AnyNonCanonArgs = false;
6847 auto *CanonicalConcept =
6848 cast<TemplateDecl>(TypeConstraintConcept->getCanonicalDecl());
6849 auto CanonicalConceptArgs = ::getCanonicalTemplateArguments(
6850 *this, TypeConstraintArgs, AnyNonCanonArgs);
6851 if (CanonicalConcept != TypeConstraintConcept || AnyNonCanonArgs) {
6852 Canon = getAutoTypeInternal(QualType(), Keyword, IsDependent, IsPack,
6853 CanonicalConcept, CanonicalConceptArgs,
6854 /*IsCanon=*/true);
6855 }
6856 }
6857 }
6858
6859 void *Mem = Allocate(sizeof(AutoType) +
6860 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
6861 alignof(AutoType));
6862 auto *AT = new (Mem) AutoType(
6864 (IsDependent ? TypeDependence::DependentInstantiation
6865 : TypeDependence::None) |
6866 (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None),
6867 Canon, TypeConstraintConcept, TypeConstraintArgs);
6868#ifndef NDEBUG
6869 llvm::FoldingSetNodeID InsertedID;
6870 AT->Profile(InsertedID, *this);
6871 assert(InsertedID == ID && "ID does not match");
6872#endif
6873 Types.push_back(AT);
6874 AutoTypes.try_emplace(ID, AT);
6875 return QualType(AT, 0);
6876}
6877
6878/// getAutoType - Return the uniqued reference to the 'auto' type which has been
6879/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
6880/// canonical deduced-but-dependent 'auto' type.
6883 bool IsDependent, bool IsPack,
6884 TemplateDecl *TypeConstraintConcept,
6885 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
6886 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
6887 assert((!IsDependent || DeducedType.isNull()) &&
6888 "A dependent auto should be undeduced");
6889 return getAutoTypeInternal(DeducedType, Keyword, IsDependent, IsPack,
6890 TypeConstraintConcept, TypeConstraintArgs);
6891}
6892
6894 QualType CanonT = T.getNonPackExpansionType().getCanonicalType();
6895
6896 // Remove a type-constraint from a top-level auto or decltype(auto).
6897 if (auto *AT = CanonT->getAs<AutoType>()) {
6898 if (!AT->isConstrained())
6899 return T;
6900 return getQualifiedType(getAutoType(QualType(), AT->getKeyword(),
6901 AT->isDependentType(),
6902 AT->containsUnexpandedParameterPack()),
6903 T.getQualifiers());
6904 }
6905
6906 // FIXME: We only support constrained auto at the top level in the type of a
6907 // non-type template parameter at the moment. Once we lift that restriction,
6908 // we'll need to recursively build types containing auto here.
6909 assert(!CanonT->getContainedAutoType() ||
6910 !CanonT->getContainedAutoType()->isConstrained());
6911 return T;
6912}
6913
6914QualType ASTContext::getDeducedTemplateSpecializationTypeInternal(
6916 bool IsDependent, QualType Canon) const {
6917 // Look in the folding set for an existing type.
6918 void *InsertPos = nullptr;
6919 llvm::FoldingSetNodeID ID;
6921 IsDependent);
6923 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6924 return QualType(DTST, 0);
6925
6926 auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType))
6928 IsDependent, Canon);
6929
6930#ifndef NDEBUG
6931 llvm::FoldingSetNodeID TempID;
6932 DTST->Profile(TempID);
6933 assert(ID == TempID && "ID does not match");
6934#endif
6935 Types.push_back(DTST);
6936 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
6937 return QualType(DTST, 0);
6938}
6939
6940/// Return the uniqued reference to the deduced template specialization type
6941/// which has been deduced to the given type, or to the canonical undeduced
6942/// such type, or the canonical deduced-but-dependent such type.
6945 bool IsDependent) const {
6946 // FIXME: This could save an extra hash table lookup if it handled all the
6947 // parameters already being canonical.
6948 // FIXME: Can this be formed from a DependentTemplateName, such that the
6949 // keyword should be part of the canonical type?
6950 QualType Canon =
6951 DeducedType.isNull()
6952 ? getDeducedTemplateSpecializationTypeInternal(
6954 QualType(), IsDependent, QualType())
6955 : DeducedType.getCanonicalType();
6956 return getDeducedTemplateSpecializationTypeInternal(
6957 Keyword, Template, DeducedType, IsDependent, Canon);
6958}
6959
6960/// getAtomicType - Return the uniqued reference to the atomic type for
6961/// the given value type.
6963 // Unique pointers, to guarantee there is only one pointer of a particular
6964 // structure.
6965 llvm::FoldingSetNodeID ID;
6967
6968 void *InsertPos = nullptr;
6969 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
6970 return QualType(AT, 0);
6971
6972 // If the atomic value type isn't canonical, this won't be a canonical type
6973 // either, so fill in the canonical type field.
6974 QualType Canonical;
6975 if (!T.isCanonical()) {
6976 Canonical = getAtomicType(getCanonicalType(T));
6977
6978 // Get the new insert position for the node we care about.
6979 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
6980 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
6981 }
6982 auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
6983 Types.push_back(New);
6984 AtomicTypes.InsertNode(New, InsertPos);
6985 return QualType(New, 0);
6986}
6987
6988/// getAutoDeductType - Get type pattern for deducing against 'auto'.
6990 if (AutoDeductTy.isNull())
6991 AutoDeductTy = QualType(new (*this, alignof(AutoType))
6993 TypeDependence::None, QualType(),
6994 /*concept*/ nullptr, /*args*/ {}),
6995 0);
6996 return AutoDeductTy;
6997}
6998
6999/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
7003 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
7004 return AutoRRefDeductTy;
7005}
7006
7007/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
7008/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
7009/// needs to agree with the definition in <stddef.h>.
7012}
7013
7015 return getFromTargetType(Target->getSizeType());
7016}
7017
7018/// Return the unique signed counterpart of the integer type
7019/// corresponding to size_t.
7022}
7023
7024/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
7025/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
7028}
7029
7030/// Return the unique unsigned counterpart of "ptrdiff_t"
7031/// integer type. The standard (C11 7.21.6.1p7) refers to this type
7032/// in the definition of %tu format specifier.
7034 return getFromTargetType(Target->getUnsignedPtrDiffType(LangAS::Default));
7035}
7036
7037/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
7039 return getFromTargetType(Target->getIntMaxType());
7040}
7041
7042/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
7044 return getFromTargetType(Target->getUIntMaxType());
7045}
7046
7047/// getSignedWCharType - Return the type of "signed wchar_t".
7048/// Used when in C++, as a GCC extension.
7050 // FIXME: derive from "Target" ?
7051 return WCharTy;
7052}
7053
7054/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
7055/// Used when in C++, as a GCC extension.
7057 // FIXME: derive from "Target" ?
7058 return UnsignedIntTy;
7059}
7060
7062 return getFromTargetType(Target->getIntPtrType());
7063}
7064
7067}
7068
7069/// Return the unique type for "pid_t" defined in
7070/// <sys/types.h>. We need this to compute the correct type for vfork().
7072 return getFromTargetType(Target->getProcessIDType());
7073}
7074
7075//===----------------------------------------------------------------------===//
7076// Type Operators
7077//===----------------------------------------------------------------------===//
7078
7080 // Push qualifiers into arrays, and then discard any remaining
7081 // qualifiers.
7082 T = getCanonicalType(T);
7084 const Type *Ty = T.getTypePtr();
7086 if (getLangOpts().HLSL && isa<ConstantArrayType>(Ty)) {
7088 } else if (isa<ArrayType>(Ty)) {
7090 } else if (isa<FunctionType>(Ty)) {
7091 Result = getPointerType(QualType(Ty, 0));
7092 } else {
7093 Result = QualType(Ty, 0);
7094 }
7095
7097}
7098
7100 Qualifiers &quals) const {
7101 SplitQualType splitType = type.getSplitUnqualifiedType();
7102
7103 // FIXME: getSplitUnqualifiedType() actually walks all the way to
7104 // the unqualified desugared type and then drops it on the floor.
7105 // We then have to strip that sugar back off with
7106 // getUnqualifiedDesugaredType(), which is silly.
7107 const auto *AT =
7108 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
7109
7110 // If we don't have an array, just use the results in splitType.
7111 if (!AT) {
7112 quals = splitType.Quals;
7113 return QualType(splitType.Ty, 0);
7114 }
7115
7116 // Otherwise, recurse on the array's element type.
7117 QualType elementType = AT->getElementType();
7118 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
7119
7120 // If that didn't change the element type, AT has no qualifiers, so we
7121 // can just use the results in splitType.
7122 if (elementType == unqualElementType) {
7123 assert(quals.empty()); // from the recursive call
7124 quals = splitType.Quals;
7125 return QualType(splitType.Ty, 0);
7126 }
7127
7128 // Otherwise, add in the qualifiers from the outermost type, then
7129 // build the type back up.
7130 quals.addConsistentQualifiers(splitType.Quals);
7131
7132 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
7133 return getConstantArrayType(unqualElementType, CAT->getSize(),
7134 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
7135 }
7136
7137 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
7138 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
7139 }
7140
7141 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
7142 return getVariableArrayType(unqualElementType, VAT->getSizeExpr(),
7143 VAT->getSizeModifier(),
7144 VAT->getIndexTypeCVRQualifiers());
7145 }
7146
7147 const auto *DSAT = cast<DependentSizedArrayType>(AT);
7148 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
7149 DSAT->getSizeModifier(), 0);
7150}
7151
7152/// Attempt to unwrap two types that may both be array types with the same bound
7153/// (or both be array types of unknown bound) for the purpose of comparing the
7154/// cv-decomposition of two types per C++ [conv.qual].
7155///
7156/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7157/// C++20 [conv.qual], if permitted by the current language mode.
7159 bool AllowPiMismatch) const {
7160 while (true) {
7161 auto *AT1 = getAsArrayType(T1);
7162 if (!AT1)
7163 return;
7164
7165 auto *AT2 = getAsArrayType(T2);
7166 if (!AT2)
7167 return;
7168
7169 // If we don't have two array types with the same constant bound nor two
7170 // incomplete array types, we've unwrapped everything we can.
7171 // C++20 also permits one type to be a constant array type and the other
7172 // to be an incomplete array type.
7173 // FIXME: Consider also unwrapping array of unknown bound and VLA.
7174 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
7175 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
7176 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
7177 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7178 isa<IncompleteArrayType>(AT2))))
7179 return;
7180 } else if (isa<IncompleteArrayType>(AT1)) {
7181 if (!(isa<IncompleteArrayType>(AT2) ||
7182 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7183 isa<ConstantArrayType>(AT2))))
7184 return;
7185 } else {
7186 return;
7187 }
7188
7189 T1 = AT1->getElementType();
7190 T2 = AT2->getElementType();
7191 }
7192}
7193
7194/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
7195///
7196/// If T1 and T2 are both pointer types of the same kind, or both array types
7197/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
7198/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
7199///
7200/// This function will typically be called in a loop that successively
7201/// "unwraps" pointer and pointer-to-member types to compare them at each
7202/// level.
7203///
7204/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7205/// C++20 [conv.qual], if permitted by the current language mode.
7206///
7207/// \return \c true if a pointer type was unwrapped, \c false if we reached a
7208/// pair of types that can't be unwrapped further.
7210 bool AllowPiMismatch) const {
7211 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
7212
7213 const auto *T1PtrType = T1->getAs<PointerType>();
7214 const auto *T2PtrType = T2->getAs<PointerType>();
7215 if (T1PtrType && T2PtrType) {
7216 T1 = T1PtrType->getPointeeType();
7217 T2 = T2PtrType->getPointeeType();
7218 return true;
7219 }
7220
7221 if (const auto *T1MPType = T1->getAs<MemberPointerType>(),
7222 *T2MPType = T2->getAs<MemberPointerType>();
7223 T1MPType && T2MPType) {
7224 if (auto *RD1 = T1MPType->getMostRecentCXXRecordDecl(),
7225 *RD2 = T2MPType->getMostRecentCXXRecordDecl();
7226 RD1 != RD2 && RD1->getCanonicalDecl() != RD2->getCanonicalDecl())
7227 return false;
7228 if (T1MPType->getQualifier().getCanonical() !=
7229 T2MPType->getQualifier().getCanonical())
7230 return false;
7231 T1 = T1MPType->getPointeeType();
7232 T2 = T2MPType->getPointeeType();
7233 return true;
7234 }
7235
7236 if (getLangOpts().ObjC) {
7237 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
7238 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
7239 if (T1OPType && T2OPType) {
7240 T1 = T1OPType->getPointeeType();
7241 T2 = T2OPType->getPointeeType();
7242 return true;
7243 }
7244 }
7245
7246 // FIXME: Block pointers, too?
7247
7248 return false;
7249}
7250
7252 while (true) {
7253 Qualifiers Quals;
7254 T1 = getUnqualifiedArrayType(T1, Quals);
7255 T2 = getUnqualifiedArrayType(T2, Quals);
7256 if (hasSameType(T1, T2))
7257 return true;
7258 if (!UnwrapSimilarTypes(T1, T2))
7259 return false;
7260 }
7261}
7262
7264 while (true) {
7265 Qualifiers Quals1, Quals2;
7266 T1 = getUnqualifiedArrayType(T1, Quals1);
7267 T2 = getUnqualifiedArrayType(T2, Quals2);
7268
7269 Quals1.removeCVRQualifiers();
7270 Quals2.removeCVRQualifiers();
7271 if (Quals1 != Quals2)
7272 return false;
7273
7274 if (hasSameType(T1, T2))
7275 return true;
7276
7277 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
7278 return false;
7279 }
7280}
7281
7284 SourceLocation NameLoc) const {
7285 switch (Name.getKind()) {
7288 // DNInfo work in progress: CHECKME: what about DNLoc?
7289 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
7290 NameLoc);
7291
7293 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
7294 // DNInfo work in progress: CHECKME: what about DNLoc?
7295 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
7296 }
7297
7299 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
7300 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
7301 }
7302
7304 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
7306 DeclarationName DName;
7307 if (const IdentifierInfo *II = TN.getIdentifier()) {
7308 DName = DeclarationNames.getIdentifier(II);
7309 return DeclarationNameInfo(DName, NameLoc);
7310 } else {
7312 // DNInfo work in progress: FIXME: source locations?
7313 DeclarationNameLoc DNLoc =
7315 return DeclarationNameInfo(DName, NameLoc, DNLoc);
7316 }
7317 }
7318
7321 = Name.getAsSubstTemplateTemplateParm();
7322 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
7323 NameLoc);
7324 }
7325
7328 = Name.getAsSubstTemplateTemplateParmPack();
7330 NameLoc);
7331 }
7333 return DeclarationNameInfo(Name.getAsUsingShadowDecl()->getDeclName(),
7334 NameLoc);
7336 DeducedTemplateStorage *DTS = Name.getAsDeducedTemplateName();
7337 return getNameForTemplate(DTS->getUnderlying(), NameLoc);
7338 }
7339 }
7340
7341 llvm_unreachable("bad template name kind!");
7342}
7343
7344static const TemplateArgument *
7346 auto handleParam = [](auto *TP) -> const TemplateArgument * {
7347 if (!TP->hasDefaultArgument())
7348 return nullptr;
7349 return &TP->getDefaultArgument().getArgument();
7350 };
7351 switch (P->getKind()) {
7352 case NamedDecl::TemplateTypeParm:
7353 return handleParam(cast<TemplateTypeParmDecl>(P));
7354 case NamedDecl::NonTypeTemplateParm:
7355 return handleParam(cast<NonTypeTemplateParmDecl>(P));
7356 case NamedDecl::TemplateTemplateParm:
7357 return handleParam(cast<TemplateTemplateParmDecl>(P));
7358 default:
7359 llvm_unreachable("Unexpected template parameter kind");
7360 }
7361}
7362
7364 bool IgnoreDeduced) const {
7365 while (std::optional<TemplateName> UnderlyingOrNone =
7366 Name.desugar(IgnoreDeduced))
7367 Name = *UnderlyingOrNone;
7368
7369 switch (Name.getKind()) {
7371 TemplateDecl *Template = Name.getAsTemplateDecl();
7372 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
7374
7375 // The canonical template name is the canonical template declaration.
7376 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
7377 }
7378
7381 llvm_unreachable("cannot canonicalize unresolved template");
7382
7384 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
7385 assert(DTN && "Non-dependent template names must refer to template decls.");
7386 NestedNameSpecifier Qualifier = DTN->getQualifier();
7387 NestedNameSpecifier CanonQualifier = Qualifier.getCanonical();
7388 if (Qualifier != CanonQualifier || !DTN->hasTemplateKeyword())
7389 return getDependentTemplateName({CanonQualifier, DTN->getName(),
7390 /*HasTemplateKeyword=*/true});
7391 return Name;
7392 }
7393
7396 Name.getAsSubstTemplateTemplateParmPack();
7397 TemplateArgument canonArgPack =
7400 canonArgPack, subst->getAssociatedDecl()->getCanonicalDecl(),
7401 subst->getIndex(), subst->getFinal());
7402 }
7404 assert(IgnoreDeduced == false);
7405 DeducedTemplateStorage *DTS = Name.getAsDeducedTemplateName();
7406 DefaultArguments DefArgs = DTS->getDefaultArguments();
7407 TemplateName Underlying = DTS->getUnderlying();
7408
7409 TemplateName CanonUnderlying =
7410 getCanonicalTemplateName(Underlying, /*IgnoreDeduced=*/true);
7411 bool NonCanonical = CanonUnderlying != Underlying;
7412 auto CanonArgs =
7413 getCanonicalTemplateArguments(*this, DefArgs.Args, NonCanonical);
7414
7415 ArrayRef<NamedDecl *> Params =
7416 CanonUnderlying.getAsTemplateDecl()->getTemplateParameters()->asArray();
7417 assert(CanonArgs.size() <= Params.size());
7418 // A deduced template name which deduces the same default arguments already
7419 // declared in the underlying template is the same template as the
7420 // underlying template. We need need to note any arguments which differ from
7421 // the corresponding declaration. If any argument differs, we must build a
7422 // deduced template name.
7423 for (int I = CanonArgs.size() - 1; I >= 0; --I) {
7425 if (!A)
7426 break;
7427 auto CanonParamDefArg = getCanonicalTemplateArgument(*A);
7428 TemplateArgument &CanonDefArg = CanonArgs[I];
7429 if (CanonDefArg.structurallyEquals(CanonParamDefArg))
7430 continue;
7431 // Keep popping from the back any deault arguments which are the same.
7432 if (I == int(CanonArgs.size() - 1))
7433 CanonArgs.pop_back();
7434 NonCanonical = true;
7435 }
7436 return NonCanonical ? getDeducedTemplateName(
7437 CanonUnderlying,
7438 /*DefaultArgs=*/{DefArgs.StartPos, CanonArgs})
7439 : Name;
7440 }
7444 llvm_unreachable("always sugar node");
7445 }
7446
7447 llvm_unreachable("bad template name!");
7448}
7449
7451 const TemplateName &Y,
7452 bool IgnoreDeduced) const {
7453 return getCanonicalTemplateName(X, IgnoreDeduced) ==
7454 getCanonicalTemplateName(Y, IgnoreDeduced);
7455}
7456
7458 const AssociatedConstraint &ACX, const AssociatedConstraint &ACY) const {
7459 if (ACX.ArgPackSubstIndex != ACY.ArgPackSubstIndex)
7460 return false;
7462 return false;
7463 return true;
7464}
7465
7466bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
7467 if (!XCE != !YCE)
7468 return false;
7469
7470 if (!XCE)
7471 return true;
7472
7473 llvm::FoldingSetNodeID XCEID, YCEID;
7474 XCE->Profile(XCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7475 YCE->Profile(YCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7476 return XCEID == YCEID;
7477}
7478
7480 const TypeConstraint *YTC) const {
7481 if (!XTC != !YTC)
7482 return false;
7483
7484 if (!XTC)
7485 return true;
7486
7487 auto *NCX = XTC->getNamedConcept();
7488 auto *NCY = YTC->getNamedConcept();
7489 if (!NCX || !NCY || !isSameEntity(NCX, NCY))
7490 return false;
7493 return false;
7495 if (XTC->getConceptReference()
7497 ->NumTemplateArgs !=
7499 return false;
7500
7501 // Compare slowly by profiling.
7502 //
7503 // We couldn't compare the profiling result for the template
7504 // args here. Consider the following example in different modules:
7505 //
7506 // template <__integer_like _Tp, C<_Tp> Sentinel>
7507 // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
7508 // return __t;
7509 // }
7510 //
7511 // When we compare the profiling result for `C<_Tp>` in different
7512 // modules, it will compare the type of `_Tp` in different modules.
7513 // However, the type of `_Tp` in different modules refer to different
7514 // types here naturally. So we couldn't compare the profiling result
7515 // for the template args directly.
7518}
7519
7521 const NamedDecl *Y) const {
7522 if (X->getKind() != Y->getKind())
7523 return false;
7524
7525 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
7526 auto *TY = cast<TemplateTypeParmDecl>(Y);
7527 if (TX->isParameterPack() != TY->isParameterPack())
7528 return false;
7529 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
7530 return false;
7531 return isSameTypeConstraint(TX->getTypeConstraint(),
7532 TY->getTypeConstraint());
7533 }
7534
7535 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7536 auto *TY = cast<NonTypeTemplateParmDecl>(Y);
7537 return TX->isParameterPack() == TY->isParameterPack() &&
7538 TX->getASTContext().hasSameType(TX->getType(), TY->getType()) &&
7539 isSameConstraintExpr(TX->getPlaceholderTypeConstraint(),
7540 TY->getPlaceholderTypeConstraint());
7541 }
7542
7543 auto *TX = cast<TemplateTemplateParmDecl>(X);
7544 auto *TY = cast<TemplateTemplateParmDecl>(Y);
7545 return TX->isParameterPack() == TY->isParameterPack() &&
7546 isSameTemplateParameterList(TX->getTemplateParameters(),
7547 TY->getTemplateParameters());
7548}
7549
7551 const TemplateParameterList *X, const TemplateParameterList *Y) const {
7552 if (X->size() != Y->size())
7553 return false;
7554
7555 for (unsigned I = 0, N = X->size(); I != N; ++I)
7556 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
7557 return false;
7558
7559 return isSameConstraintExpr(X->getRequiresClause(), Y->getRequiresClause());
7560}
7561
7563 const NamedDecl *Y) const {
7564 // If the type parameter isn't the same already, we don't need to check the
7565 // default argument further.
7566 if (!isSameTemplateParameter(X, Y))
7567 return false;
7568
7569 if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(X)) {
7570 auto *TTPY = cast<TemplateTypeParmDecl>(Y);
7571 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7572 return false;
7573
7574 return hasSameType(TTPX->getDefaultArgument().getArgument().getAsType(),
7575 TTPY->getDefaultArgument().getArgument().getAsType());
7576 }
7577
7578 if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7579 auto *NTTPY = cast<NonTypeTemplateParmDecl>(Y);
7580 if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
7581 return false;
7582
7583 Expr *DefaultArgumentX =
7584 NTTPX->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7585 Expr *DefaultArgumentY =
7586 NTTPY->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7587 llvm::FoldingSetNodeID XID, YID;
7588 DefaultArgumentX->Profile(XID, *this, /*Canonical=*/true);
7589 DefaultArgumentY->Profile(YID, *this, /*Canonical=*/true);
7590 return XID == YID;
7591 }
7592
7593 auto *TTPX = cast<TemplateTemplateParmDecl>(X);
7594 auto *TTPY = cast<TemplateTemplateParmDecl>(Y);
7595
7596 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7597 return false;
7598
7599 const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
7600 const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
7601 return hasSameTemplateName(TAX.getAsTemplate(), TAY.getAsTemplate());
7602}
7603
7605 const NestedNameSpecifier Y) {
7606 if (X == Y)
7607 return true;
7608 if (!X || !Y)
7609 return false;
7610
7611 auto Kind = X.getKind();
7612 if (Kind != Y.getKind())
7613 return false;
7614
7615 // FIXME: For namespaces and types, we're permitted to check that the entity
7616 // is named via the same tokens. We should probably do so.
7617 switch (Kind) {
7619 auto [NamespaceX, PrefixX] = X.getAsNamespaceAndPrefix();
7620 auto [NamespaceY, PrefixY] = Y.getAsNamespaceAndPrefix();
7621 if (!declaresSameEntity(NamespaceX->getNamespace(),
7622 NamespaceY->getNamespace()))
7623 return false;
7624 return isSameQualifier(PrefixX, PrefixY);
7625 }
7627 const auto *TX = X.getAsType(), *TY = Y.getAsType();
7628 if (TX->getCanonicalTypeInternal() != TY->getCanonicalTypeInternal())
7629 return false;
7630 return isSameQualifier(TX->getPrefix(), TY->getPrefix());
7631 }
7635 return true;
7636 }
7637 llvm_unreachable("unhandled qualifier kind");
7638}
7639
7640static bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B) {
7641 if (!A->getASTContext().getLangOpts().CUDA)
7642 return true; // Target attributes are overloadable in CUDA compilation only.
7643 if (A->hasAttr<CUDADeviceAttr>() != B->hasAttr<CUDADeviceAttr>())
7644 return false;
7645 if (A->hasAttr<CUDADeviceAttr>() && B->hasAttr<CUDADeviceAttr>())
7646 return A->hasAttr<CUDAHostAttr>() == B->hasAttr<CUDAHostAttr>();
7647 return true; // unattributed and __host__ functions are the same.
7648}
7649
7650/// Determine whether the attributes we can overload on are identical for A and
7651/// B. Will ignore any overloadable attrs represented in the type of A and B.
7653 const FunctionDecl *B) {
7654 // Note that pass_object_size attributes are represented in the function's
7655 // ExtParameterInfo, so we don't need to check them here.
7656
7657 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
7658 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
7659 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
7660
7661 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
7662 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
7663 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
7664
7665 // Return false if the number of enable_if attributes is different.
7666 if (!Cand1A || !Cand2A)
7667 return false;
7668
7669 Cand1ID.clear();
7670 Cand2ID.clear();
7671
7672 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
7673 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
7674
7675 // Return false if any of the enable_if expressions of A and B are
7676 // different.
7677 if (Cand1ID != Cand2ID)
7678 return false;
7679 }
7680 return hasSameCudaAttrs(A, B);
7681}
7682
7683bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
7684 // Caution: this function is called by the AST reader during deserialization,
7685 // so it cannot rely on AST invariants being met. Non-trivial accessors
7686 // should be avoided, along with any traversal of redeclaration chains.
7687
7688 if (X == Y)
7689 return true;
7690
7691 if (X->getDeclName() != Y->getDeclName())
7692 return false;
7693
7694 // Must be in the same context.
7695 //
7696 // Note that we can't use DeclContext::Equals here, because the DeclContexts
7697 // could be two different declarations of the same function. (We will fix the
7698 // semantic DC to refer to the primary definition after merging.)
7699 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
7700 cast<Decl>(Y->getDeclContext()->getRedeclContext())))
7701 return false;
7702
7703 // If either X or Y are local to the owning module, they are only possible to
7704 // be the same entity if they are in the same module.
7705 if (X->isModuleLocal() || Y->isModuleLocal())
7706 if (!isInSameModule(X->getOwningModule(), Y->getOwningModule()))
7707 return false;
7708
7709 // Two typedefs refer to the same entity if they have the same underlying
7710 // type.
7711 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
7712 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
7713 return hasSameType(TypedefX->getUnderlyingType(),
7714 TypedefY->getUnderlyingType());
7715
7716 // Must have the same kind.
7717 if (X->getKind() != Y->getKind())
7718 return false;
7719
7720 // Objective-C classes and protocols with the same name always match.
7721 if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
7722 return true;
7723
7724 if (isa<ClassTemplateSpecializationDecl>(X)) {
7725 // No need to handle these here: we merge them when adding them to the
7726 // template.
7727 return false;
7728 }
7729
7730 // Compatible tags match.
7731 if (const auto *TagX = dyn_cast<TagDecl>(X)) {
7732 const auto *TagY = cast<TagDecl>(Y);
7733 return (TagX->getTagKind() == TagY->getTagKind()) ||
7734 ((TagX->getTagKind() == TagTypeKind::Struct ||
7735 TagX->getTagKind() == TagTypeKind::Class ||
7736 TagX->getTagKind() == TagTypeKind::Interface) &&
7737 (TagY->getTagKind() == TagTypeKind::Struct ||
7738 TagY->getTagKind() == TagTypeKind::Class ||
7739 TagY->getTagKind() == TagTypeKind::Interface));
7740 }
7741
7742 // Functions with the same type and linkage match.
7743 // FIXME: This needs to cope with merging of prototyped/non-prototyped
7744 // functions, etc.
7745 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
7746 const auto *FuncY = cast<FunctionDecl>(Y);
7747 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
7748 const auto *CtorY = cast<CXXConstructorDecl>(Y);
7749 if (CtorX->getInheritedConstructor() &&
7750 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
7751 CtorY->getInheritedConstructor().getConstructor()))
7752 return false;
7753 }
7754
7755 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
7756 return false;
7757
7758 // Multiversioned functions with different feature strings are represented
7759 // as separate declarations.
7760 if (FuncX->isMultiVersion()) {
7761 const auto *TAX = FuncX->getAttr<TargetAttr>();
7762 const auto *TAY = FuncY->getAttr<TargetAttr>();
7763 assert(TAX && TAY && "Multiversion Function without target attribute");
7764
7765 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
7766 return false;
7767 }
7768
7769 // Per C++20 [temp.over.link]/4, friends in different classes are sometimes
7770 // not the same entity if they are constrained.
7771 if ((FuncX->isMemberLikeConstrainedFriend() ||
7772 FuncY->isMemberLikeConstrainedFriend()) &&
7773 !FuncX->getLexicalDeclContext()->Equals(
7774 FuncY->getLexicalDeclContext())) {
7775 return false;
7776 }
7777
7778 if (!isSameAssociatedConstraint(FuncX->getTrailingRequiresClause(),
7779 FuncY->getTrailingRequiresClause()))
7780 return false;
7781
7782 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
7783 // Map to the first declaration that we've already merged into this one.
7784 // The TSI of redeclarations might not match (due to calling conventions
7785 // being inherited onto the type but not the TSI), but the TSI type of
7786 // the first declaration of the function should match across modules.
7787 FD = FD->getCanonicalDecl();
7788 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
7789 : FD->getType();
7790 };
7791 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
7792 if (!hasSameType(XT, YT)) {
7793 // We can get functions with different types on the redecl chain in C++17
7794 // if they have differing exception specifications and at least one of
7795 // the excpetion specs is unresolved.
7796 auto *XFPT = XT->getAs<FunctionProtoType>();
7797 auto *YFPT = YT->getAs<FunctionProtoType>();
7798 if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
7799 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
7802 return true;
7803 return false;
7804 }
7805
7806 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
7807 hasSameOverloadableAttrs(FuncX, FuncY);
7808 }
7809
7810 // Variables with the same type and linkage match.
7811 if (const auto *VarX = dyn_cast<VarDecl>(X)) {
7812 const auto *VarY = cast<VarDecl>(Y);
7813 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
7814 // During deserialization, we might compare variables before we load
7815 // their types. Assume the types will end up being the same.
7816 if (VarX->getType().isNull() || VarY->getType().isNull())
7817 return true;
7818
7819 if (hasSameType(VarX->getType(), VarY->getType()))
7820 return true;
7821
7822 // We can get decls with different types on the redecl chain. Eg.
7823 // template <typename T> struct S { static T Var[]; }; // #1
7824 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
7825 // Only? happens when completing an incomplete array type. In this case
7826 // when comparing #1 and #2 we should go through their element type.
7827 const ArrayType *VarXTy = getAsArrayType(VarX->getType());
7828 const ArrayType *VarYTy = getAsArrayType(VarY->getType());
7829 if (!VarXTy || !VarYTy)
7830 return false;
7831 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
7832 return hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
7833 }
7834 return false;
7835 }
7836
7837 // Namespaces with the same name and inlinedness match.
7838 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
7839 const auto *NamespaceY = cast<NamespaceDecl>(Y);
7840 return NamespaceX->isInline() == NamespaceY->isInline();
7841 }
7842
7843 // Identical template names and kinds match if their template parameter lists
7844 // and patterns match.
7845 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
7846 const auto *TemplateY = cast<TemplateDecl>(Y);
7847
7848 // ConceptDecl wouldn't be the same if their constraint expression differs.
7849 if (const auto *ConceptX = dyn_cast<ConceptDecl>(X)) {
7850 const auto *ConceptY = cast<ConceptDecl>(Y);
7851 if (!isSameConstraintExpr(ConceptX->getConstraintExpr(),
7852 ConceptY->getConstraintExpr()))
7853 return false;
7854 }
7855
7856 return isSameEntity(TemplateX->getTemplatedDecl(),
7857 TemplateY->getTemplatedDecl()) &&
7858 isSameTemplateParameterList(TemplateX->getTemplateParameters(),
7859 TemplateY->getTemplateParameters());
7860 }
7861
7862 // Fields with the same name and the same type match.
7863 if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
7864 const auto *FDY = cast<FieldDecl>(Y);
7865 // FIXME: Also check the bitwidth is odr-equivalent, if any.
7866 return hasSameType(FDX->getType(), FDY->getType());
7867 }
7868
7869 // Indirect fields with the same target field match.
7870 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
7871 const auto *IFDY = cast<IndirectFieldDecl>(Y);
7872 return IFDX->getAnonField()->getCanonicalDecl() ==
7873 IFDY->getAnonField()->getCanonicalDecl();
7874 }
7875
7876 // Enumerators with the same name match.
7877 if (isa<EnumConstantDecl>(X))
7878 // FIXME: Also check the value is odr-equivalent.
7879 return true;
7880
7881 // Using shadow declarations with the same target match.
7882 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
7883 const auto *USY = cast<UsingShadowDecl>(Y);
7884 return declaresSameEntity(USX->getTargetDecl(), USY->getTargetDecl());
7885 }
7886
7887 // Using declarations with the same qualifier match. (We already know that
7888 // the name matches.)
7889 if (const auto *UX = dyn_cast<UsingDecl>(X)) {
7890 const auto *UY = cast<UsingDecl>(Y);
7891 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7892 UX->hasTypename() == UY->hasTypename() &&
7893 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7894 }
7895 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
7896 const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
7897 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7898 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7899 }
7900 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
7901 return isSameQualifier(
7902 UX->getQualifier(),
7903 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
7904 }
7905
7906 // Using-pack declarations are only created by instantiation, and match if
7907 // they're instantiated from matching UnresolvedUsing...Decls.
7908 if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
7909 return declaresSameEntity(
7910 UX->getInstantiatedFromUsingDecl(),
7911 cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
7912 }
7913
7914 // Namespace alias definitions with the same target match.
7915 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
7916 const auto *NAY = cast<NamespaceAliasDecl>(Y);
7917 return NAX->getNamespace()->Equals(NAY->getNamespace());
7918 }
7919
7920 return false;
7921}
7922
7925 switch (Arg.getKind()) {
7927 return Arg;
7928
7930 return TemplateArgument(Arg.getAsExpr(), /*IsCanonical=*/true,
7931 Arg.getIsDefaulted());
7932
7934 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
7936 Arg.getIsDefaulted());
7937 }
7938
7941 /*isNullPtr*/ true, Arg.getIsDefaulted());
7942
7945 Arg.getIsDefaulted());
7946
7948 return TemplateArgument(
7951
7954
7956 return TemplateArgument(*this,
7959
7962 /*isNullPtr*/ false, Arg.getIsDefaulted());
7963
7965 bool AnyNonCanonArgs = false;
7966 auto CanonArgs = ::getCanonicalTemplateArguments(
7967 *this, Arg.pack_elements(), AnyNonCanonArgs);
7968 if (!AnyNonCanonArgs)
7969 return Arg;
7971 const_cast<ASTContext &>(*this), CanonArgs);
7972 NewArg.setIsDefaulted(Arg.getIsDefaulted());
7973 return NewArg;
7974 }
7975 }
7976
7977 // Silence GCC warning
7978 llvm_unreachable("Unhandled template argument kind");
7979}
7980
7982 const TemplateArgument &Arg2) const {
7983 if (Arg1.getKind() != Arg2.getKind())
7984 return false;
7985
7986 switch (Arg1.getKind()) {
7988 llvm_unreachable("Comparing NULL template argument");
7989
7991 return hasSameType(Arg1.getAsType(), Arg2.getAsType());
7992
7994 return Arg1.getAsDecl()->getUnderlyingDecl()->getCanonicalDecl() ==
7996
7998 return hasSameType(Arg1.getNullPtrType(), Arg2.getNullPtrType());
7999
8004
8006 return llvm::APSInt::isSameValue(Arg1.getAsIntegral(),
8007 Arg2.getAsIntegral());
8008
8010 return Arg1.structurallyEquals(Arg2);
8011
8013 llvm::FoldingSetNodeID ID1, ID2;
8014 Arg1.getAsExpr()->Profile(ID1, *this, /*Canonical=*/true);
8015 Arg2.getAsExpr()->Profile(ID2, *this, /*Canonical=*/true);
8016 return ID1 == ID2;
8017 }
8018
8020 return llvm::equal(
8021 Arg1.getPackAsArray(), Arg2.getPackAsArray(),
8022 [&](const TemplateArgument &Arg1, const TemplateArgument &Arg2) {
8023 return isSameTemplateArgument(Arg1, Arg2);
8024 });
8025 }
8026
8027 llvm_unreachable("Unhandled template argument kind");
8028}
8029
8031 // Handle the non-qualified case efficiently.
8032 if (!T.hasLocalQualifiers()) {
8033 // Handle the common positive case fast.
8034 if (const auto *AT = dyn_cast<ArrayType>(T))
8035 return AT;
8036 }
8037
8038 // Handle the common negative case fast.
8039 if (!isa<ArrayType>(T.getCanonicalType()))
8040 return nullptr;
8041
8042 // Apply any qualifiers from the array type to the element type. This
8043 // implements C99 6.7.3p8: "If the specification of an array type includes
8044 // any type qualifiers, the element type is so qualified, not the array type."
8045
8046 // If we get here, we either have type qualifiers on the type, or we have
8047 // sugar such as a typedef in the way. If we have type qualifiers on the type
8048 // we must propagate them down into the element type.
8049
8050 SplitQualType split = T.getSplitDesugaredType();
8051 Qualifiers qs = split.Quals;
8052
8053 // If we have a simple case, just return now.
8054 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
8055 if (!ATy || qs.empty())
8056 return ATy;
8057
8058 // Otherwise, we have an array and we have qualifiers on it. Push the
8059 // qualifiers into the array element type and return a new array type.
8060 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
8061
8062 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
8063 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
8064 CAT->getSizeExpr(),
8065 CAT->getSizeModifier(),
8066 CAT->getIndexTypeCVRQualifiers()));
8067 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
8068 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
8069 IAT->getSizeModifier(),
8070 IAT->getIndexTypeCVRQualifiers()));
8071
8072 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
8073 return cast<ArrayType>(getDependentSizedArrayType(
8074 NewEltTy, DSAT->getSizeExpr(), DSAT->getSizeModifier(),
8075 DSAT->getIndexTypeCVRQualifiers()));
8076
8077 const auto *VAT = cast<VariableArrayType>(ATy);
8078 return cast<ArrayType>(
8079 getVariableArrayType(NewEltTy, VAT->getSizeExpr(), VAT->getSizeModifier(),
8080 VAT->getIndexTypeCVRQualifiers()));
8081}
8082
8085 return getArrayParameterType(T);
8086 if (T->isArrayType() || T->isFunctionType())
8087 return getDecayedType(T);
8088 return T;
8089}
8090
8094 return T.getUnqualifiedType();
8095}
8096
8098 // C++ [except.throw]p3:
8099 // A throw-expression initializes a temporary object, called the exception
8100 // object, the type of which is determined by removing any top-level
8101 // cv-qualifiers from the static type of the operand of throw and adjusting
8102 // the type from "array of T" or "function returning T" to "pointer to T"
8103 // or "pointer to function returning T", [...]
8105 if (T->isArrayType() || T->isFunctionType())
8106 T = getDecayedType(T);
8107 return T.getUnqualifiedType();
8108}
8109
8110/// getArrayDecayedType - Return the properly qualified result of decaying the
8111/// specified array type to a pointer. This operation is non-trivial when
8112/// handling typedefs etc. The canonical type of "T" must be an array type,
8113/// this returns a pointer to a properly qualified element of the array.
8114///
8115/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
8117 // Get the element type with 'getAsArrayType' so that we don't lose any
8118 // typedefs in the element type of the array. This also handles propagation
8119 // of type qualifiers from the array type into the element type if present
8120 // (C99 6.7.3p8).
8121 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
8122 assert(PrettyArrayType && "Not an array type!");
8123
8124 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
8125
8126 // int x[restrict 4] -> int *restrict
8128 PrettyArrayType->getIndexTypeQualifiers());
8129
8130 // int x[_Nullable] -> int * _Nullable
8131 if (auto Nullability = Ty->getNullability()) {
8132 Result = const_cast<ASTContext *>(this)->getAttributedType(*Nullability,
8133 Result, Result);
8134 }
8135 return Result;
8136}
8137
8139 return getBaseElementType(array->getElementType());
8140}
8141
8143 Qualifiers qs;
8144 while (true) {
8145 SplitQualType split = type.getSplitDesugaredType();
8146 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
8147 if (!array) break;
8148
8149 type = array->getElementType();
8151 }
8152
8153 return getQualifiedType(type, qs);
8154}
8155
8156/// getConstantArrayElementCount - Returns number of constant array elements.
8157uint64_t
8159 uint64_t ElementCount = 1;
8160 do {
8161 ElementCount *= CA->getZExtSize();
8162 CA = dyn_cast_or_null<ConstantArrayType>(
8164 } while (CA);
8165 return ElementCount;
8166}
8167
8169 const ArrayInitLoopExpr *AILE) const {
8170 if (!AILE)
8171 return 0;
8172
8173 uint64_t ElementCount = 1;
8174
8175 do {
8176 ElementCount *= AILE->getArraySize().getZExtValue();
8177 AILE = dyn_cast<ArrayInitLoopExpr>(AILE->getSubExpr());
8178 } while (AILE);
8179
8180 return ElementCount;
8181}
8182
8183/// getFloatingRank - Return a relative rank for floating point types.
8184/// This routine will assert if passed a built-in type that isn't a float.
8186 if (const auto *CT = T->getAs<ComplexType>())
8187 return getFloatingRank(CT->getElementType());
8188
8189 switch (T->castAs<BuiltinType>()->getKind()) {
8190 default: llvm_unreachable("getFloatingRank(): not a floating type");
8191 case BuiltinType::Float16: return Float16Rank;
8192 case BuiltinType::Half: return HalfRank;
8193 case BuiltinType::Float: return FloatRank;
8194 case BuiltinType::Double: return DoubleRank;
8195 case BuiltinType::LongDouble: return LongDoubleRank;
8196 case BuiltinType::Float128: return Float128Rank;
8197 case BuiltinType::BFloat16: return BFloat16Rank;
8198 case BuiltinType::Ibm128: return Ibm128Rank;
8199 }
8200}
8201
8202/// getFloatingTypeOrder - Compare the rank of the two specified floating
8203/// point types, ignoring the domain of the type (i.e. 'double' ==
8204/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
8205/// LHS < RHS, return -1.
8207 FloatingRank LHSR = getFloatingRank(LHS);
8208 FloatingRank RHSR = getFloatingRank(RHS);
8209
8210 if (LHSR == RHSR)
8211 return 0;
8212 if (LHSR > RHSR)
8213 return 1;
8214 return -1;
8215}
8216
8219 return 0;
8220 return getFloatingTypeOrder(LHS, RHS);
8221}
8222
8223/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
8224/// routine will assert if passed a built-in type that isn't an integer or enum,
8225/// or if it is not canonicalized.
8226unsigned ASTContext::getIntegerRank(const Type *T) const {
8227 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
8228
8229 // Results in this 'losing' to any type of the same size, but winning if
8230 // larger.
8231 if (const auto *EIT = dyn_cast<BitIntType>(T))
8232 return 0 + (EIT->getNumBits() << 3);
8233
8234 switch (cast<BuiltinType>(T)->getKind()) {
8235 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
8236 case BuiltinType::Bool:
8237 return 1 + (getIntWidth(BoolTy) << 3);
8238 case BuiltinType::Char_S:
8239 case BuiltinType::Char_U:
8240 case BuiltinType::SChar:
8241 case BuiltinType::UChar:
8242 return 2 + (getIntWidth(CharTy) << 3);
8243 case BuiltinType::Short:
8244 case BuiltinType::UShort:
8245 return 3 + (getIntWidth(ShortTy) << 3);
8246 case BuiltinType::Int:
8247 case BuiltinType::UInt:
8248 return 4 + (getIntWidth(IntTy) << 3);
8249 case BuiltinType::Long:
8250 case BuiltinType::ULong:
8251 return 5 + (getIntWidth(LongTy) << 3);
8252 case BuiltinType::LongLong:
8253 case BuiltinType::ULongLong:
8254 return 6 + (getIntWidth(LongLongTy) << 3);
8255 case BuiltinType::Int128:
8256 case BuiltinType::UInt128:
8257 return 7 + (getIntWidth(Int128Ty) << 3);
8258
8259 // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
8260 // their underlying types" [c++20 conv.rank]
8261 case BuiltinType::Char8:
8262 return getIntegerRank(UnsignedCharTy.getTypePtr());
8263 case BuiltinType::Char16:
8264 return getIntegerRank(
8265 getFromTargetType(Target->getChar16Type()).getTypePtr());
8266 case BuiltinType::Char32:
8267 return getIntegerRank(
8268 getFromTargetType(Target->getChar32Type()).getTypePtr());
8269 case BuiltinType::WChar_S:
8270 case BuiltinType::WChar_U:
8271 return getIntegerRank(
8272 getFromTargetType(Target->getWCharType()).getTypePtr());
8273 }
8274}
8275
8276/// Whether this is a promotable bitfield reference according
8277/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
8278///
8279/// \returns the type this bit-field will promote to, or NULL if no
8280/// promotion occurs.
8282 if (E->isTypeDependent() || E->isValueDependent())
8283 return {};
8284
8285 // C++ [conv.prom]p5:
8286 // If the bit-field has an enumerated type, it is treated as any other
8287 // value of that type for promotion purposes.
8289 return {};
8290
8291 // FIXME: We should not do this unless E->refersToBitField() is true. This
8292 // matters in C where getSourceBitField() will find bit-fields for various
8293 // cases where the source expression is not a bit-field designator.
8294
8295 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
8296 if (!Field)
8297 return {};
8298
8299 QualType FT = Field->getType();
8300
8301 uint64_t BitWidth = Field->getBitWidthValue();
8302 uint64_t IntSize = getTypeSize(IntTy);
8303 // C++ [conv.prom]p5:
8304 // A prvalue for an integral bit-field can be converted to a prvalue of type
8305 // int if int can represent all the values of the bit-field; otherwise, it
8306 // can be converted to unsigned int if unsigned int can represent all the
8307 // values of the bit-field. If the bit-field is larger yet, no integral
8308 // promotion applies to it.
8309 // C11 6.3.1.1/2:
8310 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
8311 // If an int can represent all values of the original type (as restricted by
8312 // the width, for a bit-field), the value is converted to an int; otherwise,
8313 // it is converted to an unsigned int.
8314 //
8315 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
8316 // We perform that promotion here to match GCC and C++.
8317 // FIXME: C does not permit promotion of an enum bit-field whose rank is
8318 // greater than that of 'int'. We perform that promotion to match GCC.
8319 //
8320 // C23 6.3.1.1p2:
8321 // The value from a bit-field of a bit-precise integer type is converted to
8322 // the corresponding bit-precise integer type. (The rest is the same as in
8323 // C11.)
8324 if (QualType QT = Field->getType(); QT->isBitIntType())
8325 return QT;
8326
8327 if (BitWidth < IntSize)
8328 return IntTy;
8329
8330 if (BitWidth == IntSize)
8331 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
8332
8333 // Bit-fields wider than int are not subject to promotions, and therefore act
8334 // like the base type. GCC has some weird bugs in this area that we
8335 // deliberately do not follow (GCC follows a pre-standard resolution to
8336 // C's DR315 which treats bit-width as being part of the type, and this leaks
8337 // into their semantics in some cases).
8338 return {};
8339}
8340
8341/// getPromotedIntegerType - Returns the type that Promotable will
8342/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
8343/// integer type.
8345 assert(!Promotable.isNull());
8346 assert(isPromotableIntegerType(Promotable));
8347 if (const auto *ED = Promotable->getAsEnumDecl())
8348 return ED->getPromotionType();
8349
8350 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
8351 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
8352 // (3.9.1) can be converted to a prvalue of the first of the following
8353 // types that can represent all the values of its underlying type:
8354 // int, unsigned int, long int, unsigned long int, long long int, or
8355 // unsigned long long int [...]
8356 // FIXME: Is there some better way to compute this?
8357 if (BT->getKind() == BuiltinType::WChar_S ||
8358 BT->getKind() == BuiltinType::WChar_U ||
8359 BT->getKind() == BuiltinType::Char8 ||
8360 BT->getKind() == BuiltinType::Char16 ||
8361 BT->getKind() == BuiltinType::Char32) {
8362 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
8363 uint64_t FromSize = getTypeSize(BT);
8364 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
8366 for (const auto &PT : PromoteTypes) {
8367 uint64_t ToSize = getTypeSize(PT);
8368 if (FromSize < ToSize ||
8369 (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
8370 return PT;
8371 }
8372 llvm_unreachable("char type should fit into long long");
8373 }
8374 }
8375
8376 // At this point, we should have a signed or unsigned integer type.
8377 if (Promotable->isSignedIntegerType())
8378 return IntTy;
8379 uint64_t PromotableSize = getIntWidth(Promotable);
8380 uint64_t IntSize = getIntWidth(IntTy);
8381 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
8382 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
8383}
8384
8385/// Recurses in pointer/array types until it finds an objc retainable
8386/// type and returns its ownership.
8388 while (!T.isNull()) {
8389 if (T.getObjCLifetime() != Qualifiers::OCL_None)
8390 return T.getObjCLifetime();
8391 if (T->isArrayType())
8393 else if (const auto *PT = T->getAs<PointerType>())
8394 T = PT->getPointeeType();
8395 else if (const auto *RT = T->getAs<ReferenceType>())
8396 T = RT->getPointeeType();
8397 else
8398 break;
8399 }
8400
8401 return Qualifiers::OCL_None;
8402}
8403
8404static const Type *getIntegerTypeForEnum(const EnumType *ET) {
8405 // Incomplete enum types are not treated as integer types.
8406 // FIXME: In C++, enum types are never integer types.
8407 const EnumDecl *ED = ET->getOriginalDecl()->getDefinitionOrSelf();
8408 if (ED->isComplete() && !ED->isScoped())
8409 return ED->getIntegerType().getTypePtr();
8410 return nullptr;
8411}
8412
8413/// getIntegerTypeOrder - Returns the highest ranked integer type:
8414/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
8415/// LHS < RHS, return -1.
8417 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
8418 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
8419
8420 // Unwrap enums to their underlying type.
8421 if (const auto *ET = dyn_cast<EnumType>(LHSC))
8422 LHSC = getIntegerTypeForEnum(ET);
8423 if (const auto *ET = dyn_cast<EnumType>(RHSC))
8424 RHSC = getIntegerTypeForEnum(ET);
8425
8426 if (LHSC == RHSC) return 0;
8427
8428 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
8429 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
8430
8431 unsigned LHSRank = getIntegerRank(LHSC);
8432 unsigned RHSRank = getIntegerRank(RHSC);
8433
8434 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
8435 if (LHSRank == RHSRank) return 0;
8436 return LHSRank > RHSRank ? 1 : -1;
8437 }
8438
8439 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
8440 if (LHSUnsigned) {
8441 // If the unsigned [LHS] type is larger, return it.
8442 if (LHSRank >= RHSRank)
8443 return 1;
8444
8445 // If the signed type can represent all values of the unsigned type, it
8446 // wins. Because we are dealing with 2's complement and types that are
8447 // powers of two larger than each other, this is always safe.
8448 return -1;
8449 }
8450
8451 // If the unsigned [RHS] type is larger, return it.
8452 if (RHSRank >= LHSRank)
8453 return -1;
8454
8455 // If the signed type can represent all values of the unsigned type, it
8456 // wins. Because we are dealing with 2's complement and types that are
8457 // powers of two larger than each other, this is always safe.
8458 return 1;
8459}
8460
8462 if (CFConstantStringTypeDecl)
8463 return CFConstantStringTypeDecl;
8464
8465 assert(!CFConstantStringTagDecl &&
8466 "tag and typedef should be initialized together");
8467 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
8468 CFConstantStringTagDecl->startDefinition();
8469
8470 struct {
8471 QualType Type;
8472 const char *Name;
8473 } Fields[5];
8474 unsigned Count = 0;
8475
8476 /// Objective-C ABI
8477 ///
8478 /// typedef struct __NSConstantString_tag {
8479 /// const int *isa;
8480 /// int flags;
8481 /// const char *str;
8482 /// long length;
8483 /// } __NSConstantString;
8484 ///
8485 /// Swift ABI (4.1, 4.2)
8486 ///
8487 /// typedef struct __NSConstantString_tag {
8488 /// uintptr_t _cfisa;
8489 /// uintptr_t _swift_rc;
8490 /// _Atomic(uint64_t) _cfinfoa;
8491 /// const char *_ptr;
8492 /// uint32_t _length;
8493 /// } __NSConstantString;
8494 ///
8495 /// Swift ABI (5.0)
8496 ///
8497 /// typedef struct __NSConstantString_tag {
8498 /// uintptr_t _cfisa;
8499 /// uintptr_t _swift_rc;
8500 /// _Atomic(uint64_t) _cfinfoa;
8501 /// const char *_ptr;
8502 /// uintptr_t _length;
8503 /// } __NSConstantString;
8504
8505 const auto CFRuntime = getLangOpts().CFRuntime;
8506 if (static_cast<unsigned>(CFRuntime) <
8507 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
8508 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
8509 Fields[Count++] = { IntTy, "flags" };
8510 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
8511 Fields[Count++] = { LongTy, "length" };
8512 } else {
8513 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
8514 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
8515 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
8516 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
8519 Fields[Count++] = { IntTy, "_ptr" };
8520 else
8521 Fields[Count++] = { getUIntPtrType(), "_ptr" };
8522 }
8523
8524 // Create fields
8525 for (unsigned i = 0; i < Count; ++i) {
8526 FieldDecl *Field =
8527 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
8528 SourceLocation(), &Idents.get(Fields[i].Name),
8529 Fields[i].Type, /*TInfo=*/nullptr,
8530 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8531 Field->setAccess(AS_public);
8532 CFConstantStringTagDecl->addDecl(Field);
8533 }
8534
8535 CFConstantStringTagDecl->completeDefinition();
8536 // This type is designed to be compatible with NSConstantString, but cannot
8537 // use the same name, since NSConstantString is an interface.
8538 CanQualType tagType = getCanonicalTagType(CFConstantStringTagDecl);
8539 CFConstantStringTypeDecl =
8540 buildImplicitTypedef(tagType, "__NSConstantString");
8541
8542 return CFConstantStringTypeDecl;
8543}
8544
8546 if (!CFConstantStringTagDecl)
8547 getCFConstantStringDecl(); // Build the tag and the typedef.
8548 return CFConstantStringTagDecl;
8549}
8550
8551// getCFConstantStringType - Return the type used for constant CFStrings.
8553 return getTypedefType(ElaboratedTypeKeyword::None, /*Qualifier=*/std::nullopt,
8555}
8556
8558 if (ObjCSuperType.isNull()) {
8559 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
8560 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl);
8561 ObjCSuperType = getCanonicalTagType(ObjCSuperTypeDecl);
8562 }
8563 return ObjCSuperType;
8564}
8565
8567 const auto *TT = T->castAs<TypedefType>();
8568 CFConstantStringTypeDecl = cast<TypedefDecl>(TT->getDecl());
8569 CFConstantStringTagDecl = TT->castAsRecordDecl();
8570}
8571
8573 if (BlockDescriptorType)
8574 return getCanonicalTagType(BlockDescriptorType);
8575
8576 RecordDecl *RD;
8577 // FIXME: Needs the FlagAppleBlock bit.
8578 RD = buildImplicitRecord("__block_descriptor");
8579 RD->startDefinition();
8580
8581 QualType FieldTypes[] = {
8584 };
8585
8586 static const char *const FieldNames[] = {
8587 "reserved",
8588 "Size"
8589 };
8590
8591 for (size_t i = 0; i < 2; ++i) {
8593 *this, RD, SourceLocation(), SourceLocation(),
8594 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8595 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8596 Field->setAccess(AS_public);
8597 RD->addDecl(Field);
8598 }
8599
8600 RD->completeDefinition();
8601
8602 BlockDescriptorType = RD;
8603
8604 return getCanonicalTagType(BlockDescriptorType);
8605}
8606
8608 if (BlockDescriptorExtendedType)
8609 return getCanonicalTagType(BlockDescriptorExtendedType);
8610
8611 RecordDecl *RD;
8612 // FIXME: Needs the FlagAppleBlock bit.
8613 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
8614 RD->startDefinition();
8615
8616 QualType FieldTypes[] = {
8621 };
8622
8623 static const char *const FieldNames[] = {
8624 "reserved",
8625 "Size",
8626 "CopyFuncPtr",
8627 "DestroyFuncPtr"
8628 };
8629
8630 for (size_t i = 0; i < 4; ++i) {
8632 *this, RD, SourceLocation(), SourceLocation(),
8633 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8634 /*BitWidth=*/nullptr,
8635 /*Mutable=*/false, ICIS_NoInit);
8636 Field->setAccess(AS_public);
8637 RD->addDecl(Field);
8638 }
8639
8640 RD->completeDefinition();
8641
8642 BlockDescriptorExtendedType = RD;
8643 return getCanonicalTagType(BlockDescriptorExtendedType);
8644}
8645
8647 const auto *BT = dyn_cast<BuiltinType>(T);
8648
8649 if (!BT) {
8650 if (isa<PipeType>(T))
8651 return OCLTK_Pipe;
8652
8653 return OCLTK_Default;
8654 }
8655
8656 switch (BT->getKind()) {
8657#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8658 case BuiltinType::Id: \
8659 return OCLTK_Image;
8660#include "clang/Basic/OpenCLImageTypes.def"
8661
8662 case BuiltinType::OCLClkEvent:
8663 return OCLTK_ClkEvent;
8664
8665 case BuiltinType::OCLEvent:
8666 return OCLTK_Event;
8667
8668 case BuiltinType::OCLQueue:
8669 return OCLTK_Queue;
8670
8671 case BuiltinType::OCLReserveID:
8672 return OCLTK_ReserveID;
8673
8674 case BuiltinType::OCLSampler:
8675 return OCLTK_Sampler;
8676
8677 default:
8678 return OCLTK_Default;
8679 }
8680}
8681
8683 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
8684}
8685
8686/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
8687/// requires copy/dispose. Note that this must match the logic
8688/// in buildByrefHelpers.
8690 const VarDecl *D) {
8691 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
8692 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
8693 if (!copyExpr && record->hasTrivialDestructor()) return false;
8694
8695 return true;
8696 }
8697
8699 return true;
8700
8701 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
8702 // move or destroy.
8704 return true;
8705
8706 if (!Ty->isObjCRetainableType()) return false;
8707
8708 Qualifiers qs = Ty.getQualifiers();
8709
8710 // If we have lifetime, that dominates.
8711 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
8712 switch (lifetime) {
8713 case Qualifiers::OCL_None: llvm_unreachable("impossible");
8714
8715 // These are just bits as far as the runtime is concerned.
8718 return false;
8719
8720 // These cases should have been taken care of when checking the type's
8721 // non-triviality.
8724 llvm_unreachable("impossible");
8725 }
8726 llvm_unreachable("fell out of lifetime switch!");
8727 }
8728 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
8730}
8731
8733 Qualifiers::ObjCLifetime &LifeTime,
8734 bool &HasByrefExtendedLayout) const {
8735 if (!getLangOpts().ObjC ||
8736 getLangOpts().getGC() != LangOptions::NonGC)
8737 return false;
8738
8739 HasByrefExtendedLayout = false;
8740 if (Ty->isRecordType()) {
8741 HasByrefExtendedLayout = true;
8742 LifeTime = Qualifiers::OCL_None;
8743 } else if ((LifeTime = Ty.getObjCLifetime())) {
8744 // Honor the ARC qualifiers.
8745 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
8746 // The MRR rule.
8748 } else {
8749 LifeTime = Qualifiers::OCL_None;
8750 }
8751 return true;
8752}
8753
8755 assert(Target && "Expected target to be initialized");
8756 const llvm::Triple &T = Target->getTriple();
8757 // Windows is LLP64 rather than LP64
8758 if (T.isOSWindows() && T.isArch64Bit())
8759 return UnsignedLongLongTy;
8760 return UnsignedLongTy;
8761}
8762
8764 assert(Target && "Expected target to be initialized");
8765 const llvm::Triple &T = Target->getTriple();
8766 // Windows is LLP64 rather than LP64
8767 if (T.isOSWindows() && T.isArch64Bit())
8768 return LongLongTy;
8769 return LongTy;
8770}
8771
8773 if (!ObjCInstanceTypeDecl)
8774 ObjCInstanceTypeDecl =
8775 buildImplicitTypedef(getObjCIdType(), "instancetype");
8776 return ObjCInstanceTypeDecl;
8777}
8778
8779// This returns true if a type has been typedefed to BOOL:
8780// typedef <type> BOOL;
8782 if (const auto *TT = dyn_cast<TypedefType>(T))
8783 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
8784 return II->isStr("BOOL");
8785
8786 return false;
8787}
8788
8789/// getObjCEncodingTypeSize returns size of type for objective-c encoding
8790/// purpose.
8792 if (!type->isIncompleteArrayType() && type->isIncompleteType())
8793 return CharUnits::Zero();
8794
8796
8797 // Make all integer and enum types at least as large as an int
8798 if (sz.isPositive() && type->isIntegralOrEnumerationType())
8799 sz = std::max(sz, getTypeSizeInChars(IntTy));
8800 // Treat arrays as pointers, since that's how they're passed in.
8801 else if (type->isArrayType())
8803 return sz;
8804}
8805
8807 return getTargetInfo().getCXXABI().isMicrosoft() &&
8808 VD->isStaticDataMember() &&
8810 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
8811}
8812
8815 if (!VD->isInline())
8817
8818 // In almost all cases, it's a weak definition.
8819 auto *First = VD->getFirstDecl();
8820 if (First->isInlineSpecified() || !First->isStaticDataMember())
8822
8823 // If there's a file-context declaration in this translation unit, it's a
8824 // non-discardable definition.
8825 for (auto *D : VD->redecls())
8827 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
8829
8830 // If we've not seen one yet, we don't know.
8832}
8833
8834static std::string charUnitsToString(const CharUnits &CU) {
8835 return llvm::itostr(CU.getQuantity());
8836}
8837
8838/// getObjCEncodingForBlock - Return the encoded type for this block
8839/// declaration.
8841 std::string S;
8842
8843 const BlockDecl *Decl = Expr->getBlockDecl();
8844 QualType BlockTy =
8846 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
8847 // Encode result type.
8848 if (getLangOpts().EncodeExtendedBlockSig)
8850 true /*Extended*/);
8851 else
8852 getObjCEncodingForType(BlockReturnTy, S);
8853 // Compute size of all parameters.
8854 // Start with computing size of a pointer in number of bytes.
8855 // FIXME: There might(should) be a better way of doing this computation!
8857 CharUnits ParmOffset = PtrSize;
8858 for (auto *PI : Decl->parameters()) {
8859 QualType PType = PI->getType();
8861 if (sz.isZero())
8862 continue;
8863 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
8864 ParmOffset += sz;
8865 }
8866 // Size of the argument frame
8867 S += charUnitsToString(ParmOffset);
8868 // Block pointer and offset.
8869 S += "@?0";
8870
8871 // Argument types.
8872 ParmOffset = PtrSize;
8873 for (auto *PVDecl : Decl->parameters()) {
8874 QualType PType = PVDecl->getOriginalType();
8875 if (const auto *AT =
8876 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8877 // Use array's original type only if it has known number of
8878 // elements.
8879 if (!isa<ConstantArrayType>(AT))
8880 PType = PVDecl->getType();
8881 } else if (PType->isFunctionType())
8882 PType = PVDecl->getType();
8883 if (getLangOpts().EncodeExtendedBlockSig)
8885 S, true /*Extended*/);
8886 else
8887 getObjCEncodingForType(PType, S);
8888 S += charUnitsToString(ParmOffset);
8889 ParmOffset += getObjCEncodingTypeSize(PType);
8890 }
8891
8892 return S;
8893}
8894
8895std::string
8897 std::string S;
8898 // Encode result type.
8899 getObjCEncodingForType(Decl->getReturnType(), S);
8900 CharUnits ParmOffset;
8901 // Compute size of all parameters.
8902 for (auto *PI : Decl->parameters()) {
8903 QualType PType = PI->getType();
8905 if (sz.isZero())
8906 continue;
8907
8908 assert(sz.isPositive() &&
8909 "getObjCEncodingForFunctionDecl - Incomplete param type");
8910 ParmOffset += sz;
8911 }
8912 S += charUnitsToString(ParmOffset);
8913 ParmOffset = CharUnits::Zero();
8914
8915 // Argument types.
8916 for (auto *PVDecl : Decl->parameters()) {
8917 QualType PType = PVDecl->getOriginalType();
8918 if (const auto *AT =
8919 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8920 // Use array's original type only if it has known number of
8921 // elements.
8922 if (!isa<ConstantArrayType>(AT))
8923 PType = PVDecl->getType();
8924 } else if (PType->isFunctionType())
8925 PType = PVDecl->getType();
8926 getObjCEncodingForType(PType, S);
8927 S += charUnitsToString(ParmOffset);
8928 ParmOffset += getObjCEncodingTypeSize(PType);
8929 }
8930
8931 return S;
8932}
8933
8934/// getObjCEncodingForMethodParameter - Return the encoded type for a single
8935/// method parameter or return type. If Extended, include class names and
8936/// block object types.
8938 QualType T, std::string& S,
8939 bool Extended) const {
8940 // Encode type qualifier, 'in', 'inout', etc. for the parameter.
8942 // Encode parameter type.
8943 ObjCEncOptions Options = ObjCEncOptions()
8944 .setExpandPointedToStructures()
8945 .setExpandStructures()
8946 .setIsOutermostType();
8947 if (Extended)
8948 Options.setEncodeBlockParameters().setEncodeClassNames();
8949 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
8950}
8951
8952/// getObjCEncodingForMethodDecl - Return the encoded type for this method
8953/// declaration.
8955 bool Extended) const {
8956 // FIXME: This is not very efficient.
8957 // Encode return type.
8958 std::string S;
8959 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
8960 Decl->getReturnType(), S, Extended);
8961 // Compute size of all parameters.
8962 // Start with computing size of a pointer in number of bytes.
8963 // FIXME: There might(should) be a better way of doing this computation!
8965 // The first two arguments (self and _cmd) are pointers; account for
8966 // their size.
8967 CharUnits ParmOffset = 2 * PtrSize;
8968 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8969 E = Decl->sel_param_end(); PI != E; ++PI) {
8970 QualType PType = (*PI)->getType();
8972 if (sz.isZero())
8973 continue;
8974
8975 assert(sz.isPositive() &&
8976 "getObjCEncodingForMethodDecl - Incomplete param type");
8977 ParmOffset += sz;
8978 }
8979 S += charUnitsToString(ParmOffset);
8980 S += "@0:";
8981 S += charUnitsToString(PtrSize);
8982
8983 // Argument types.
8984 ParmOffset = 2 * PtrSize;
8985 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8986 E = Decl->sel_param_end(); PI != E; ++PI) {
8987 const ParmVarDecl *PVDecl = *PI;
8988 QualType PType = PVDecl->getOriginalType();
8989 if (const auto *AT =
8990 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8991 // Use array's original type only if it has known number of
8992 // elements.
8993 if (!isa<ConstantArrayType>(AT))
8994 PType = PVDecl->getType();
8995 } else if (PType->isFunctionType())
8996 PType = PVDecl->getType();
8998 PType, S, Extended);
8999 S += charUnitsToString(ParmOffset);
9000 ParmOffset += getObjCEncodingTypeSize(PType);
9001 }
9002
9003 return S;
9004}
9005
9008 const ObjCPropertyDecl *PD,
9009 const Decl *Container) const {
9010 if (!Container)
9011 return nullptr;
9012 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
9013 for (auto *PID : CID->property_impls())
9014 if (PID->getPropertyDecl() == PD)
9015 return PID;
9016 } else {
9017 const auto *OID = cast<ObjCImplementationDecl>(Container);
9018 for (auto *PID : OID->property_impls())
9019 if (PID->getPropertyDecl() == PD)
9020 return PID;
9021 }
9022 return nullptr;
9023}
9024
9025/// getObjCEncodingForPropertyDecl - Return the encoded type for this
9026/// property declaration. If non-NULL, Container must be either an
9027/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
9028/// NULL when getting encodings for protocol properties.
9029/// Property attributes are stored as a comma-delimited C string. The simple
9030/// attributes readonly and bycopy are encoded as single characters. The
9031/// parametrized attributes, getter=name, setter=name, and ivar=name, are
9032/// encoded as single characters, followed by an identifier. Property types
9033/// are also encoded as a parametrized attribute. The characters used to encode
9034/// these attributes are defined by the following enumeration:
9035/// @code
9036/// enum PropertyAttributes {
9037/// kPropertyReadOnly = 'R', // property is read-only.
9038/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
9039/// kPropertyByref = '&', // property is a reference to the value last assigned
9040/// kPropertyDynamic = 'D', // property is dynamic
9041/// kPropertyGetter = 'G', // followed by getter selector name
9042/// kPropertySetter = 'S', // followed by setter selector name
9043/// kPropertyInstanceVariable = 'V' // followed by instance variable name
9044/// kPropertyType = 'T' // followed by old-style type encoding.
9045/// kPropertyWeak = 'W' // 'weak' property
9046/// kPropertyStrong = 'P' // property GC'able
9047/// kPropertyNonAtomic = 'N' // property non-atomic
9048/// kPropertyOptional = '?' // property optional
9049/// };
9050/// @endcode
9051std::string
9053 const Decl *Container) const {
9054 // Collect information from the property implementation decl(s).
9055 bool Dynamic = false;
9056 ObjCPropertyImplDecl *SynthesizePID = nullptr;
9057
9058 if (ObjCPropertyImplDecl *PropertyImpDecl =
9060 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
9061 Dynamic = true;
9062 else
9063 SynthesizePID = PropertyImpDecl;
9064 }
9065
9066 // FIXME: This is not very efficient.
9067 std::string S = "T";
9068
9069 // Encode result type.
9070 // GCC has some special rules regarding encoding of properties which
9071 // closely resembles encoding of ivars.
9073
9074 if (PD->isOptional())
9075 S += ",?";
9076
9077 if (PD->isReadOnly()) {
9078 S += ",R";
9080 S += ",C";
9082 S += ",&";
9084 S += ",W";
9085 } else {
9086 switch (PD->getSetterKind()) {
9087 case ObjCPropertyDecl::Assign: break;
9088 case ObjCPropertyDecl::Copy: S += ",C"; break;
9089 case ObjCPropertyDecl::Retain: S += ",&"; break;
9090 case ObjCPropertyDecl::Weak: S += ",W"; break;
9091 }
9092 }
9093
9094 // It really isn't clear at all what this means, since properties
9095 // are "dynamic by default".
9096 if (Dynamic)
9097 S += ",D";
9098
9100 S += ",N";
9101
9103 S += ",G";
9104 S += PD->getGetterName().getAsString();
9105 }
9106
9108 S += ",S";
9109 S += PD->getSetterName().getAsString();
9110 }
9111
9112 if (SynthesizePID) {
9113 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
9114 S += ",V";
9115 S += OID->getNameAsString();
9116 }
9117
9118 // FIXME: OBJCGC: weak & strong
9119 return S;
9120}
9121
9122/// getLegacyIntegralTypeEncoding -
9123/// Another legacy compatibility encoding: 32-bit longs are encoded as
9124/// 'l' or 'L' , but not always. For typedefs, we need to use
9125/// 'i' or 'I' instead if encoding a struct field, or a pointer!
9127 if (PointeeTy->getAs<TypedefType>()) {
9128 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
9129 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
9130 PointeeTy = UnsignedIntTy;
9131 else
9132 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
9133 PointeeTy = IntTy;
9134 }
9135 }
9136}
9137
9139 const FieldDecl *Field,
9140 QualType *NotEncodedT) const {
9141 // We follow the behavior of gcc, expanding structures which are
9142 // directly pointed to, and expanding embedded structures. Note that
9143 // these rules are sufficient to prevent recursive encoding of the
9144 // same type.
9145 getObjCEncodingForTypeImpl(T, S,
9146 ObjCEncOptions()
9147 .setExpandPointedToStructures()
9148 .setExpandStructures()
9149 .setIsOutermostType(),
9150 Field, NotEncodedT);
9151}
9152
9154 std::string& S) const {
9155 // Encode result type.
9156 // GCC has some special rules regarding encoding of properties which
9157 // closely resembles encoding of ivars.
9158 getObjCEncodingForTypeImpl(T, S,
9159 ObjCEncOptions()
9160 .setExpandPointedToStructures()
9161 .setExpandStructures()
9162 .setIsOutermostType()
9163 .setEncodingProperty(),
9164 /*Field=*/nullptr);
9165}
9166
9168 const BuiltinType *BT) {
9169 BuiltinType::Kind kind = BT->getKind();
9170 switch (kind) {
9171 case BuiltinType::Void: return 'v';
9172 case BuiltinType::Bool: return 'B';
9173 case BuiltinType::Char8:
9174 case BuiltinType::Char_U:
9175 case BuiltinType::UChar: return 'C';
9176 case BuiltinType::Char16:
9177 case BuiltinType::UShort: return 'S';
9178 case BuiltinType::Char32:
9179 case BuiltinType::UInt: return 'I';
9180 case BuiltinType::ULong:
9181 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
9182 case BuiltinType::UInt128: return 'T';
9183 case BuiltinType::ULongLong: return 'Q';
9184 case BuiltinType::Char_S:
9185 case BuiltinType::SChar: return 'c';
9186 case BuiltinType::Short: return 's';
9187 case BuiltinType::WChar_S:
9188 case BuiltinType::WChar_U:
9189 case BuiltinType::Int: return 'i';
9190 case BuiltinType::Long:
9191 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
9192 case BuiltinType::LongLong: return 'q';
9193 case BuiltinType::Int128: return 't';
9194 case BuiltinType::Float: return 'f';
9195 case BuiltinType::Double: return 'd';
9196 case BuiltinType::LongDouble: return 'D';
9197 case BuiltinType::NullPtr: return '*'; // like char*
9198
9199 case BuiltinType::BFloat16:
9200 case BuiltinType::Float16:
9201 case BuiltinType::Float128:
9202 case BuiltinType::Ibm128:
9203 case BuiltinType::Half:
9204 case BuiltinType::ShortAccum:
9205 case BuiltinType::Accum:
9206 case BuiltinType::LongAccum:
9207 case BuiltinType::UShortAccum:
9208 case BuiltinType::UAccum:
9209 case BuiltinType::ULongAccum:
9210 case BuiltinType::ShortFract:
9211 case BuiltinType::Fract:
9212 case BuiltinType::LongFract:
9213 case BuiltinType::UShortFract:
9214 case BuiltinType::UFract:
9215 case BuiltinType::ULongFract:
9216 case BuiltinType::SatShortAccum:
9217 case BuiltinType::SatAccum:
9218 case BuiltinType::SatLongAccum:
9219 case BuiltinType::SatUShortAccum:
9220 case BuiltinType::SatUAccum:
9221 case BuiltinType::SatULongAccum:
9222 case BuiltinType::SatShortFract:
9223 case BuiltinType::SatFract:
9224 case BuiltinType::SatLongFract:
9225 case BuiltinType::SatUShortFract:
9226 case BuiltinType::SatUFract:
9227 case BuiltinType::SatULongFract:
9228 // FIXME: potentially need @encodes for these!
9229 return ' ';
9230
9231#define SVE_TYPE(Name, Id, SingletonId) \
9232 case BuiltinType::Id:
9233#include "clang/Basic/AArch64ACLETypes.def"
9234#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9235#include "clang/Basic/RISCVVTypes.def"
9236#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9237#include "clang/Basic/WebAssemblyReferenceTypes.def"
9238#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
9239#include "clang/Basic/AMDGPUTypes.def"
9240 {
9241 DiagnosticsEngine &Diags = C->getDiagnostics();
9242 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
9243 "cannot yet @encode type %0");
9244 Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
9245 return ' ';
9246 }
9247
9248 case BuiltinType::ObjCId:
9249 case BuiltinType::ObjCClass:
9250 case BuiltinType::ObjCSel:
9251 llvm_unreachable("@encoding ObjC primitive type");
9252
9253 // OpenCL and placeholder types don't need @encodings.
9254#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
9255 case BuiltinType::Id:
9256#include "clang/Basic/OpenCLImageTypes.def"
9257#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
9258 case BuiltinType::Id:
9259#include "clang/Basic/OpenCLExtensionTypes.def"
9260 case BuiltinType::OCLEvent:
9261 case BuiltinType::OCLClkEvent:
9262 case BuiltinType::OCLQueue:
9263 case BuiltinType::OCLReserveID:
9264 case BuiltinType::OCLSampler:
9265 case BuiltinType::Dependent:
9266#define PPC_VECTOR_TYPE(Name, Id, Size) \
9267 case BuiltinType::Id:
9268#include "clang/Basic/PPCTypes.def"
9269#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9270#include "clang/Basic/HLSLIntangibleTypes.def"
9271#define BUILTIN_TYPE(KIND, ID)
9272#define PLACEHOLDER_TYPE(KIND, ID) \
9273 case BuiltinType::KIND:
9274#include "clang/AST/BuiltinTypes.def"
9275 llvm_unreachable("invalid builtin type for @encode");
9276 }
9277 llvm_unreachable("invalid BuiltinType::Kind value");
9278}
9279
9280static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED) {
9282
9283 // The encoding of an non-fixed enum type is always 'i', regardless of size.
9284 if (!Enum->isFixed())
9285 return 'i';
9286
9287 // The encoding of a fixed enum type matches its fixed underlying type.
9288 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
9290}
9291
9292static void EncodeBitField(const ASTContext *Ctx, std::string& S,
9293 QualType T, const FieldDecl *FD) {
9294 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
9295 S += 'b';
9296 // The NeXT runtime encodes bit fields as b followed by the number of bits.
9297 // The GNU runtime requires more information; bitfields are encoded as b,
9298 // then the offset (in bits) of the first element, then the type of the
9299 // bitfield, then the size in bits. For example, in this structure:
9300 //
9301 // struct
9302 // {
9303 // int integer;
9304 // int flags:2;
9305 // };
9306 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
9307 // runtime, but b32i2 for the GNU runtime. The reason for this extra
9308 // information is not especially sensible, but we're stuck with it for
9309 // compatibility with GCC, although providing it breaks anything that
9310 // actually uses runtime introspection and wants to work on both runtimes...
9311 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
9312 uint64_t Offset;
9313
9314 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
9315 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), IVD);
9316 } else {
9317 const RecordDecl *RD = FD->getParent();
9318 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
9319 Offset = RL.getFieldOffset(FD->getFieldIndex());
9320 }
9321
9322 S += llvm::utostr(Offset);
9323
9324 if (const auto *ET = T->getAsCanonical<EnumType>())
9325 S += ObjCEncodingForEnumDecl(Ctx, ET->getOriginalDecl());
9326 else {
9327 const auto *BT = T->castAs<BuiltinType>();
9328 S += getObjCEncodingForPrimitiveType(Ctx, BT);
9329 }
9330 }
9331 S += llvm::utostr(FD->getBitWidthValue());
9332}
9333
9334// Helper function for determining whether the encoded type string would include
9335// a template specialization type.
9337 bool VisitBasesAndFields) {
9339
9340 if (auto *PT = T->getAs<PointerType>())
9342 PT->getPointeeType().getTypePtr(), false);
9343
9344 auto *CXXRD = T->getAsCXXRecordDecl();
9345
9346 if (!CXXRD)
9347 return false;
9348
9349 if (isa<ClassTemplateSpecializationDecl>(CXXRD))
9350 return true;
9351
9352 if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
9353 return false;
9354
9355 for (const auto &B : CXXRD->bases())
9356 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
9357 true))
9358 return true;
9359
9360 for (auto *FD : CXXRD->fields())
9361 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
9362 true))
9363 return true;
9364
9365 return false;
9366}
9367
9368// FIXME: Use SmallString for accumulating string.
9369void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
9370 const ObjCEncOptions Options,
9371 const FieldDecl *FD,
9372 QualType *NotEncodedT) const {
9374 switch (CT->getTypeClass()) {
9375 case Type::Builtin:
9376 case Type::Enum:
9377 if (FD && FD->isBitField())
9378 return EncodeBitField(this, S, T, FD);
9379 if (const auto *BT = dyn_cast<BuiltinType>(CT))
9380 S += getObjCEncodingForPrimitiveType(this, BT);
9381 else
9382 S += ObjCEncodingForEnumDecl(this, cast<EnumType>(CT)->getOriginalDecl());
9383 return;
9384
9385 case Type::Complex:
9386 S += 'j';
9387 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
9388 ObjCEncOptions(),
9389 /*Field=*/nullptr);
9390 return;
9391
9392 case Type::Atomic:
9393 S += 'A';
9394 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
9395 ObjCEncOptions(),
9396 /*Field=*/nullptr);
9397 return;
9398
9399 // encoding for pointer or reference types.
9400 case Type::Pointer:
9401 case Type::LValueReference:
9402 case Type::RValueReference: {
9403 QualType PointeeTy;
9404 if (isa<PointerType>(CT)) {
9405 const auto *PT = T->castAs<PointerType>();
9406 if (PT->isObjCSelType()) {
9407 S += ':';
9408 return;
9409 }
9410 PointeeTy = PT->getPointeeType();
9411 } else {
9412 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
9413 }
9414
9415 bool isReadOnly = false;
9416 // For historical/compatibility reasons, the read-only qualifier of the
9417 // pointee gets emitted _before_ the '^'. The read-only qualifier of
9418 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
9419 // Also, do not emit the 'r' for anything but the outermost type!
9420 if (T->getAs<TypedefType>()) {
9421 if (Options.IsOutermostType() && T.isConstQualified()) {
9422 isReadOnly = true;
9423 S += 'r';
9424 }
9425 } else if (Options.IsOutermostType()) {
9426 QualType P = PointeeTy;
9427 while (auto PT = P->getAs<PointerType>())
9428 P = PT->getPointeeType();
9429 if (P.isConstQualified()) {
9430 isReadOnly = true;
9431 S += 'r';
9432 }
9433 }
9434 if (isReadOnly) {
9435 // Another legacy compatibility encoding. Some ObjC qualifier and type
9436 // combinations need to be rearranged.
9437 // Rewrite "in const" from "nr" to "rn"
9438 if (StringRef(S).ends_with("nr"))
9439 S.replace(S.end()-2, S.end(), "rn");
9440 }
9441
9442 if (PointeeTy->isCharType()) {
9443 // char pointer types should be encoded as '*' unless it is a
9444 // type that has been typedef'd to 'BOOL'.
9445 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
9446 S += '*';
9447 return;
9448 }
9449 } else if (const auto *RTy = PointeeTy->getAsCanonical<RecordType>()) {
9450 const IdentifierInfo *II = RTy->getOriginalDecl()->getIdentifier();
9451 // GCC binary compat: Need to convert "struct objc_class *" to "#".
9452 if (II == &Idents.get("objc_class")) {
9453 S += '#';
9454 return;
9455 }
9456 // GCC binary compat: Need to convert "struct objc_object *" to "@".
9457 if (II == &Idents.get("objc_object")) {
9458 S += '@';
9459 return;
9460 }
9461 // If the encoded string for the class includes template names, just emit
9462 // "^v" for pointers to the class.
9463 if (getLangOpts().CPlusPlus &&
9464 (!getLangOpts().EncodeCXXClassTemplateSpec &&
9466 RTy, Options.ExpandPointedToStructures()))) {
9467 S += "^v";
9468 return;
9469 }
9470 // fall through...
9471 }
9472 S += '^';
9474
9475 ObjCEncOptions NewOptions;
9476 if (Options.ExpandPointedToStructures())
9477 NewOptions.setExpandStructures();
9478 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
9479 /*Field=*/nullptr, NotEncodedT);
9480 return;
9481 }
9482
9483 case Type::ConstantArray:
9484 case Type::IncompleteArray:
9485 case Type::VariableArray: {
9486 const auto *AT = cast<ArrayType>(CT);
9487
9488 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
9489 // Incomplete arrays are encoded as a pointer to the array element.
9490 S += '^';
9491
9492 getObjCEncodingForTypeImpl(
9493 AT->getElementType(), S,
9494 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
9495 } else {
9496 S += '[';
9497
9498 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
9499 S += llvm::utostr(CAT->getZExtSize());
9500 else {
9501 //Variable length arrays are encoded as a regular array with 0 elements.
9502 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
9503 "Unknown array type!");
9504 S += '0';
9505 }
9506
9507 getObjCEncodingForTypeImpl(
9508 AT->getElementType(), S,
9509 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
9510 NotEncodedT);
9511 S += ']';
9512 }
9513 return;
9514 }
9515
9516 case Type::FunctionNoProto:
9517 case Type::FunctionProto:
9518 S += '?';
9519 return;
9520
9521 case Type::Record: {
9522 RecordDecl *RDecl = cast<RecordType>(CT)->getOriginalDecl();
9523 S += RDecl->isUnion() ? '(' : '{';
9524 // Anonymous structures print as '?'
9525 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
9526 S += II->getName();
9527 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
9528 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
9529 llvm::raw_string_ostream OS(S);
9530 printTemplateArgumentList(OS, TemplateArgs.asArray(),
9532 }
9533 } else {
9534 S += '?';
9535 }
9536 if (Options.ExpandStructures()) {
9537 S += '=';
9538 if (!RDecl->isUnion()) {
9539 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
9540 } else {
9541 for (const auto *Field : RDecl->fields()) {
9542 if (FD) {
9543 S += '"';
9544 S += Field->getNameAsString();
9545 S += '"';
9546 }
9547
9548 // Special case bit-fields.
9549 if (Field->isBitField()) {
9550 getObjCEncodingForTypeImpl(Field->getType(), S,
9551 ObjCEncOptions().setExpandStructures(),
9552 Field);
9553 } else {
9554 QualType qt = Field->getType();
9556 getObjCEncodingForTypeImpl(
9557 qt, S,
9558 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
9559 NotEncodedT);
9560 }
9561 }
9562 }
9563 }
9564 S += RDecl->isUnion() ? ')' : '}';
9565 return;
9566 }
9567
9568 case Type::BlockPointer: {
9569 const auto *BT = T->castAs<BlockPointerType>();
9570 S += "@?"; // Unlike a pointer-to-function, which is "^?".
9571 if (Options.EncodeBlockParameters()) {
9572 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
9573
9574 S += '<';
9575 // Block return type
9576 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
9577 Options.forComponentType(), FD, NotEncodedT);
9578 // Block self
9579 S += "@?";
9580 // Block parameters
9581 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
9582 for (const auto &I : FPT->param_types())
9583 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
9584 NotEncodedT);
9585 }
9586 S += '>';
9587 }
9588 return;
9589 }
9590
9591 case Type::ObjCObject: {
9592 // hack to match legacy encoding of *id and *Class
9594 if (Ty->isObjCIdType()) {
9595 S += "{objc_object=}";
9596 return;
9597 }
9598 else if (Ty->isObjCClassType()) {
9599 S += "{objc_class=}";
9600 return;
9601 }
9602 // TODO: Double check to make sure this intentionally falls through.
9603 [[fallthrough]];
9604 }
9605
9606 case Type::ObjCInterface: {
9607 // Ignore protocol qualifiers when mangling at this level.
9608 // @encode(class_name)
9609 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
9610 S += '{';
9611 S += OI->getObjCRuntimeNameAsString();
9612 if (Options.ExpandStructures()) {
9613 S += '=';
9615 DeepCollectObjCIvars(OI, true, Ivars);
9616 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
9617 const FieldDecl *Field = Ivars[i];
9618 if (Field->isBitField())
9619 getObjCEncodingForTypeImpl(Field->getType(), S,
9620 ObjCEncOptions().setExpandStructures(),
9621 Field);
9622 else
9623 getObjCEncodingForTypeImpl(Field->getType(), S,
9624 ObjCEncOptions().setExpandStructures(), FD,
9625 NotEncodedT);
9626 }
9627 }
9628 S += '}';
9629 return;
9630 }
9631
9632 case Type::ObjCObjectPointer: {
9633 const auto *OPT = T->castAs<ObjCObjectPointerType>();
9634 if (OPT->isObjCIdType()) {
9635 S += '@';
9636 return;
9637 }
9638
9639 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
9640 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
9641 // Since this is a binary compatibility issue, need to consult with
9642 // runtime folks. Fortunately, this is a *very* obscure construct.
9643 S += '#';
9644 return;
9645 }
9646
9647 if (OPT->isObjCQualifiedIdType()) {
9648 getObjCEncodingForTypeImpl(
9649 getObjCIdType(), S,
9650 Options.keepingOnly(ObjCEncOptions()
9651 .setExpandPointedToStructures()
9652 .setExpandStructures()),
9653 FD);
9654 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
9655 // Note that we do extended encoding of protocol qualifier list
9656 // Only when doing ivar or property encoding.
9657 S += '"';
9658 for (const auto *I : OPT->quals()) {
9659 S += '<';
9660 S += I->getObjCRuntimeNameAsString();
9661 S += '>';
9662 }
9663 S += '"';
9664 }
9665 return;
9666 }
9667
9668 S += '@';
9669 if (OPT->getInterfaceDecl() &&
9670 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
9671 S += '"';
9672 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
9673 for (const auto *I : OPT->quals()) {
9674 S += '<';
9675 S += I->getObjCRuntimeNameAsString();
9676 S += '>';
9677 }
9678 S += '"';
9679 }
9680 return;
9681 }
9682
9683 // gcc just blithely ignores member pointers.
9684 // FIXME: we should do better than that. 'M' is available.
9685 case Type::MemberPointer:
9686 // This matches gcc's encoding, even though technically it is insufficient.
9687 //FIXME. We should do a better job than gcc.
9688 case Type::Vector:
9689 case Type::ExtVector:
9690 // Until we have a coherent encoding of these three types, issue warning.
9691 if (NotEncodedT)
9692 *NotEncodedT = T;
9693 return;
9694
9695 case Type::ConstantMatrix:
9696 if (NotEncodedT)
9697 *NotEncodedT = T;
9698 return;
9699
9700 case Type::BitInt:
9701 if (NotEncodedT)
9702 *NotEncodedT = T;
9703 return;
9704
9705 // We could see an undeduced auto type here during error recovery.
9706 // Just ignore it.
9707 case Type::Auto:
9708 case Type::DeducedTemplateSpecialization:
9709 return;
9710
9711 case Type::HLSLAttributedResource:
9712 case Type::HLSLInlineSpirv:
9713 llvm_unreachable("unexpected type");
9714
9715 case Type::ArrayParameter:
9716 case Type::Pipe:
9717#define ABSTRACT_TYPE(KIND, BASE)
9718#define TYPE(KIND, BASE)
9719#define DEPENDENT_TYPE(KIND, BASE) \
9720 case Type::KIND:
9721#define NON_CANONICAL_TYPE(KIND, BASE) \
9722 case Type::KIND:
9723#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
9724 case Type::KIND:
9725#include "clang/AST/TypeNodes.inc"
9726 llvm_unreachable("@encode for dependent type!");
9727 }
9728 llvm_unreachable("bad type kind!");
9729}
9730
9731void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
9732 std::string &S,
9733 const FieldDecl *FD,
9734 bool includeVBases,
9735 QualType *NotEncodedT) const {
9736 assert(RDecl && "Expected non-null RecordDecl");
9737 assert(!RDecl->isUnion() && "Should not be called for unions");
9738 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
9739 return;
9740
9741 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
9742 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
9743 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
9744
9745 if (CXXRec) {
9746 for (const auto &BI : CXXRec->bases()) {
9747 if (!BI.isVirtual()) {
9748 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9749 if (base->isEmpty())
9750 continue;
9751 uint64_t offs = toBits(layout.getBaseClassOffset(base));
9752 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9753 std::make_pair(offs, base));
9754 }
9755 }
9756 }
9757
9758 for (FieldDecl *Field : RDecl->fields()) {
9759 if (!Field->isZeroLengthBitField() && Field->isZeroSize(*this))
9760 continue;
9761 uint64_t offs = layout.getFieldOffset(Field->getFieldIndex());
9762 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9763 std::make_pair(offs, Field));
9764 }
9765
9766 if (CXXRec && includeVBases) {
9767 for (const auto &BI : CXXRec->vbases()) {
9768 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9769 if (base->isEmpty())
9770 continue;
9771 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
9772 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
9773 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
9774 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
9775 std::make_pair(offs, base));
9776 }
9777 }
9778
9779 CharUnits size;
9780 if (CXXRec) {
9781 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
9782 } else {
9783 size = layout.getSize();
9784 }
9785
9786#ifndef NDEBUG
9787 uint64_t CurOffs = 0;
9788#endif
9789 std::multimap<uint64_t, NamedDecl *>::iterator
9790 CurLayObj = FieldOrBaseOffsets.begin();
9791
9792 if (CXXRec && CXXRec->isDynamicClass() &&
9793 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
9794 if (FD) {
9795 S += "\"_vptr$";
9796 std::string recname = CXXRec->getNameAsString();
9797 if (recname.empty()) recname = "?";
9798 S += recname;
9799 S += '"';
9800 }
9801 S += "^^?";
9802#ifndef NDEBUG
9803 CurOffs += getTypeSize(VoidPtrTy);
9804#endif
9805 }
9806
9807 if (!RDecl->hasFlexibleArrayMember()) {
9808 // Mark the end of the structure.
9809 uint64_t offs = toBits(size);
9810 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9811 std::make_pair(offs, nullptr));
9812 }
9813
9814 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
9815#ifndef NDEBUG
9816 assert(CurOffs <= CurLayObj->first);
9817 if (CurOffs < CurLayObj->first) {
9818 uint64_t padding = CurLayObj->first - CurOffs;
9819 // FIXME: There doesn't seem to be a way to indicate in the encoding that
9820 // packing/alignment of members is different that normal, in which case
9821 // the encoding will be out-of-sync with the real layout.
9822 // If the runtime switches to just consider the size of types without
9823 // taking into account alignment, we could make padding explicit in the
9824 // encoding (e.g. using arrays of chars). The encoding strings would be
9825 // longer then though.
9826 CurOffs += padding;
9827 }
9828#endif
9829
9830 NamedDecl *dcl = CurLayObj->second;
9831 if (!dcl)
9832 break; // reached end of structure.
9833
9834 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
9835 // We expand the bases without their virtual bases since those are going
9836 // in the initial structure. Note that this differs from gcc which
9837 // expands virtual bases each time one is encountered in the hierarchy,
9838 // making the encoding type bigger than it really is.
9839 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
9840 NotEncodedT);
9841 assert(!base->isEmpty());
9842#ifndef NDEBUG
9843 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
9844#endif
9845 } else {
9846 const auto *field = cast<FieldDecl>(dcl);
9847 if (FD) {
9848 S += '"';
9849 S += field->getNameAsString();
9850 S += '"';
9851 }
9852
9853 if (field->isBitField()) {
9854 EncodeBitField(this, S, field->getType(), field);
9855#ifndef NDEBUG
9856 CurOffs += field->getBitWidthValue();
9857#endif
9858 } else {
9859 QualType qt = field->getType();
9861 getObjCEncodingForTypeImpl(
9862 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
9863 FD, NotEncodedT);
9864#ifndef NDEBUG
9865 CurOffs += getTypeSize(field->getType());
9866#endif
9867 }
9868 }
9869 }
9870}
9871
9873 std::string& S) const {
9874 if (QT & Decl::OBJC_TQ_In)
9875 S += 'n';
9876 if (QT & Decl::OBJC_TQ_Inout)
9877 S += 'N';
9878 if (QT & Decl::OBJC_TQ_Out)
9879 S += 'o';
9880 if (QT & Decl::OBJC_TQ_Bycopy)
9881 S += 'O';
9882 if (QT & Decl::OBJC_TQ_Byref)
9883 S += 'R';
9884 if (QT & Decl::OBJC_TQ_Oneway)
9885 S += 'V';
9886}
9887
9889 if (!ObjCIdDecl) {
9892 ObjCIdDecl = buildImplicitTypedef(T, "id");
9893 }
9894 return ObjCIdDecl;
9895}
9896
9898 if (!ObjCSelDecl) {
9900 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
9901 }
9902 return ObjCSelDecl;
9903}
9904
9906 if (!ObjCClassDecl) {
9909 ObjCClassDecl = buildImplicitTypedef(T, "Class");
9910 }
9911 return ObjCClassDecl;
9912}
9913
9915 if (!ObjCProtocolClassDecl) {
9916 ObjCProtocolClassDecl
9919 &Idents.get("Protocol"),
9920 /*typeParamList=*/nullptr,
9921 /*PrevDecl=*/nullptr,
9922 SourceLocation(), true);
9923 }
9924
9925 return ObjCProtocolClassDecl;
9926}
9927
9929 if (!getLangOpts().PointerAuthObjcInterfaceSel)
9930 return PointerAuthQualifier();
9932 getLangOpts().PointerAuthObjcInterfaceSelKey,
9933 /*isAddressDiscriminated=*/true, SelPointerConstantDiscriminator,
9935 /*isIsaPointer=*/false,
9936 /*authenticatesNullValues=*/false);
9937}
9938
9939//===----------------------------------------------------------------------===//
9940// __builtin_va_list Construction Functions
9941//===----------------------------------------------------------------------===//
9942
9944 StringRef Name) {
9945 // typedef char* __builtin[_ms]_va_list;
9946 QualType T = Context->getPointerType(Context->CharTy);
9947 return Context->buildImplicitTypedef(T, Name);
9948}
9949
9951 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
9952}
9953
9955 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
9956}
9957
9959 // typedef void* __builtin_va_list;
9960 QualType T = Context->getPointerType(Context->VoidTy);
9961 return Context->buildImplicitTypedef(T, "__builtin_va_list");
9962}
9963
9964static TypedefDecl *
9966 // struct __va_list
9967 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
9968 if (Context->getLangOpts().CPlusPlus) {
9969 // namespace std { struct __va_list {
9970 auto *NS = NamespaceDecl::Create(
9971 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(),
9972 /*Inline=*/false, SourceLocation(), SourceLocation(),
9973 &Context->Idents.get("std"),
9974 /*PrevDecl=*/nullptr, /*Nested=*/false);
9975 NS->setImplicit();
9976 VaListTagDecl->setDeclContext(NS);
9977 }
9978
9979 VaListTagDecl->startDefinition();
9980
9981 const size_t NumFields = 5;
9982 QualType FieldTypes[NumFields];
9983 const char *FieldNames[NumFields];
9984
9985 // void *__stack;
9986 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
9987 FieldNames[0] = "__stack";
9988
9989 // void *__gr_top;
9990 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
9991 FieldNames[1] = "__gr_top";
9992
9993 // void *__vr_top;
9994 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9995 FieldNames[2] = "__vr_top";
9996
9997 // int __gr_offs;
9998 FieldTypes[3] = Context->IntTy;
9999 FieldNames[3] = "__gr_offs";
10000
10001 // int __vr_offs;
10002 FieldTypes[4] = Context->IntTy;
10003 FieldNames[4] = "__vr_offs";
10004
10005 // Create fields
10006 for (unsigned i = 0; i < NumFields; ++i) {
10007 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10008 VaListTagDecl,
10011 &Context->Idents.get(FieldNames[i]),
10012 FieldTypes[i], /*TInfo=*/nullptr,
10013 /*BitWidth=*/nullptr,
10014 /*Mutable=*/false,
10015 ICIS_NoInit);
10016 Field->setAccess(AS_public);
10017 VaListTagDecl->addDecl(Field);
10018 }
10019 VaListTagDecl->completeDefinition();
10020 Context->VaListTagDecl = VaListTagDecl;
10021 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10022
10023 // } __builtin_va_list;
10024 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
10025}
10026
10028 // typedef struct __va_list_tag {
10029 RecordDecl *VaListTagDecl;
10030
10031 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10032 VaListTagDecl->startDefinition();
10033
10034 const size_t NumFields = 5;
10035 QualType FieldTypes[NumFields];
10036 const char *FieldNames[NumFields];
10037
10038 // unsigned char gpr;
10039 FieldTypes[0] = Context->UnsignedCharTy;
10040 FieldNames[0] = "gpr";
10041
10042 // unsigned char fpr;
10043 FieldTypes[1] = Context->UnsignedCharTy;
10044 FieldNames[1] = "fpr";
10045
10046 // unsigned short reserved;
10047 FieldTypes[2] = Context->UnsignedShortTy;
10048 FieldNames[2] = "reserved";
10049
10050 // void* overflow_arg_area;
10051 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10052 FieldNames[3] = "overflow_arg_area";
10053
10054 // void* reg_save_area;
10055 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
10056 FieldNames[4] = "reg_save_area";
10057
10058 // Create fields
10059 for (unsigned i = 0; i < NumFields; ++i) {
10060 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
10063 &Context->Idents.get(FieldNames[i]),
10064 FieldTypes[i], /*TInfo=*/nullptr,
10065 /*BitWidth=*/nullptr,
10066 /*Mutable=*/false,
10067 ICIS_NoInit);
10068 Field->setAccess(AS_public);
10069 VaListTagDecl->addDecl(Field);
10070 }
10071 VaListTagDecl->completeDefinition();
10072 Context->VaListTagDecl = VaListTagDecl;
10073 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10074
10075 // } __va_list_tag;
10076 TypedefDecl *VaListTagTypedefDecl =
10077 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10078
10079 QualType VaListTagTypedefType =
10081 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10082
10083 // typedef __va_list_tag __builtin_va_list[1];
10084 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10085 QualType VaListTagArrayType = Context->getConstantArrayType(
10086 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10087 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10088}
10089
10090static TypedefDecl *
10092 // struct __va_list_tag {
10093 RecordDecl *VaListTagDecl;
10094 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10095 VaListTagDecl->startDefinition();
10096
10097 const size_t NumFields = 4;
10098 QualType FieldTypes[NumFields];
10099 const char *FieldNames[NumFields];
10100
10101 // unsigned gp_offset;
10102 FieldTypes[0] = Context->UnsignedIntTy;
10103 FieldNames[0] = "gp_offset";
10104
10105 // unsigned fp_offset;
10106 FieldTypes[1] = Context->UnsignedIntTy;
10107 FieldNames[1] = "fp_offset";
10108
10109 // void* overflow_arg_area;
10110 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10111 FieldNames[2] = "overflow_arg_area";
10112
10113 // void* reg_save_area;
10114 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10115 FieldNames[3] = "reg_save_area";
10116
10117 // Create fields
10118 for (unsigned i = 0; i < NumFields; ++i) {
10119 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10120 VaListTagDecl,
10123 &Context->Idents.get(FieldNames[i]),
10124 FieldTypes[i], /*TInfo=*/nullptr,
10125 /*BitWidth=*/nullptr,
10126 /*Mutable=*/false,
10127 ICIS_NoInit);
10128 Field->setAccess(AS_public);
10129 VaListTagDecl->addDecl(Field);
10130 }
10131 VaListTagDecl->completeDefinition();
10132 Context->VaListTagDecl = VaListTagDecl;
10133 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10134
10135 // };
10136
10137 // typedef struct __va_list_tag __builtin_va_list[1];
10138 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10139 QualType VaListTagArrayType = Context->getConstantArrayType(
10140 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10141 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10142}
10143
10144static TypedefDecl *
10146 // struct __va_list
10147 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
10148 if (Context->getLangOpts().CPlusPlus) {
10149 // namespace std { struct __va_list {
10150 NamespaceDecl *NS;
10151 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
10152 Context->getTranslationUnitDecl(),
10153 /*Inline=*/false, SourceLocation(),
10154 SourceLocation(), &Context->Idents.get("std"),
10155 /*PrevDecl=*/nullptr, /*Nested=*/false);
10156 NS->setImplicit();
10157 VaListDecl->setDeclContext(NS);
10158 }
10159
10160 VaListDecl->startDefinition();
10161
10162 // void * __ap;
10163 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10164 VaListDecl,
10167 &Context->Idents.get("__ap"),
10168 Context->getPointerType(Context->VoidTy),
10169 /*TInfo=*/nullptr,
10170 /*BitWidth=*/nullptr,
10171 /*Mutable=*/false,
10172 ICIS_NoInit);
10173 Field->setAccess(AS_public);
10174 VaListDecl->addDecl(Field);
10175
10176 // };
10177 VaListDecl->completeDefinition();
10178 Context->VaListTagDecl = VaListDecl;
10179
10180 // typedef struct __va_list __builtin_va_list;
10181 CanQualType T = Context->getCanonicalTagType(VaListDecl);
10182 return Context->buildImplicitTypedef(T, "__builtin_va_list");
10183}
10184
10185static TypedefDecl *
10187 // struct __va_list_tag {
10188 RecordDecl *VaListTagDecl;
10189 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10190 VaListTagDecl->startDefinition();
10191
10192 const size_t NumFields = 4;
10193 QualType FieldTypes[NumFields];
10194 const char *FieldNames[NumFields];
10195
10196 // long __gpr;
10197 FieldTypes[0] = Context->LongTy;
10198 FieldNames[0] = "__gpr";
10199
10200 // long __fpr;
10201 FieldTypes[1] = Context->LongTy;
10202 FieldNames[1] = "__fpr";
10203
10204 // void *__overflow_arg_area;
10205 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10206 FieldNames[2] = "__overflow_arg_area";
10207
10208 // void *__reg_save_area;
10209 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10210 FieldNames[3] = "__reg_save_area";
10211
10212 // Create fields
10213 for (unsigned i = 0; i < NumFields; ++i) {
10214 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10215 VaListTagDecl,
10218 &Context->Idents.get(FieldNames[i]),
10219 FieldTypes[i], /*TInfo=*/nullptr,
10220 /*BitWidth=*/nullptr,
10221 /*Mutable=*/false,
10222 ICIS_NoInit);
10223 Field->setAccess(AS_public);
10224 VaListTagDecl->addDecl(Field);
10225 }
10226 VaListTagDecl->completeDefinition();
10227 Context->VaListTagDecl = VaListTagDecl;
10228 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10229
10230 // };
10231
10232 // typedef __va_list_tag __builtin_va_list[1];
10233 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10234 QualType VaListTagArrayType = Context->getConstantArrayType(
10235 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10236
10237 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10238}
10239
10241 // typedef struct __va_list_tag {
10242 RecordDecl *VaListTagDecl;
10243 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10244 VaListTagDecl->startDefinition();
10245
10246 const size_t NumFields = 3;
10247 QualType FieldTypes[NumFields];
10248 const char *FieldNames[NumFields];
10249
10250 // void *CurrentSavedRegisterArea;
10251 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
10252 FieldNames[0] = "__current_saved_reg_area_pointer";
10253
10254 // void *SavedRegAreaEnd;
10255 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
10256 FieldNames[1] = "__saved_reg_area_end_pointer";
10257
10258 // void *OverflowArea;
10259 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10260 FieldNames[2] = "__overflow_area_pointer";
10261
10262 // Create fields
10263 for (unsigned i = 0; i < NumFields; ++i) {
10265 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
10266 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
10267 /*TInfo=*/nullptr,
10268 /*BitWidth=*/nullptr,
10269 /*Mutable=*/false, ICIS_NoInit);
10270 Field->setAccess(AS_public);
10271 VaListTagDecl->addDecl(Field);
10272 }
10273 VaListTagDecl->completeDefinition();
10274 Context->VaListTagDecl = VaListTagDecl;
10275 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10276
10277 // } __va_list_tag;
10278 TypedefDecl *VaListTagTypedefDecl =
10279 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10280
10281 QualType VaListTagTypedefType =
10283 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10284
10285 // typedef __va_list_tag __builtin_va_list[1];
10286 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10287 QualType VaListTagArrayType = Context->getConstantArrayType(
10288 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10289
10290 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10291}
10292
10293static TypedefDecl *
10295 // typedef struct __va_list_tag {
10296 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10297
10298 VaListTagDecl->startDefinition();
10299
10300 // int* __va_stk;
10301 // int* __va_reg;
10302 // int __va_ndx;
10303 constexpr size_t NumFields = 3;
10304 QualType FieldTypes[NumFields] = {Context->getPointerType(Context->IntTy),
10305 Context->getPointerType(Context->IntTy),
10306 Context->IntTy};
10307 const char *FieldNames[NumFields] = {"__va_stk", "__va_reg", "__va_ndx"};
10308
10309 // Create fields
10310 for (unsigned i = 0; i < NumFields; ++i) {
10312 *Context, VaListTagDecl, SourceLocation(), SourceLocation(),
10313 &Context->Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
10314 /*BitWidth=*/nullptr,
10315 /*Mutable=*/false, ICIS_NoInit);
10316 Field->setAccess(AS_public);
10317 VaListTagDecl->addDecl(Field);
10318 }
10319 VaListTagDecl->completeDefinition();
10320 Context->VaListTagDecl = VaListTagDecl;
10321 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10322
10323 // } __va_list_tag;
10324 TypedefDecl *VaListTagTypedefDecl =
10325 Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
10326
10327 return VaListTagTypedefDecl;
10328}
10329
10332 switch (Kind) {
10334 return CreateCharPtrBuiltinVaListDecl(Context);
10336 return CreateVoidPtrBuiltinVaListDecl(Context);
10338 return CreateAArch64ABIBuiltinVaListDecl(Context);
10340 return CreatePowerABIBuiltinVaListDecl(Context);
10342 return CreateX86_64ABIBuiltinVaListDecl(Context);
10344 return CreateAAPCSABIBuiltinVaListDecl(Context);
10346 return CreateSystemZBuiltinVaListDecl(Context);
10348 return CreateHexagonBuiltinVaListDecl(Context);
10350 return CreateXtensaABIBuiltinVaListDecl(Context);
10351 }
10352
10353 llvm_unreachable("Unhandled __builtin_va_list type kind");
10354}
10355
10357 if (!BuiltinVaListDecl) {
10358 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
10359 assert(BuiltinVaListDecl->isImplicit());
10360 }
10361
10362 return BuiltinVaListDecl;
10363}
10364
10366 // Force the creation of VaListTagDecl by building the __builtin_va_list
10367 // declaration.
10368 if (!VaListTagDecl)
10369 (void)getBuiltinVaListDecl();
10370
10371 return VaListTagDecl;
10372}
10373
10375 if (!BuiltinMSVaListDecl)
10376 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
10377
10378 return BuiltinMSVaListDecl;
10379}
10380
10382 // Allow redecl custom type checking builtin for HLSL.
10383 if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
10385 return true;
10386 // Allow redecl custom type checking builtin for SPIR-V.
10387 if (getTargetInfo().getTriple().isSPIROrSPIRV() &&
10390 return true;
10392}
10393
10395 assert(ObjCConstantStringType.isNull() &&
10396 "'NSConstantString' type already set!");
10397
10398 ObjCConstantStringType = getObjCInterfaceType(Decl);
10399}
10400
10401/// Retrieve the template name that corresponds to a non-empty
10402/// lookup.
10405 UnresolvedSetIterator End) const {
10406 unsigned size = End - Begin;
10407 assert(size > 1 && "set is not overloaded!");
10408
10409 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
10410 size * sizeof(FunctionTemplateDecl*));
10411 auto *OT = new (memory) OverloadedTemplateStorage(size);
10412
10413 NamedDecl **Storage = OT->getStorage();
10414 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
10415 NamedDecl *D = *I;
10416 assert(isa<FunctionTemplateDecl>(D) ||
10417 isa<UnresolvedUsingValueDecl>(D) ||
10418 (isa<UsingShadowDecl>(D) &&
10419 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
10420 *Storage++ = D;
10421 }
10422
10423 return TemplateName(OT);
10424}
10425
10426/// Retrieve a template name representing an unqualified-id that has been
10427/// assumed to name a template for ADL purposes.
10429 auto *OT = new (*this) AssumedTemplateStorage(Name);
10430 return TemplateName(OT);
10431}
10432
10433/// Retrieve the template name that represents a qualified
10434/// template name such as \c std::vector.
10436 bool TemplateKeyword,
10437 TemplateName Template) const {
10438 assert(Template.getKind() == TemplateName::Template ||
10440
10441 if (Template.getAsTemplateDecl()->getKind() == Decl::TemplateTemplateParm) {
10442 assert(!Qualifier && "unexpected qualified template template parameter");
10443 assert(TemplateKeyword == false);
10444 return Template;
10445 }
10446
10447 // FIXME: Canonicalization?
10448 llvm::FoldingSetNodeID ID;
10449 QualifiedTemplateName::Profile(ID, Qualifier, TemplateKeyword, Template);
10450
10451 void *InsertPos = nullptr;
10453 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
10454 if (!QTN) {
10455 QTN = new (*this, alignof(QualifiedTemplateName))
10456 QualifiedTemplateName(Qualifier, TemplateKeyword, Template);
10457 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
10458 }
10459
10460 return TemplateName(QTN);
10461}
10462
10463/// Retrieve the template name that represents a dependent
10464/// template name such as \c MetaFun::template operator+.
10467 llvm::FoldingSetNodeID ID;
10468 S.Profile(ID);
10469
10470 void *InsertPos = nullptr;
10471 if (DependentTemplateName *QTN =
10472 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos))
10473 return TemplateName(QTN);
10474
10476 new (*this, alignof(DependentTemplateName)) DependentTemplateName(S);
10477 DependentTemplateNames.InsertNode(QTN, InsertPos);
10478 return TemplateName(QTN);
10479}
10480
10482 Decl *AssociatedDecl,
10483 unsigned Index,
10484 UnsignedOrNone PackIndex,
10485 bool Final) const {
10486 llvm::FoldingSetNodeID ID;
10487 SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
10488 Index, PackIndex, Final);
10489
10490 void *insertPos = nullptr;
10492 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
10493
10494 if (!subst) {
10495 subst = new (*this) SubstTemplateTemplateParmStorage(
10496 Replacement, AssociatedDecl, Index, PackIndex, Final);
10497 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
10498 }
10499
10500 return TemplateName(subst);
10501}
10502
10505 Decl *AssociatedDecl,
10506 unsigned Index, bool Final) const {
10507 auto &Self = const_cast<ASTContext &>(*this);
10508 llvm::FoldingSetNodeID ID;
10510 AssociatedDecl, Index, Final);
10511
10512 void *InsertPos = nullptr;
10514 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
10515
10516 if (!Subst) {
10517 Subst = new (*this) SubstTemplateTemplateParmPackStorage(
10518 ArgPack.pack_elements(), AssociatedDecl, Index, Final);
10519 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
10520 }
10521
10522 return TemplateName(Subst);
10523}
10524
10525/// Retrieve the template name that represents a template name
10526/// deduced from a specialization.
10529 DefaultArguments DefaultArgs) const {
10530 if (!DefaultArgs)
10531 return Underlying;
10532
10533 llvm::FoldingSetNodeID ID;
10534 DeducedTemplateStorage::Profile(ID, *this, Underlying, DefaultArgs);
10535
10536 void *InsertPos = nullptr;
10538 DeducedTemplates.FindNodeOrInsertPos(ID, InsertPos);
10539 if (!DTS) {
10540 void *Mem = Allocate(sizeof(DeducedTemplateStorage) +
10541 sizeof(TemplateArgument) * DefaultArgs.Args.size(),
10542 alignof(DeducedTemplateStorage));
10543 DTS = new (Mem) DeducedTemplateStorage(Underlying, DefaultArgs);
10544 DeducedTemplates.InsertNode(DTS, InsertPos);
10545 }
10546 return TemplateName(DTS);
10547}
10548
10549/// getFromTargetType - Given one of the integer types provided by
10550/// TargetInfo, produce the corresponding type. The unsigned @p Type
10551/// is actually a value of type @c TargetInfo::IntType.
10552CanQualType ASTContext::getFromTargetType(unsigned Type) const {
10553 switch (Type) {
10554 case TargetInfo::NoInt: return {};
10557 case TargetInfo::SignedShort: return ShortTy;
10559 case TargetInfo::SignedInt: return IntTy;
10561 case TargetInfo::SignedLong: return LongTy;
10565 }
10566
10567 llvm_unreachable("Unhandled TargetInfo::IntType value");
10568}
10569
10570//===----------------------------------------------------------------------===//
10571// Type Predicates.
10572//===----------------------------------------------------------------------===//
10573
10574/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
10575/// garbage collection attribute.
10576///
10578 if (getLangOpts().getGC() == LangOptions::NonGC)
10579 return Qualifiers::GCNone;
10580
10581 assert(getLangOpts().ObjC);
10582 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
10583
10584 // Default behaviour under objective-C's gc is for ObjC pointers
10585 // (or pointers to them) be treated as though they were declared
10586 // as __strong.
10587 if (GCAttrs == Qualifiers::GCNone) {
10589 return Qualifiers::Strong;
10590 else if (Ty->isPointerType())
10592 } else {
10593 // It's not valid to set GC attributes on anything that isn't a
10594 // pointer.
10595#ifndef NDEBUG
10597 while (const auto *AT = dyn_cast<ArrayType>(CT))
10598 CT = AT->getElementType();
10599 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
10600#endif
10601 }
10602 return GCAttrs;
10603}
10604
10605//===----------------------------------------------------------------------===//
10606// Type Compatibility Testing
10607//===----------------------------------------------------------------------===//
10608
10609/// areCompatVectorTypes - Return true if the two specified vector types are
10610/// compatible.
10611static bool areCompatVectorTypes(const VectorType *LHS,
10612 const VectorType *RHS) {
10613 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10614 return LHS->getElementType() == RHS->getElementType() &&
10615 LHS->getNumElements() == RHS->getNumElements();
10616}
10617
10618/// areCompatMatrixTypes - Return true if the two specified matrix types are
10619/// compatible.
10621 const ConstantMatrixType *RHS) {
10622 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10623 return LHS->getElementType() == RHS->getElementType() &&
10624 LHS->getNumRows() == RHS->getNumRows() &&
10625 LHS->getNumColumns() == RHS->getNumColumns();
10626}
10627
10629 QualType SecondVec) {
10630 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
10631 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
10632
10633 if (hasSameUnqualifiedType(FirstVec, SecondVec))
10634 return true;
10635
10636 // Treat Neon vector types and most AltiVec vector types as if they are the
10637 // equivalent GCC vector types.
10638 const auto *First = FirstVec->castAs<VectorType>();
10639 const auto *Second = SecondVec->castAs<VectorType>();
10640 if (First->getNumElements() == Second->getNumElements() &&
10641 hasSameType(First->getElementType(), Second->getElementType()) &&
10642 First->getVectorKind() != VectorKind::AltiVecPixel &&
10643 First->getVectorKind() != VectorKind::AltiVecBool &&
10646 First->getVectorKind() != VectorKind::SveFixedLengthData &&
10647 First->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10650 First->getVectorKind() != VectorKind::RVVFixedLengthData &&
10652 First->getVectorKind() != VectorKind::RVVFixedLengthMask &&
10654 First->getVectorKind() != VectorKind::RVVFixedLengthMask_1 &&
10656 First->getVectorKind() != VectorKind::RVVFixedLengthMask_2 &&
10658 First->getVectorKind() != VectorKind::RVVFixedLengthMask_4 &&
10660 return true;
10661
10662 return false;
10663}
10664
10665/// getRVVTypeSize - Return RVV vector register size.
10666static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) {
10667 assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type");
10668 auto VScale = Context.getTargetInfo().getVScaleRange(
10670 if (!VScale)
10671 return 0;
10672
10674
10675 uint64_t EltSize = Context.getTypeSize(Info.ElementType);
10676 if (Info.ElementType == Context.BoolTy)
10677 EltSize = 1;
10678
10679 uint64_t MinElts = Info.EC.getKnownMinValue();
10680 return VScale->first * MinElts * EltSize;
10681}
10682
10684 QualType SecondType) {
10685 assert(
10686 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10687 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10688 "Expected RVV builtin type and vector type!");
10689
10690 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10691 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10692 if (const auto *VT = SecondType->getAs<VectorType>()) {
10693 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask) {
10695 return FirstType->isRVVVLSBuiltinType() &&
10696 Info.ElementType == BoolTy &&
10697 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)));
10698 }
10699 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1) {
10701 return FirstType->isRVVVLSBuiltinType() &&
10702 Info.ElementType == BoolTy &&
10703 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT) * 8));
10704 }
10705 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2) {
10707 return FirstType->isRVVVLSBuiltinType() &&
10708 Info.ElementType == BoolTy &&
10709 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 4);
10710 }
10711 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10713 return FirstType->isRVVVLSBuiltinType() &&
10714 Info.ElementType == BoolTy &&
10715 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 2);
10716 }
10717 if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
10718 VT->getVectorKind() == VectorKind::Generic)
10719 return FirstType->isRVVVLSBuiltinType() &&
10720 getTypeSize(SecondType) == getRVVTypeSize(*this, BT) &&
10721 hasSameType(VT->getElementType(),
10722 getBuiltinVectorTypeInfo(BT).ElementType);
10723 }
10724 }
10725 return false;
10726 };
10727
10728 return IsValidCast(FirstType, SecondType) ||
10729 IsValidCast(SecondType, FirstType);
10730}
10731
10733 QualType SecondType) {
10734 assert(
10735 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10736 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10737 "Expected RVV builtin type and vector type!");
10738
10739 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10740 const auto *BT = FirstType->getAs<BuiltinType>();
10741 if (!BT)
10742 return false;
10743
10744 if (!BT->isRVVVLSBuiltinType())
10745 return false;
10746
10747 const auto *VecTy = SecondType->getAs<VectorType>();
10748 if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) {
10750 getLangOpts().getLaxVectorConversions();
10751
10752 // If __riscv_v_fixed_vlen != N do not allow vector lax conversion.
10753 if (getTypeSize(SecondType) != getRVVTypeSize(*this, BT))
10754 return false;
10755
10756 // If -flax-vector-conversions=all is specified, the types are
10757 // certainly compatible.
10759 return true;
10760
10761 // If -flax-vector-conversions=integer is specified, the types are
10762 // compatible if the elements are integer types.
10764 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10765 FirstType->getRVVEltType(*this)->isIntegerType();
10766 }
10767
10768 return false;
10769 };
10770
10771 return IsLaxCompatible(FirstType, SecondType) ||
10772 IsLaxCompatible(SecondType, FirstType);
10773}
10774
10776 while (true) {
10777 // __strong id
10778 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
10779 if (Attr->getAttrKind() == attr::ObjCOwnership)
10780 return true;
10781
10782 Ty = Attr->getModifiedType();
10783
10784 // X *__strong (...)
10785 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
10786 Ty = Paren->getInnerType();
10787
10788 // We do not want to look through typedefs, typeof(expr),
10789 // typeof(type), or any other way that the type is somehow
10790 // abstracted.
10791 } else {
10792 return false;
10793 }
10794 }
10795}
10796
10797//===----------------------------------------------------------------------===//
10798// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
10799//===----------------------------------------------------------------------===//
10800
10801/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
10802/// inheritance hierarchy of 'rProto'.
10803bool
10805 ObjCProtocolDecl *rProto) const {
10806 if (declaresSameEntity(lProto, rProto))
10807 return true;
10808 for (auto *PI : rProto->protocols())
10809 if (ProtocolCompatibleWithProtocol(lProto, PI))
10810 return true;
10811 return false;
10812}
10813
10814/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
10815/// Class<pr1, ...>.
10817 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
10818 for (auto *lhsProto : lhs->quals()) {
10819 bool match = false;
10820 for (auto *rhsProto : rhs->quals()) {
10821 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
10822 match = true;
10823 break;
10824 }
10825 }
10826 if (!match)
10827 return false;
10828 }
10829 return true;
10830}
10831
10832/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
10833/// ObjCQualifiedIDType.
10835 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
10836 bool compare) {
10837 // Allow id<P..> and an 'id' in all cases.
10838 if (lhs->isObjCIdType() || rhs->isObjCIdType())
10839 return true;
10840
10841 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
10842 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
10844 return false;
10845
10846 if (lhs->isObjCQualifiedIdType()) {
10847 if (rhs->qual_empty()) {
10848 // If the RHS is a unqualified interface pointer "NSString*",
10849 // make sure we check the class hierarchy.
10850 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10851 for (auto *I : lhs->quals()) {
10852 // when comparing an id<P> on lhs with a static type on rhs,
10853 // see if static class implements all of id's protocols, directly or
10854 // through its super class and categories.
10855 if (!rhsID->ClassImplementsProtocol(I, true))
10856 return false;
10857 }
10858 }
10859 // If there are no qualifiers and no interface, we have an 'id'.
10860 return true;
10861 }
10862 // Both the right and left sides have qualifiers.
10863 for (auto *lhsProto : lhs->quals()) {
10864 bool match = false;
10865
10866 // when comparing an id<P> on lhs with a static type on rhs,
10867 // see if static class implements all of id's protocols, directly or
10868 // through its super class and categories.
10869 for (auto *rhsProto : rhs->quals()) {
10870 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10871 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10872 match = true;
10873 break;
10874 }
10875 }
10876 // If the RHS is a qualified interface pointer "NSString<P>*",
10877 // make sure we check the class hierarchy.
10878 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10879 for (auto *I : lhs->quals()) {
10880 // when comparing an id<P> on lhs with a static type on rhs,
10881 // see if static class implements all of id's protocols, directly or
10882 // through its super class and categories.
10883 if (rhsID->ClassImplementsProtocol(I, true)) {
10884 match = true;
10885 break;
10886 }
10887 }
10888 }
10889 if (!match)
10890 return false;
10891 }
10892
10893 return true;
10894 }
10895
10896 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
10897
10898 if (lhs->getInterfaceType()) {
10899 // If both the right and left sides have qualifiers.
10900 for (auto *lhsProto : lhs->quals()) {
10901 bool match = false;
10902
10903 // when comparing an id<P> on rhs with a static type on lhs,
10904 // see if static class implements all of id's protocols, directly or
10905 // through its super class and categories.
10906 // First, lhs protocols in the qualifier list must be found, direct
10907 // or indirect in rhs's qualifier list or it is a mismatch.
10908 for (auto *rhsProto : rhs->quals()) {
10909 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10910 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10911 match = true;
10912 break;
10913 }
10914 }
10915 if (!match)
10916 return false;
10917 }
10918
10919 // Static class's protocols, or its super class or category protocols
10920 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
10921 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
10922 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
10923 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
10924 // This is rather dubious but matches gcc's behavior. If lhs has
10925 // no type qualifier and its class has no static protocol(s)
10926 // assume that it is mismatch.
10927 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
10928 return false;
10929 for (auto *lhsProto : LHSInheritedProtocols) {
10930 bool match = false;
10931 for (auto *rhsProto : rhs->quals()) {
10932 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10933 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10934 match = true;
10935 break;
10936 }
10937 }
10938 if (!match)
10939 return false;
10940 }
10941 }
10942 return true;
10943 }
10944 return false;
10945}
10946
10947/// canAssignObjCInterfaces - Return true if the two interface types are
10948/// compatible for assignment from RHS to LHS. This handles validation of any
10949/// protocol qualifiers on the LHS or RHS.
10951 const ObjCObjectPointerType *RHSOPT) {
10952 const ObjCObjectType* LHS = LHSOPT->getObjectType();
10953 const ObjCObjectType* RHS = RHSOPT->getObjectType();
10954
10955 // If either type represents the built-in 'id' type, return true.
10956 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
10957 return true;
10958
10959 // Function object that propagates a successful result or handles
10960 // __kindof types.
10961 auto finish = [&](bool succeeded) -> bool {
10962 if (succeeded)
10963 return true;
10964
10965 if (!RHS->isKindOfType())
10966 return false;
10967
10968 // Strip off __kindof and protocol qualifiers, then check whether
10969 // we can assign the other way.
10971 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
10972 };
10973
10974 // Casts from or to id<P> are allowed when the other side has compatible
10975 // protocols.
10976 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
10977 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
10978 }
10979
10980 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
10981 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
10982 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
10983 }
10984
10985 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
10986 if (LHS->isObjCClass() && RHS->isObjCClass()) {
10987 return true;
10988 }
10989
10990 // If we have 2 user-defined types, fall into that path.
10991 if (LHS->getInterface() && RHS->getInterface()) {
10992 return finish(canAssignObjCInterfaces(LHS, RHS));
10993 }
10994
10995 return false;
10996}
10997
10998/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
10999/// for providing type-safety for objective-c pointers used to pass/return
11000/// arguments in block literals. When passed as arguments, passing 'A*' where
11001/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
11002/// not OK. For the return type, the opposite is not OK.
11004 const ObjCObjectPointerType *LHSOPT,
11005 const ObjCObjectPointerType *RHSOPT,
11006 bool BlockReturnType) {
11007
11008 // Function object that propagates a successful result or handles
11009 // __kindof types.
11010 auto finish = [&](bool succeeded) -> bool {
11011 if (succeeded)
11012 return true;
11013
11014 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
11015 if (!Expected->isKindOfType())
11016 return false;
11017
11018 // Strip off __kindof and protocol qualifiers, then check whether
11019 // we can assign the other way.
11021 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
11022 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
11023 BlockReturnType);
11024 };
11025
11026 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
11027 return true;
11028
11029 if (LHSOPT->isObjCBuiltinType()) {
11030 return finish(RHSOPT->isObjCBuiltinType() ||
11031 RHSOPT->isObjCQualifiedIdType());
11032 }
11033
11034 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
11035 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
11036 // Use for block parameters previous type checking for compatibility.
11037 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
11038 // Or corrected type checking as in non-compat mode.
11039 (!BlockReturnType &&
11040 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
11041 else
11043 (BlockReturnType ? LHSOPT : RHSOPT),
11044 (BlockReturnType ? RHSOPT : LHSOPT), false));
11045 }
11046
11047 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
11048 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
11049 if (LHS && RHS) { // We have 2 user-defined types.
11050 if (LHS != RHS) {
11051 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
11052 return finish(BlockReturnType);
11053 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
11054 return finish(!BlockReturnType);
11055 }
11056 else
11057 return true;
11058 }
11059 return false;
11060}
11061
11062/// Comparison routine for Objective-C protocols to be used with
11063/// llvm::array_pod_sort.
11065 ObjCProtocolDecl * const *rhs) {
11066 return (*lhs)->getName().compare((*rhs)->getName());
11067}
11068
11069/// getIntersectionOfProtocols - This routine finds the intersection of set
11070/// of protocols inherited from two distinct objective-c pointer objects with
11071/// the given common base.
11072/// It is used to build composite qualifier list of the composite type of
11073/// the conditional expression involving two objective-c pointer objects.
11074static
11076 const ObjCInterfaceDecl *CommonBase,
11077 const ObjCObjectPointerType *LHSOPT,
11078 const ObjCObjectPointerType *RHSOPT,
11079 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
11080
11081 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11082 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11083 assert(LHS->getInterface() && "LHS must have an interface base");
11084 assert(RHS->getInterface() && "RHS must have an interface base");
11085
11086 // Add all of the protocols for the LHS.
11088
11089 // Start with the protocol qualifiers.
11090 for (auto *proto : LHS->quals()) {
11091 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
11092 }
11093
11094 // Also add the protocols associated with the LHS interface.
11095 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
11096
11097 // Add all of the protocols for the RHS.
11099
11100 // Start with the protocol qualifiers.
11101 for (auto *proto : RHS->quals()) {
11102 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
11103 }
11104
11105 // Also add the protocols associated with the RHS interface.
11106 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
11107
11108 // Compute the intersection of the collected protocol sets.
11109 for (auto *proto : LHSProtocolSet) {
11110 if (RHSProtocolSet.count(proto))
11111 IntersectionSet.push_back(proto);
11112 }
11113
11114 // Compute the set of protocols that is implied by either the common type or
11115 // the protocols within the intersection.
11117 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
11118
11119 // Remove any implied protocols from the list of inherited protocols.
11120 if (!ImpliedProtocols.empty()) {
11121 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool {
11122 return ImpliedProtocols.contains(proto);
11123 });
11124 }
11125
11126 // Sort the remaining protocols by name.
11127 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
11129}
11130
11131/// Determine whether the first type is a subtype of the second.
11133 QualType rhs) {
11134 // Common case: two object pointers.
11135 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
11136 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
11137 if (lhsOPT && rhsOPT)
11138 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
11139
11140 // Two block pointers.
11141 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
11142 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
11143 if (lhsBlock && rhsBlock)
11144 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
11145
11146 // If either is an unqualified 'id' and the other is a block, it's
11147 // acceptable.
11148 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
11149 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
11150 return true;
11151
11152 return false;
11153}
11154
11155// Check that the given Objective-C type argument lists are equivalent.
11157 const ObjCInterfaceDecl *iface,
11158 ArrayRef<QualType> lhsArgs,
11159 ArrayRef<QualType> rhsArgs,
11160 bool stripKindOf) {
11161 if (lhsArgs.size() != rhsArgs.size())
11162 return false;
11163
11164 ObjCTypeParamList *typeParams = iface->getTypeParamList();
11165 if (!typeParams)
11166 return false;
11167
11168 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
11169 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
11170 continue;
11171
11172 switch (typeParams->begin()[i]->getVariance()) {
11174 if (!stripKindOf ||
11175 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
11176 rhsArgs[i].stripObjCKindOfType(ctx))) {
11177 return false;
11178 }
11179 break;
11180
11182 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
11183 return false;
11184 break;
11185
11187 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
11188 return false;
11189 break;
11190 }
11191 }
11192
11193 return true;
11194}
11195
11197 const ObjCObjectPointerType *Lptr,
11198 const ObjCObjectPointerType *Rptr) {
11199 const ObjCObjectType *LHS = Lptr->getObjectType();
11200 const ObjCObjectType *RHS = Rptr->getObjectType();
11201 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
11202 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
11203
11204 if (!LDecl || !RDecl)
11205 return {};
11206
11207 // When either LHS or RHS is a kindof type, we should return a kindof type.
11208 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
11209 // kindof(A).
11210 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
11211
11212 // Follow the left-hand side up the class hierarchy until we either hit a
11213 // root or find the RHS. Record the ancestors in case we don't find it.
11214 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
11215 LHSAncestors;
11216 while (true) {
11217 // Record this ancestor. We'll need this if the common type isn't in the
11218 // path from the LHS to the root.
11219 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
11220
11221 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
11222 // Get the type arguments.
11223 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
11224 bool anyChanges = false;
11225 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11226 // Both have type arguments, compare them.
11227 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11228 LHS->getTypeArgs(), RHS->getTypeArgs(),
11229 /*stripKindOf=*/true))
11230 return {};
11231 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11232 // If only one has type arguments, the result will not have type
11233 // arguments.
11234 LHSTypeArgs = {};
11235 anyChanges = true;
11236 }
11237
11238 // Compute the intersection of protocols.
11240 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
11241 Protocols);
11242 if (!Protocols.empty())
11243 anyChanges = true;
11244
11245 // If anything in the LHS will have changed, build a new result type.
11246 // If we need to return a kindof type but LHS is not a kindof type, we
11247 // build a new result type.
11248 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
11250 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
11251 anyKindOf || LHS->isKindOfType());
11253 }
11254
11255 return getObjCObjectPointerType(QualType(LHS, 0));
11256 }
11257
11258 // Find the superclass.
11259 QualType LHSSuperType = LHS->getSuperClassType();
11260 if (LHSSuperType.isNull())
11261 break;
11262
11263 LHS = LHSSuperType->castAs<ObjCObjectType>();
11264 }
11265
11266 // We didn't find anything by following the LHS to its root; now check
11267 // the RHS against the cached set of ancestors.
11268 while (true) {
11269 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
11270 if (KnownLHS != LHSAncestors.end()) {
11271 LHS = KnownLHS->second;
11272
11273 // Get the type arguments.
11274 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
11275 bool anyChanges = false;
11276 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11277 // Both have type arguments, compare them.
11278 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11279 LHS->getTypeArgs(), RHS->getTypeArgs(),
11280 /*stripKindOf=*/true))
11281 return {};
11282 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11283 // If only one has type arguments, the result will not have type
11284 // arguments.
11285 RHSTypeArgs = {};
11286 anyChanges = true;
11287 }
11288
11289 // Compute the intersection of protocols.
11291 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
11292 Protocols);
11293 if (!Protocols.empty())
11294 anyChanges = true;
11295
11296 // If we need to return a kindof type but RHS is not a kindof type, we
11297 // build a new result type.
11298 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
11300 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
11301 anyKindOf || RHS->isKindOfType());
11303 }
11304
11305 return getObjCObjectPointerType(QualType(RHS, 0));
11306 }
11307
11308 // Find the superclass of the RHS.
11309 QualType RHSSuperType = RHS->getSuperClassType();
11310 if (RHSSuperType.isNull())
11311 break;
11312
11313 RHS = RHSSuperType->castAs<ObjCObjectType>();
11314 }
11315
11316 return {};
11317}
11318
11320 const ObjCObjectType *RHS) {
11321 assert(LHS->getInterface() && "LHS is not an interface type");
11322 assert(RHS->getInterface() && "RHS is not an interface type");
11323
11324 // Verify that the base decls are compatible: the RHS must be a subclass of
11325 // the LHS.
11326 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
11327 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
11328 if (!IsSuperClass)
11329 return false;
11330
11331 // If the LHS has protocol qualifiers, determine whether all of them are
11332 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
11333 // LHS).
11334 if (LHS->getNumProtocols() > 0) {
11335 // OK if conversion of LHS to SuperClass results in narrowing of types
11336 // ; i.e., SuperClass may implement at least one of the protocols
11337 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
11338 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
11339 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
11340 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
11341 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
11342 // qualifiers.
11343 for (auto *RHSPI : RHS->quals())
11344 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
11345 // If there is no protocols associated with RHS, it is not a match.
11346 if (SuperClassInheritedProtocols.empty())
11347 return false;
11348
11349 for (const auto *LHSProto : LHS->quals()) {
11350 bool SuperImplementsProtocol = false;
11351 for (auto *SuperClassProto : SuperClassInheritedProtocols)
11352 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
11353 SuperImplementsProtocol = true;
11354 break;
11355 }
11356 if (!SuperImplementsProtocol)
11357 return false;
11358 }
11359 }
11360
11361 // If the LHS is specialized, we may need to check type arguments.
11362 if (LHS->isSpecialized()) {
11363 // Follow the superclass chain until we've matched the LHS class in the
11364 // hierarchy. This substitutes type arguments through.
11365 const ObjCObjectType *RHSSuper = RHS;
11366 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
11367 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
11368
11369 // If the RHS is specializd, compare type arguments.
11370 if (RHSSuper->isSpecialized() &&
11371 !sameObjCTypeArgs(*this, LHS->getInterface(),
11372 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
11373 /*stripKindOf=*/true)) {
11374 return false;
11375 }
11376 }
11377
11378 return true;
11379}
11380
11382 // get the "pointed to" types
11383 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
11384 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
11385
11386 if (!LHSOPT || !RHSOPT)
11387 return false;
11388
11389 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
11390 canAssignObjCInterfaces(RHSOPT, LHSOPT);
11391}
11392
11395 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
11396 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
11397}
11398
11399/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
11400/// both shall have the identically qualified version of a compatible type.
11401/// C99 6.2.7p1: Two types have compatible types if their types are the
11402/// same. See 6.7.[2,3,5] for additional rules.
11404 bool CompareUnqualified) {
11405 if (getLangOpts().CPlusPlus)
11406 return hasSameType(LHS, RHS);
11407
11408 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
11409}
11410
11412 return typesAreCompatible(LHS, RHS);
11413}
11414
11416 return !mergeTypes(LHS, RHS, true).isNull();
11417}
11418
11419/// mergeTransparentUnionType - if T is a transparent union type and a member
11420/// of T is compatible with SubType, return the merged type, else return
11421/// QualType()
11423 bool OfBlockPointer,
11424 bool Unqualified) {
11425 if (const RecordType *UT = T->getAsUnionType()) {
11426 RecordDecl *UD = UT->getOriginalDecl()->getMostRecentDecl();
11427 if (UD->hasAttr<TransparentUnionAttr>()) {
11428 for (const auto *I : UD->fields()) {
11429 QualType ET = I->getType().getUnqualifiedType();
11430 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
11431 if (!MT.isNull())
11432 return MT;
11433 }
11434 }
11435 }
11436
11437 return {};
11438}
11439
11440/// mergeFunctionParameterTypes - merge two types which appear as function
11441/// parameter types
11443 bool OfBlockPointer,
11444 bool Unqualified) {
11445 // GNU extension: two types are compatible if they appear as a function
11446 // argument, one of the types is a transparent union type and the other
11447 // type is compatible with a union member
11448 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
11449 Unqualified);
11450 if (!lmerge.isNull())
11451 return lmerge;
11452
11453 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
11454 Unqualified);
11455 if (!rmerge.isNull())
11456 return rmerge;
11457
11458 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
11459}
11460
11462 bool OfBlockPointer, bool Unqualified,
11463 bool AllowCXX,
11464 bool IsConditionalOperator) {
11465 const auto *lbase = lhs->castAs<FunctionType>();
11466 const auto *rbase = rhs->castAs<FunctionType>();
11467 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
11468 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
11469 bool allLTypes = true;
11470 bool allRTypes = true;
11471
11472 // Check return type
11473 QualType retType;
11474 if (OfBlockPointer) {
11475 QualType RHS = rbase->getReturnType();
11476 QualType LHS = lbase->getReturnType();
11477 bool UnqualifiedResult = Unqualified;
11478 if (!UnqualifiedResult)
11479 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
11480 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
11481 }
11482 else
11483 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
11484 Unqualified);
11485 if (retType.isNull())
11486 return {};
11487
11488 if (Unqualified)
11489 retType = retType.getUnqualifiedType();
11490
11491 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
11492 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
11493 if (Unqualified) {
11494 LRetType = LRetType.getUnqualifiedType();
11495 RRetType = RRetType.getUnqualifiedType();
11496 }
11497
11498 if (getCanonicalType(retType) != LRetType)
11499 allLTypes = false;
11500 if (getCanonicalType(retType) != RRetType)
11501 allRTypes = false;
11502
11503 // FIXME: double check this
11504 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
11505 // rbase->getRegParmAttr() != 0 &&
11506 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
11507 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
11508 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
11509
11510 // Compatible functions must have compatible calling conventions
11511 if (lbaseInfo.getCC() != rbaseInfo.getCC())
11512 return {};
11513
11514 // Regparm is part of the calling convention.
11515 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
11516 return {};
11517 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
11518 return {};
11519
11520 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
11521 return {};
11522 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
11523 return {};
11524 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
11525 return {};
11526
11527 // When merging declarations, it's common for supplemental information like
11528 // attributes to only be present in one of the declarations, and we generally
11529 // want type merging to preserve the union of information. So a merged
11530 // function type should be noreturn if it was noreturn in *either* operand
11531 // type.
11532 //
11533 // But for the conditional operator, this is backwards. The result of the
11534 // operator could be either operand, and its type should conservatively
11535 // reflect that. So a function type in a composite type is noreturn only
11536 // if it's noreturn in *both* operand types.
11537 //
11538 // Arguably, noreturn is a kind of subtype, and the conditional operator
11539 // ought to produce the most specific common supertype of its operand types.
11540 // That would differ from this rule in contravariant positions. However,
11541 // neither C nor C++ generally uses this kind of subtype reasoning. Also,
11542 // as a practical matter, it would only affect C code that does abstraction of
11543 // higher-order functions (taking noreturn callbacks!), which is uncommon to
11544 // say the least. So we use the simpler rule.
11545 bool NoReturn = IsConditionalOperator
11546 ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
11547 : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
11548 if (lbaseInfo.getNoReturn() != NoReturn)
11549 allLTypes = false;
11550 if (rbaseInfo.getNoReturn() != NoReturn)
11551 allRTypes = false;
11552
11553 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
11554
11555 std::optional<FunctionEffectSet> MergedFX;
11556
11557 if (lproto && rproto) { // two C99 style function prototypes
11558 assert((AllowCXX ||
11559 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
11560 "C++ shouldn't be here");
11561 // Compatible functions must have the same number of parameters
11562 if (lproto->getNumParams() != rproto->getNumParams())
11563 return {};
11564
11565 // Variadic and non-variadic functions aren't compatible
11566 if (lproto->isVariadic() != rproto->isVariadic())
11567 return {};
11568
11569 if (lproto->getMethodQuals() != rproto->getMethodQuals())
11570 return {};
11571
11572 // Function protos with different 'cfi_salt' values aren't compatible.
11573 if (lproto->getExtraAttributeInfo().CFISalt !=
11574 rproto->getExtraAttributeInfo().CFISalt)
11575 return {};
11576
11577 // Function effects are handled similarly to noreturn, see above.
11578 FunctionEffectsRef LHSFX = lproto->getFunctionEffects();
11579 FunctionEffectsRef RHSFX = rproto->getFunctionEffects();
11580 if (LHSFX != RHSFX) {
11581 if (IsConditionalOperator)
11582 MergedFX = FunctionEffectSet::getIntersection(LHSFX, RHSFX);
11583 else {
11585 MergedFX = FunctionEffectSet::getUnion(LHSFX, RHSFX, Errs);
11586 // Here we're discarding a possible error due to conflicts in the effect
11587 // sets. But we're not in a context where we can report it. The
11588 // operation does however guarantee maintenance of invariants.
11589 }
11590 if (*MergedFX != LHSFX)
11591 allLTypes = false;
11592 if (*MergedFX != RHSFX)
11593 allRTypes = false;
11594 }
11595
11597 bool canUseLeft, canUseRight;
11598 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
11599 newParamInfos))
11600 return {};
11601
11602 if (!canUseLeft)
11603 allLTypes = false;
11604 if (!canUseRight)
11605 allRTypes = false;
11606
11607 // Check parameter type compatibility
11609 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
11610 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
11611 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
11613 lParamType, rParamType, OfBlockPointer, Unqualified);
11614 if (paramType.isNull())
11615 return {};
11616
11617 if (Unqualified)
11618 paramType = paramType.getUnqualifiedType();
11619
11620 types.push_back(paramType);
11621 if (Unqualified) {
11622 lParamType = lParamType.getUnqualifiedType();
11623 rParamType = rParamType.getUnqualifiedType();
11624 }
11625
11626 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
11627 allLTypes = false;
11628 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
11629 allRTypes = false;
11630 }
11631
11632 if (allLTypes) return lhs;
11633 if (allRTypes) return rhs;
11634
11635 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
11636 EPI.ExtInfo = einfo;
11637 EPI.ExtParameterInfos =
11638 newParamInfos.empty() ? nullptr : newParamInfos.data();
11639 if (MergedFX)
11640 EPI.FunctionEffects = *MergedFX;
11641 return getFunctionType(retType, types, EPI);
11642 }
11643
11644 if (lproto) allRTypes = false;
11645 if (rproto) allLTypes = false;
11646
11647 const FunctionProtoType *proto = lproto ? lproto : rproto;
11648 if (proto) {
11649 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
11650 if (proto->isVariadic())
11651 return {};
11652 // Check that the types are compatible with the types that
11653 // would result from default argument promotions (C99 6.7.5.3p15).
11654 // The only types actually affected are promotable integer
11655 // types and floats, which would be passed as a different
11656 // type depending on whether the prototype is visible.
11657 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
11658 QualType paramTy = proto->getParamType(i);
11659
11660 // Look at the converted type of enum types, since that is the type used
11661 // to pass enum values.
11662 if (const auto *ED = paramTy->getAsEnumDecl()) {
11663 paramTy = ED->getIntegerType();
11664 if (paramTy.isNull())
11665 return {};
11666 }
11667
11668 if (isPromotableIntegerType(paramTy) ||
11669 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
11670 return {};
11671 }
11672
11673 if (allLTypes) return lhs;
11674 if (allRTypes) return rhs;
11675
11677 EPI.ExtInfo = einfo;
11678 if (MergedFX)
11679 EPI.FunctionEffects = *MergedFX;
11680 return getFunctionType(retType, proto->getParamTypes(), EPI);
11681 }
11682
11683 if (allLTypes) return lhs;
11684 if (allRTypes) return rhs;
11685 return getFunctionNoProtoType(retType, einfo);
11686}
11687
11688/// Given that we have an enum type and a non-enum type, try to merge them.
11690 QualType other, bool isBlockReturnType) {
11691 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
11692 // a signed integer type, or an unsigned integer type.
11693 // Compatibility is based on the underlying type, not the promotion
11694 // type.
11695 QualType underlyingType =
11697 if (underlyingType.isNull())
11698 return {};
11699 if (Context.hasSameType(underlyingType, other))
11700 return other;
11701
11702 // In block return types, we're more permissive and accept any
11703 // integral type of the same size.
11704 if (isBlockReturnType && other->isIntegerType() &&
11705 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
11706 return other;
11707
11708 return {};
11709}
11710
11712 // C17 and earlier and C++ disallow two tag definitions within the same TU
11713 // from being compatible.
11714 if (LangOpts.CPlusPlus || !LangOpts.C23)
11715 return {};
11716
11717 // C23, on the other hand, requires the members to be "the same enough", so
11718 // we use a structural equivalence check.
11721 getLangOpts(), *this, *this, NonEquivalentDecls,
11722 StructuralEquivalenceKind::Default, /*StrictTypeSpelling=*/false,
11723 /*Complain=*/false, /*ErrorOnTagTypeMismatch=*/true);
11724 return Ctx.IsEquivalent(LHS, RHS) ? LHS : QualType{};
11725}
11726
11727QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
11728 bool Unqualified, bool BlockReturnType,
11729 bool IsConditionalOperator) {
11730 // For C++ we will not reach this code with reference types (see below),
11731 // for OpenMP variant call overloading we might.
11732 //
11733 // C++ [expr]: If an expression initially has the type "reference to T", the
11734 // type is adjusted to "T" prior to any further analysis, the expression
11735 // designates the object or function denoted by the reference, and the
11736 // expression is an lvalue unless the reference is an rvalue reference and
11737 // the expression is a function call (possibly inside parentheses).
11738 auto *LHSRefTy = LHS->getAs<ReferenceType>();
11739 auto *RHSRefTy = RHS->getAs<ReferenceType>();
11740 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
11741 LHS->getTypeClass() == RHS->getTypeClass())
11742 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(),
11743 OfBlockPointer, Unqualified, BlockReturnType);
11744 if (LHSRefTy || RHSRefTy)
11745 return {};
11746
11747 if (Unqualified) {
11748 LHS = LHS.getUnqualifiedType();
11749 RHS = RHS.getUnqualifiedType();
11750 }
11751
11752 QualType LHSCan = getCanonicalType(LHS),
11753 RHSCan = getCanonicalType(RHS);
11754
11755 // If two types are identical, they are compatible.
11756 if (LHSCan == RHSCan)
11757 return LHS;
11758
11759 // If the qualifiers are different, the types aren't compatible... mostly.
11760 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11761 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11762 if (LQuals != RQuals) {
11763 // If any of these qualifiers are different, we have a type
11764 // mismatch.
11765 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11766 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
11767 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
11768 !LQuals.getPointerAuth().isEquivalent(RQuals.getPointerAuth()) ||
11769 LQuals.hasUnaligned() != RQuals.hasUnaligned())
11770 return {};
11771
11772 // Exactly one GC qualifier difference is allowed: __strong is
11773 // okay if the other type has no GC qualifier but is an Objective
11774 // C object pointer (i.e. implicitly strong by default). We fix
11775 // this by pretending that the unqualified type was actually
11776 // qualified __strong.
11777 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11778 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11779 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11780
11781 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
11782 return {};
11783
11784 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
11786 }
11787 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
11789 }
11790 return {};
11791 }
11792
11793 // Okay, qualifiers are equal.
11794
11795 Type::TypeClass LHSClass = LHSCan->getTypeClass();
11796 Type::TypeClass RHSClass = RHSCan->getTypeClass();
11797
11798 // We want to consider the two function types to be the same for these
11799 // comparisons, just force one to the other.
11800 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
11801 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
11802
11803 // Same as above for arrays
11804 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
11805 LHSClass = Type::ConstantArray;
11806 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
11807 RHSClass = Type::ConstantArray;
11808
11809 // ObjCInterfaces are just specialized ObjCObjects.
11810 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
11811 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
11812
11813 // Canonicalize ExtVector -> Vector.
11814 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
11815 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
11816
11817 // If the canonical type classes don't match.
11818 if (LHSClass != RHSClass) {
11819 // Note that we only have special rules for turning block enum
11820 // returns into block int returns, not vice-versa.
11821 if (const auto *ETy = LHS->getAsCanonical<EnumType>()) {
11822 return mergeEnumWithInteger(*this, ETy, RHS, false);
11823 }
11824 if (const EnumType *ETy = RHS->getAsCanonical<EnumType>()) {
11825 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
11826 }
11827 // allow block pointer type to match an 'id' type.
11828 if (OfBlockPointer && !BlockReturnType) {
11829 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
11830 return LHS;
11831 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
11832 return RHS;
11833 }
11834 // Allow __auto_type to match anything; it merges to the type with more
11835 // information.
11836 if (const auto *AT = LHS->getAs<AutoType>()) {
11837 if (!AT->isDeduced() && AT->isGNUAutoType())
11838 return RHS;
11839 }
11840 if (const auto *AT = RHS->getAs<AutoType>()) {
11841 if (!AT->isDeduced() && AT->isGNUAutoType())
11842 return LHS;
11843 }
11844 return {};
11845 }
11846
11847 // The canonical type classes match.
11848 switch (LHSClass) {
11849#define TYPE(Class, Base)
11850#define ABSTRACT_TYPE(Class, Base)
11851#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
11852#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
11853#define DEPENDENT_TYPE(Class, Base) case Type::Class:
11854#include "clang/AST/TypeNodes.inc"
11855 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
11856
11857 case Type::Auto:
11858 case Type::DeducedTemplateSpecialization:
11859 case Type::LValueReference:
11860 case Type::RValueReference:
11861 case Type::MemberPointer:
11862 llvm_unreachable("C++ should never be in mergeTypes");
11863
11864 case Type::ObjCInterface:
11865 case Type::IncompleteArray:
11866 case Type::VariableArray:
11867 case Type::FunctionProto:
11868 case Type::ExtVector:
11869 llvm_unreachable("Types are eliminated above");
11870
11871 case Type::Pointer:
11872 {
11873 // Merge two pointer types, while trying to preserve typedef info
11874 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
11875 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
11876 if (Unqualified) {
11877 LHSPointee = LHSPointee.getUnqualifiedType();
11878 RHSPointee = RHSPointee.getUnqualifiedType();
11879 }
11880 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
11881 Unqualified);
11882 if (ResultType.isNull())
11883 return {};
11884 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
11885 return LHS;
11886 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
11887 return RHS;
11888 return getPointerType(ResultType);
11889 }
11890 case Type::BlockPointer:
11891 {
11892 // Merge two block pointer types, while trying to preserve typedef info
11893 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
11894 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
11895 if (Unqualified) {
11896 LHSPointee = LHSPointee.getUnqualifiedType();
11897 RHSPointee = RHSPointee.getUnqualifiedType();
11898 }
11899 if (getLangOpts().OpenCL) {
11900 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
11901 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
11902 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
11903 // 6.12.5) thus the following check is asymmetric.
11904 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual, *this))
11905 return {};
11906 LHSPteeQual.removeAddressSpace();
11907 RHSPteeQual.removeAddressSpace();
11908 LHSPointee =
11909 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
11910 RHSPointee =
11911 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
11912 }
11913 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
11914 Unqualified);
11915 if (ResultType.isNull())
11916 return {};
11917 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
11918 return LHS;
11919 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
11920 return RHS;
11921 return getBlockPointerType(ResultType);
11922 }
11923 case Type::Atomic:
11924 {
11925 // Merge two pointer types, while trying to preserve typedef info
11926 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
11927 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
11928 if (Unqualified) {
11929 LHSValue = LHSValue.getUnqualifiedType();
11930 RHSValue = RHSValue.getUnqualifiedType();
11931 }
11932 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
11933 Unqualified);
11934 if (ResultType.isNull())
11935 return {};
11936 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
11937 return LHS;
11938 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
11939 return RHS;
11940 return getAtomicType(ResultType);
11941 }
11942 case Type::ConstantArray:
11943 {
11944 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
11945 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
11946 if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize())
11947 return {};
11948
11949 QualType LHSElem = getAsArrayType(LHS)->getElementType();
11950 QualType RHSElem = getAsArrayType(RHS)->getElementType();
11951 if (Unqualified) {
11952 LHSElem = LHSElem.getUnqualifiedType();
11953 RHSElem = RHSElem.getUnqualifiedType();
11954 }
11955
11956 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
11957 if (ResultType.isNull())
11958 return {};
11959
11960 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
11961 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
11962
11963 // If either side is a variable array, and both are complete, check whether
11964 // the current dimension is definite.
11965 if (LVAT || RVAT) {
11966 auto SizeFetch = [this](const VariableArrayType* VAT,
11967 const ConstantArrayType* CAT)
11968 -> std::pair<bool,llvm::APInt> {
11969 if (VAT) {
11970 std::optional<llvm::APSInt> TheInt;
11971 Expr *E = VAT->getSizeExpr();
11972 if (E && (TheInt = E->getIntegerConstantExpr(*this)))
11973 return std::make_pair(true, *TheInt);
11974 return std::make_pair(false, llvm::APSInt());
11975 }
11976 if (CAT)
11977 return std::make_pair(true, CAT->getSize());
11978 return std::make_pair(false, llvm::APInt());
11979 };
11980
11981 bool HaveLSize, HaveRSize;
11982 llvm::APInt LSize, RSize;
11983 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
11984 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
11985 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
11986 return {}; // Definite, but unequal, array dimension
11987 }
11988
11989 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
11990 return LHS;
11991 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
11992 return RHS;
11993 if (LCAT)
11994 return getConstantArrayType(ResultType, LCAT->getSize(),
11995 LCAT->getSizeExpr(), ArraySizeModifier(), 0);
11996 if (RCAT)
11997 return getConstantArrayType(ResultType, RCAT->getSize(),
11998 RCAT->getSizeExpr(), ArraySizeModifier(), 0);
11999 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
12000 return LHS;
12001 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
12002 return RHS;
12003 if (LVAT) {
12004 // FIXME: This isn't correct! But tricky to implement because
12005 // the array's size has to be the size of LHS, but the type
12006 // has to be different.
12007 return LHS;
12008 }
12009 if (RVAT) {
12010 // FIXME: This isn't correct! But tricky to implement because
12011 // the array's size has to be the size of RHS, but the type
12012 // has to be different.
12013 return RHS;
12014 }
12015 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
12016 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
12017 return getIncompleteArrayType(ResultType, ArraySizeModifier(), 0);
12018 }
12019 case Type::FunctionNoProto:
12020 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified,
12021 /*AllowCXX=*/false, IsConditionalOperator);
12022 case Type::Record:
12023 case Type::Enum:
12024 return mergeTagDefinitions(LHS, RHS);
12025 case Type::Builtin:
12026 // Only exactly equal builtin types are compatible, which is tested above.
12027 return {};
12028 case Type::Complex:
12029 // Distinct complex types are incompatible.
12030 return {};
12031 case Type::Vector:
12032 // FIXME: The merged type should be an ExtVector!
12033 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
12034 RHSCan->castAs<VectorType>()))
12035 return LHS;
12036 return {};
12037 case Type::ConstantMatrix:
12039 RHSCan->castAs<ConstantMatrixType>()))
12040 return LHS;
12041 return {};
12042 case Type::ObjCObject: {
12043 // Check if the types are assignment compatible.
12044 // FIXME: This should be type compatibility, e.g. whether
12045 // "LHS x; RHS x;" at global scope is legal.
12047 RHS->castAs<ObjCObjectType>()))
12048 return LHS;
12049 return {};
12050 }
12051 case Type::ObjCObjectPointer:
12052 if (OfBlockPointer) {
12055 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
12056 return LHS;
12057 return {};
12058 }
12061 return LHS;
12062 return {};
12063 case Type::Pipe:
12064 assert(LHS != RHS &&
12065 "Equivalent pipe types should have already been handled!");
12066 return {};
12067 case Type::ArrayParameter:
12068 assert(LHS != RHS &&
12069 "Equivalent ArrayParameter types should have already been handled!");
12070 return {};
12071 case Type::BitInt: {
12072 // Merge two bit-precise int types, while trying to preserve typedef info.
12073 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
12074 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
12075 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
12076 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
12077
12078 // Like unsigned/int, shouldn't have a type if they don't match.
12079 if (LHSUnsigned != RHSUnsigned)
12080 return {};
12081
12082 if (LHSBits != RHSBits)
12083 return {};
12084 return LHS;
12085 }
12086 case Type::HLSLAttributedResource: {
12087 const HLSLAttributedResourceType *LHSTy =
12089 const HLSLAttributedResourceType *RHSTy =
12091 assert(LHSTy->getWrappedType() == RHSTy->getWrappedType() &&
12092 LHSTy->getWrappedType()->isHLSLResourceType() &&
12093 "HLSLAttributedResourceType should always wrap __hlsl_resource_t");
12094
12095 if (LHSTy->getAttrs() == RHSTy->getAttrs() &&
12096 LHSTy->getContainedType() == RHSTy->getContainedType())
12097 return LHS;
12098 return {};
12099 }
12100 case Type::HLSLInlineSpirv:
12101 const HLSLInlineSpirvType *LHSTy = LHS->castAs<HLSLInlineSpirvType>();
12102 const HLSLInlineSpirvType *RHSTy = RHS->castAs<HLSLInlineSpirvType>();
12103
12104 if (LHSTy->getOpcode() == RHSTy->getOpcode() &&
12105 LHSTy->getSize() == RHSTy->getSize() &&
12106 LHSTy->getAlignment() == RHSTy->getAlignment()) {
12107 for (size_t I = 0; I < LHSTy->getOperands().size(); I++)
12108 if (LHSTy->getOperands()[I] != RHSTy->getOperands()[I])
12109 return {};
12110
12111 return LHS;
12112 }
12113 return {};
12114 }
12115
12116 llvm_unreachable("Invalid Type::Class!");
12117}
12118
12120 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
12121 bool &CanUseFirst, bool &CanUseSecond,
12123 assert(NewParamInfos.empty() && "param info list not empty");
12124 CanUseFirst = CanUseSecond = true;
12125 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
12126 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
12127
12128 // Fast path: if the first type doesn't have ext parameter infos,
12129 // we match if and only if the second type also doesn't have them.
12130 if (!FirstHasInfo && !SecondHasInfo)
12131 return true;
12132
12133 bool NeedParamInfo = false;
12134 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
12135 : SecondFnType->getExtParameterInfos().size();
12136
12137 for (size_t I = 0; I < E; ++I) {
12138 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
12139 if (FirstHasInfo)
12140 FirstParam = FirstFnType->getExtParameterInfo(I);
12141 if (SecondHasInfo)
12142 SecondParam = SecondFnType->getExtParameterInfo(I);
12143
12144 // Cannot merge unless everything except the noescape flag matches.
12145 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
12146 return false;
12147
12148 bool FirstNoEscape = FirstParam.isNoEscape();
12149 bool SecondNoEscape = SecondParam.isNoEscape();
12150 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
12151 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
12152 if (NewParamInfos.back().getOpaqueValue())
12153 NeedParamInfo = true;
12154 if (FirstNoEscape != IsNoEscape)
12155 CanUseFirst = false;
12156 if (SecondNoEscape != IsNoEscape)
12157 CanUseSecond = false;
12158 }
12159
12160 if (!NeedParamInfo)
12161 NewParamInfos.clear();
12162
12163 return true;
12164}
12165
12167 if (auto It = ObjCLayouts.find(D); It != ObjCLayouts.end()) {
12168 It->second = nullptr;
12169 for (auto *SubClass : ObjCSubClasses[D])
12170 ResetObjCLayout(SubClass);
12171 }
12172}
12173
12174/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
12175/// 'RHS' attributes and returns the merged version; including for function
12176/// return types.
12178 QualType LHSCan = getCanonicalType(LHS),
12179 RHSCan = getCanonicalType(RHS);
12180 // If two types are identical, they are compatible.
12181 if (LHSCan == RHSCan)
12182 return LHS;
12183 if (RHSCan->isFunctionType()) {
12184 if (!LHSCan->isFunctionType())
12185 return {};
12186 QualType OldReturnType =
12187 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
12188 QualType NewReturnType =
12189 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
12190 QualType ResReturnType =
12191 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
12192 if (ResReturnType.isNull())
12193 return {};
12194 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
12195 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
12196 // In either case, use OldReturnType to build the new function type.
12197 const auto *F = LHS->castAs<FunctionType>();
12198 if (const auto *FPT = cast<FunctionProtoType>(F)) {
12199 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12200 EPI.ExtInfo = getFunctionExtInfo(LHS);
12201 QualType ResultType =
12202 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
12203 return ResultType;
12204 }
12205 }
12206 return {};
12207 }
12208
12209 // If the qualifiers are different, the types can still be merged.
12210 Qualifiers LQuals = LHSCan.getLocalQualifiers();
12211 Qualifiers RQuals = RHSCan.getLocalQualifiers();
12212 if (LQuals != RQuals) {
12213 // If any of these qualifiers are different, we have a type mismatch.
12214 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
12215 LQuals.getAddressSpace() != RQuals.getAddressSpace())
12216 return {};
12217
12218 // Exactly one GC qualifier difference is allowed: __strong is
12219 // okay if the other type has no GC qualifier but is an Objective
12220 // C object pointer (i.e. implicitly strong by default). We fix
12221 // this by pretending that the unqualified type was actually
12222 // qualified __strong.
12223 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
12224 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
12225 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
12226
12227 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
12228 return {};
12229
12230 if (GC_L == Qualifiers::Strong)
12231 return LHS;
12232 if (GC_R == Qualifiers::Strong)
12233 return RHS;
12234 return {};
12235 }
12236
12237 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
12238 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12239 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12240 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
12241 if (ResQT == LHSBaseQT)
12242 return LHS;
12243 if (ResQT == RHSBaseQT)
12244 return RHS;
12245 }
12246 return {};
12247}
12248
12249//===----------------------------------------------------------------------===//
12250// Integer Predicates
12251//===----------------------------------------------------------------------===//
12252
12254 if (const auto *ED = T->getAsEnumDecl())
12255 T = ED->getIntegerType();
12256 if (T->isBooleanType())
12257 return 1;
12258 if (const auto *EIT = T->getAs<BitIntType>())
12259 return EIT->getNumBits();
12260 // For builtin types, just use the standard type sizing method
12261 return (unsigned)getTypeSize(T);
12262}
12263
12265 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12266 T->isFixedPointType()) &&
12267 "Unexpected type");
12268
12269 // Turn <4 x signed int> -> <4 x unsigned int>
12270 if (const auto *VTy = T->getAs<VectorType>())
12271 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
12272 VTy->getNumElements(), VTy->getVectorKind());
12273
12274 // For _BitInt, return an unsigned _BitInt with same width.
12275 if (const auto *EITy = T->getAs<BitIntType>())
12276 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits());
12277
12278 // For enums, get the underlying integer type of the enum, and let the general
12279 // integer type signchanging code handle it.
12280 if (const auto *ED = T->getAsEnumDecl())
12281 T = ED->getIntegerType();
12282
12283 switch (T->castAs<BuiltinType>()->getKind()) {
12284 case BuiltinType::Char_U:
12285 // Plain `char` is mapped to `unsigned char` even if it's already unsigned
12286 case BuiltinType::Char_S:
12287 case BuiltinType::SChar:
12288 case BuiltinType::Char8:
12289 return UnsignedCharTy;
12290 case BuiltinType::Short:
12291 return UnsignedShortTy;
12292 case BuiltinType::Int:
12293 return UnsignedIntTy;
12294 case BuiltinType::Long:
12295 return UnsignedLongTy;
12296 case BuiltinType::LongLong:
12297 return UnsignedLongLongTy;
12298 case BuiltinType::Int128:
12299 return UnsignedInt128Ty;
12300 // wchar_t is special. It is either signed or not, but when it's signed,
12301 // there's no matching "unsigned wchar_t". Therefore we return the unsigned
12302 // version of its underlying type instead.
12303 case BuiltinType::WChar_S:
12304 return getUnsignedWCharType();
12305
12306 case BuiltinType::ShortAccum:
12307 return UnsignedShortAccumTy;
12308 case BuiltinType::Accum:
12309 return UnsignedAccumTy;
12310 case BuiltinType::LongAccum:
12311 return UnsignedLongAccumTy;
12312 case BuiltinType::SatShortAccum:
12314 case BuiltinType::SatAccum:
12315 return SatUnsignedAccumTy;
12316 case BuiltinType::SatLongAccum:
12318 case BuiltinType::ShortFract:
12319 return UnsignedShortFractTy;
12320 case BuiltinType::Fract:
12321 return UnsignedFractTy;
12322 case BuiltinType::LongFract:
12323 return UnsignedLongFractTy;
12324 case BuiltinType::SatShortFract:
12326 case BuiltinType::SatFract:
12327 return SatUnsignedFractTy;
12328 case BuiltinType::SatLongFract:
12330 default:
12333 "Unexpected signed integer or fixed point type");
12334 return T;
12335 }
12336}
12337
12339 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12340 T->isFixedPointType()) &&
12341 "Unexpected type");
12342
12343 // Turn <4 x unsigned int> -> <4 x signed int>
12344 if (const auto *VTy = T->getAs<VectorType>())
12345 return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
12346 VTy->getNumElements(), VTy->getVectorKind());
12347
12348 // For _BitInt, return a signed _BitInt with same width.
12349 if (const auto *EITy = T->getAs<BitIntType>())
12350 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits());
12351
12352 // For enums, get the underlying integer type of the enum, and let the general
12353 // integer type signchanging code handle it.
12354 if (const auto *ED = T->getAsEnumDecl())
12355 T = ED->getIntegerType();
12356
12357 switch (T->castAs<BuiltinType>()->getKind()) {
12358 case BuiltinType::Char_S:
12359 // Plain `char` is mapped to `signed char` even if it's already signed
12360 case BuiltinType::Char_U:
12361 case BuiltinType::UChar:
12362 case BuiltinType::Char8:
12363 return SignedCharTy;
12364 case BuiltinType::UShort:
12365 return ShortTy;
12366 case BuiltinType::UInt:
12367 return IntTy;
12368 case BuiltinType::ULong:
12369 return LongTy;
12370 case BuiltinType::ULongLong:
12371 return LongLongTy;
12372 case BuiltinType::UInt128:
12373 return Int128Ty;
12374 // wchar_t is special. It is either unsigned or not, but when it's unsigned,
12375 // there's no matching "signed wchar_t". Therefore we return the signed
12376 // version of its underlying type instead.
12377 case BuiltinType::WChar_U:
12378 return getSignedWCharType();
12379
12380 case BuiltinType::UShortAccum:
12381 return ShortAccumTy;
12382 case BuiltinType::UAccum:
12383 return AccumTy;
12384 case BuiltinType::ULongAccum:
12385 return LongAccumTy;
12386 case BuiltinType::SatUShortAccum:
12387 return SatShortAccumTy;
12388 case BuiltinType::SatUAccum:
12389 return SatAccumTy;
12390 case BuiltinType::SatULongAccum:
12391 return SatLongAccumTy;
12392 case BuiltinType::UShortFract:
12393 return ShortFractTy;
12394 case BuiltinType::UFract:
12395 return FractTy;
12396 case BuiltinType::ULongFract:
12397 return LongFractTy;
12398 case BuiltinType::SatUShortFract:
12399 return SatShortFractTy;
12400 case BuiltinType::SatUFract:
12401 return SatFractTy;
12402 case BuiltinType::SatULongFract:
12403 return SatLongFractTy;
12404 default:
12405 assert(
12407 "Unexpected signed integer or fixed point type");
12408 return T;
12409 }
12410}
12411
12413
12415 QualType ReturnType) {}
12416
12417//===----------------------------------------------------------------------===//
12418// Builtin Type Computation
12419//===----------------------------------------------------------------------===//
12420
12421/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
12422/// pointer over the consumed characters. This returns the resultant type. If
12423/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
12424/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
12425/// a vector of "i*".
12426///
12427/// RequiresICE is filled in on return to indicate whether the value is required
12428/// to be an Integer Constant Expression.
12429static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
12431 bool &RequiresICE,
12432 bool AllowTypeModifiers) {
12433 // Modifiers.
12434 int HowLong = 0;
12435 bool Signed = false, Unsigned = false;
12436 RequiresICE = false;
12437
12438 // Read the prefixed modifiers first.
12439 bool Done = false;
12440 #ifndef NDEBUG
12441 bool IsSpecial = false;
12442 #endif
12443 while (!Done) {
12444 switch (*Str++) {
12445 default: Done = true; --Str; break;
12446 case 'I':
12447 RequiresICE = true;
12448 break;
12449 case 'S':
12450 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
12451 assert(!Signed && "Can't use 'S' modifier multiple times!");
12452 Signed = true;
12453 break;
12454 case 'U':
12455 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
12456 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
12457 Unsigned = true;
12458 break;
12459 case 'L':
12460 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
12461 assert(HowLong <= 2 && "Can't have LLLL modifier");
12462 ++HowLong;
12463 break;
12464 case 'N':
12465 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
12466 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12467 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
12468 #ifndef NDEBUG
12469 IsSpecial = true;
12470 #endif
12471 if (Context.getTargetInfo().getLongWidth() == 32)
12472 ++HowLong;
12473 break;
12474 case 'W':
12475 // This modifier represents int64 type.
12476 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12477 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
12478 #ifndef NDEBUG
12479 IsSpecial = true;
12480 #endif
12481 switch (Context.getTargetInfo().getInt64Type()) {
12482 default:
12483 llvm_unreachable("Unexpected integer type");
12485 HowLong = 1;
12486 break;
12488 HowLong = 2;
12489 break;
12490 }
12491 break;
12492 case 'Z':
12493 // This modifier represents int32 type.
12494 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12495 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
12496 #ifndef NDEBUG
12497 IsSpecial = true;
12498 #endif
12499 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
12500 default:
12501 llvm_unreachable("Unexpected integer type");
12503 HowLong = 0;
12504 break;
12506 HowLong = 1;
12507 break;
12509 HowLong = 2;
12510 break;
12511 }
12512 break;
12513 case 'O':
12514 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12515 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
12516 #ifndef NDEBUG
12517 IsSpecial = true;
12518 #endif
12519 if (Context.getLangOpts().OpenCL)
12520 HowLong = 1;
12521 else
12522 HowLong = 2;
12523 break;
12524 }
12525 }
12526
12527 QualType Type;
12528
12529 // Read the base type.
12530 switch (*Str++) {
12531 default: llvm_unreachable("Unknown builtin type letter!");
12532 case 'x':
12533 assert(HowLong == 0 && !Signed && !Unsigned &&
12534 "Bad modifiers used with 'x'!");
12535 Type = Context.Float16Ty;
12536 break;
12537 case 'y':
12538 assert(HowLong == 0 && !Signed && !Unsigned &&
12539 "Bad modifiers used with 'y'!");
12540 Type = Context.BFloat16Ty;
12541 break;
12542 case 'v':
12543 assert(HowLong == 0 && !Signed && !Unsigned &&
12544 "Bad modifiers used with 'v'!");
12545 Type = Context.VoidTy;
12546 break;
12547 case 'h':
12548 assert(HowLong == 0 && !Signed && !Unsigned &&
12549 "Bad modifiers used with 'h'!");
12550 Type = Context.HalfTy;
12551 break;
12552 case 'f':
12553 assert(HowLong == 0 && !Signed && !Unsigned &&
12554 "Bad modifiers used with 'f'!");
12555 Type = Context.FloatTy;
12556 break;
12557 case 'd':
12558 assert(HowLong < 3 && !Signed && !Unsigned &&
12559 "Bad modifiers used with 'd'!");
12560 if (HowLong == 1)
12561 Type = Context.LongDoubleTy;
12562 else if (HowLong == 2)
12563 Type = Context.Float128Ty;
12564 else
12565 Type = Context.DoubleTy;
12566 break;
12567 case 's':
12568 assert(HowLong == 0 && "Bad modifiers used with 's'!");
12569 if (Unsigned)
12570 Type = Context.UnsignedShortTy;
12571 else
12572 Type = Context.ShortTy;
12573 break;
12574 case 'i':
12575 if (HowLong == 3)
12576 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
12577 else if (HowLong == 2)
12578 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
12579 else if (HowLong == 1)
12580 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
12581 else
12582 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
12583 break;
12584 case 'c':
12585 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
12586 if (Signed)
12587 Type = Context.SignedCharTy;
12588 else if (Unsigned)
12589 Type = Context.UnsignedCharTy;
12590 else
12591 Type = Context.CharTy;
12592 break;
12593 case 'b': // boolean
12594 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
12595 Type = Context.BoolTy;
12596 break;
12597 case 'z': // size_t.
12598 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
12599 Type = Context.getSizeType();
12600 break;
12601 case 'w': // wchar_t.
12602 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
12603 Type = Context.getWideCharType();
12604 break;
12605 case 'F':
12606 Type = Context.getCFConstantStringType();
12607 break;
12608 case 'G':
12609 Type = Context.getObjCIdType();
12610 break;
12611 case 'H':
12612 Type = Context.getObjCSelType();
12613 break;
12614 case 'M':
12615 Type = Context.getObjCSuperType();
12616 break;
12617 case 'a':
12618 Type = Context.getBuiltinVaListType();
12619 assert(!Type.isNull() && "builtin va list type not initialized!");
12620 break;
12621 case 'A':
12622 // This is a "reference" to a va_list; however, what exactly
12623 // this means depends on how va_list is defined. There are two
12624 // different kinds of va_list: ones passed by value, and ones
12625 // passed by reference. An example of a by-value va_list is
12626 // x86, where va_list is a char*. An example of by-ref va_list
12627 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
12628 // we want this argument to be a char*&; for x86-64, we want
12629 // it to be a __va_list_tag*.
12630 Type = Context.getBuiltinVaListType();
12631 assert(!Type.isNull() && "builtin va list type not initialized!");
12632 if (Type->isArrayType())
12633 Type = Context.getArrayDecayedType(Type);
12634 else
12635 Type = Context.getLValueReferenceType(Type);
12636 break;
12637 case 'q': {
12638 char *End;
12639 unsigned NumElements = strtoul(Str, &End, 10);
12640 assert(End != Str && "Missing vector size");
12641 Str = End;
12642
12643 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12644 RequiresICE, false);
12645 assert(!RequiresICE && "Can't require vector ICE");
12646
12647 Type = Context.getScalableVectorType(ElementType, NumElements);
12648 break;
12649 }
12650 case 'Q': {
12651 switch (*Str++) {
12652 case 'a': {
12653 Type = Context.SveCountTy;
12654 break;
12655 }
12656 case 'b': {
12657 Type = Context.AMDGPUBufferRsrcTy;
12658 break;
12659 }
12660 default:
12661 llvm_unreachable("Unexpected target builtin type");
12662 }
12663 break;
12664 }
12665 case 'V': {
12666 char *End;
12667 unsigned NumElements = strtoul(Str, &End, 10);
12668 assert(End != Str && "Missing vector size");
12669 Str = End;
12670
12671 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12672 RequiresICE, false);
12673 assert(!RequiresICE && "Can't require vector ICE");
12674
12675 // TODO: No way to make AltiVec vectors in builtins yet.
12676 Type = Context.getVectorType(ElementType, NumElements, VectorKind::Generic);
12677 break;
12678 }
12679 case 'E': {
12680 char *End;
12681
12682 unsigned NumElements = strtoul(Str, &End, 10);
12683 assert(End != Str && "Missing vector size");
12684
12685 Str = End;
12686
12687 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12688 false);
12689 Type = Context.getExtVectorType(ElementType, NumElements);
12690 break;
12691 }
12692 case 'X': {
12693 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12694 false);
12695 assert(!RequiresICE && "Can't require complex ICE");
12696 Type = Context.getComplexType(ElementType);
12697 break;
12698 }
12699 case 'Y':
12700 Type = Context.getPointerDiffType();
12701 break;
12702 case 'P':
12703 Type = Context.getFILEType();
12704 if (Type.isNull()) {
12706 return {};
12707 }
12708 break;
12709 case 'J':
12710 if (Signed)
12711 Type = Context.getsigjmp_bufType();
12712 else
12713 Type = Context.getjmp_bufType();
12714
12715 if (Type.isNull()) {
12717 return {};
12718 }
12719 break;
12720 case 'K':
12721 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
12722 Type = Context.getucontext_tType();
12723
12724 if (Type.isNull()) {
12726 return {};
12727 }
12728 break;
12729 case 'p':
12730 Type = Context.getProcessIDType();
12731 break;
12732 case 'm':
12733 Type = Context.MFloat8Ty;
12734 break;
12735 }
12736
12737 // If there are modifiers and if we're allowed to parse them, go for it.
12738 Done = !AllowTypeModifiers;
12739 while (!Done) {
12740 switch (char c = *Str++) {
12741 default: Done = true; --Str; break;
12742 case '*':
12743 case '&': {
12744 // Both pointers and references can have their pointee types
12745 // qualified with an address space.
12746 char *End;
12747 unsigned AddrSpace = strtoul(Str, &End, 10);
12748 if (End != Str) {
12749 // Note AddrSpace == 0 is not the same as an unspecified address space.
12750 Type = Context.getAddrSpaceQualType(
12751 Type,
12752 Context.getLangASForBuiltinAddressSpace(AddrSpace));
12753 Str = End;
12754 }
12755 if (c == '*')
12756 Type = Context.getPointerType(Type);
12757 else
12758 Type = Context.getLValueReferenceType(Type);
12759 break;
12760 }
12761 // FIXME: There's no way to have a built-in with an rvalue ref arg.
12762 case 'C':
12763 Type = Type.withConst();
12764 break;
12765 case 'D':
12766 Type = Context.getVolatileType(Type);
12767 break;
12768 case 'R':
12769 Type = Type.withRestrict();
12770 break;
12771 }
12772 }
12773
12774 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
12775 "Integer constant 'I' type must be an integer");
12776
12777 return Type;
12778}
12779
12780// On some targets such as PowerPC, some of the builtins are defined with custom
12781// type descriptors for target-dependent types. These descriptors are decoded in
12782// other functions, but it may be useful to be able to fall back to default
12783// descriptor decoding to define builtins mixing target-dependent and target-
12784// independent types. This function allows decoding one type descriptor with
12785// default decoding.
12786QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
12787 GetBuiltinTypeError &Error, bool &RequireICE,
12788 bool AllowTypeModifiers) const {
12789 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
12790}
12791
12792/// GetBuiltinType - Return the type for the specified builtin.
12794 GetBuiltinTypeError &Error,
12795 unsigned *IntegerConstantArgs) const {
12796 const char *TypeStr = BuiltinInfo.getTypeString(Id);
12797 if (TypeStr[0] == '\0') {
12798 Error = GE_Missing_type;
12799 return {};
12800 }
12801
12802 SmallVector<QualType, 8> ArgTypes;
12803
12804 bool RequiresICE = false;
12805 Error = GE_None;
12806 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
12807 RequiresICE, true);
12808 if (Error != GE_None)
12809 return {};
12810
12811 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
12812
12813 while (TypeStr[0] && TypeStr[0] != '.') {
12814 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
12815 if (Error != GE_None)
12816 return {};
12817
12818 // If this argument is required to be an IntegerConstantExpression and the
12819 // caller cares, fill in the bitmask we return.
12820 if (RequiresICE && IntegerConstantArgs)
12821 *IntegerConstantArgs |= 1 << ArgTypes.size();
12822
12823 // Do array -> pointer decay. The builtin should use the decayed type.
12824 if (Ty->isArrayType())
12825 Ty = getArrayDecayedType(Ty);
12826
12827 ArgTypes.push_back(Ty);
12828 }
12829
12830 if (Id == Builtin::BI__GetExceptionInfo)
12831 return {};
12832
12833 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
12834 "'.' should only occur at end of builtin type list!");
12835
12836 bool Variadic = (TypeStr[0] == '.');
12837
12838 FunctionType::ExtInfo EI(Target->getDefaultCallingConv());
12840 EI = EI.withNoReturn(true);
12841
12842 // We really shouldn't be making a no-proto type here.
12843 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
12844 return getFunctionNoProtoType(ResType, EI);
12845
12847 EPI.ExtInfo = EI;
12848 EPI.Variadic = Variadic;
12850 EPI.ExceptionSpec.Type =
12852
12853 return getFunctionType(ResType, ArgTypes, EPI);
12854}
12855
12857 const FunctionDecl *FD) {
12858 if (!FD->isExternallyVisible())
12859 return GVA_Internal;
12860
12861 // Non-user-provided functions get emitted as weak definitions with every
12862 // use, no matter whether they've been explicitly instantiated etc.
12863 if (!FD->isUserProvided())
12864 return GVA_DiscardableODR;
12865
12867 switch (FD->getTemplateSpecializationKind()) {
12868 case TSK_Undeclared:
12871 break;
12872
12874 return GVA_StrongODR;
12875
12876 // C++11 [temp.explicit]p10:
12877 // [ Note: The intent is that an inline function that is the subject of
12878 // an explicit instantiation declaration will still be implicitly
12879 // instantiated when used so that the body can be considered for
12880 // inlining, but that no out-of-line copy of the inline function would be
12881 // generated in the translation unit. -- end note ]
12884
12887 break;
12888 }
12889
12890 if (!FD->isInlined())
12891 return External;
12892
12893 if ((!Context.getLangOpts().CPlusPlus &&
12894 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12895 !FD->hasAttr<DLLExportAttr>()) ||
12896 FD->hasAttr<GNUInlineAttr>()) {
12897 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
12898
12899 // GNU or C99 inline semantics. Determine whether this symbol should be
12900 // externally visible.
12902 return External;
12903
12904 // C99 inline semantics, where the symbol is not externally visible.
12906 }
12907
12908 // Functions specified with extern and inline in -fms-compatibility mode
12909 // forcibly get emitted. While the body of the function cannot be later
12910 // replaced, the function definition cannot be discarded.
12911 if (FD->isMSExternInline())
12912 return GVA_StrongODR;
12913
12914 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12915 isa<CXXConstructorDecl>(FD) &&
12916 cast<CXXConstructorDecl>(FD)->isInheritingConstructor())
12917 // Our approach to inheriting constructors is fundamentally different from
12918 // that used by the MS ABI, so keep our inheriting constructor thunks
12919 // internal rather than trying to pick an unambiguous mangling for them.
12920 return GVA_Internal;
12921
12922 return GVA_DiscardableODR;
12923}
12924
12926 const Decl *D, GVALinkage L) {
12927 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
12928 // dllexport/dllimport on inline functions.
12929 if (D->hasAttr<DLLImportAttr>()) {
12930 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
12932 } else if (D->hasAttr<DLLExportAttr>()) {
12933 if (L == GVA_DiscardableODR)
12934 return GVA_StrongODR;
12935 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
12936 // Device-side functions with __global__ attribute must always be
12937 // visible externally so they can be launched from host.
12938 if (D->hasAttr<CUDAGlobalAttr>() &&
12939 (L == GVA_DiscardableODR || L == GVA_Internal))
12940 return GVA_StrongODR;
12941 // Single source offloading languages like CUDA/HIP need to be able to
12942 // access static device variables from host code of the same compilation
12943 // unit. This is done by externalizing the static variable with a shared
12944 // name between the host and device compilation which is the same for the
12945 // same compilation unit whereas different among different compilation
12946 // units.
12947 if (Context.shouldExternalize(D))
12948 return GVA_StrongExternal;
12949 }
12950 return L;
12951}
12952
12953/// Adjust the GVALinkage for a declaration based on what an external AST source
12954/// knows about whether there can be other definitions of this declaration.
12955static GVALinkage
12957 GVALinkage L) {
12958 ExternalASTSource *Source = Ctx.getExternalSource();
12959 if (!Source)
12960 return L;
12961
12962 switch (Source->hasExternalDefinitions(D)) {
12964 // Other translation units rely on us to provide the definition.
12965 if (L == GVA_DiscardableODR)
12966 return GVA_StrongODR;
12967 break;
12968
12971
12973 break;
12974 }
12975 return L;
12976}
12977
12981 basicGVALinkageForFunction(*this, FD)));
12982}
12983
12985 const VarDecl *VD) {
12986 // As an extension for interactive REPLs, make sure constant variables are
12987 // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
12988 // marking them as internal.
12989 if (Context.getLangOpts().CPlusPlus &&
12990 Context.getLangOpts().IncrementalExtensions &&
12991 VD->getType().isConstQualified() &&
12992 !VD->getType().isVolatileQualified() && !VD->isInline() &&
12993 !isa<VarTemplateSpecializationDecl>(VD) && !VD->getDescribedVarTemplate())
12994 return GVA_DiscardableODR;
12995
12996 if (!VD->isExternallyVisible())
12997 return GVA_Internal;
12998
12999 if (VD->isStaticLocal()) {
13000 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
13001 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
13002 LexicalContext = LexicalContext->getLexicalParent();
13003
13004 // ObjC Blocks can create local variables that don't have a FunctionDecl
13005 // LexicalContext.
13006 if (!LexicalContext)
13007 return GVA_DiscardableODR;
13008
13009 // Otherwise, let the static local variable inherit its linkage from the
13010 // nearest enclosing function.
13011 auto StaticLocalLinkage =
13012 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
13013
13014 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
13015 // be emitted in any object with references to the symbol for the object it
13016 // contains, whether inline or out-of-line."
13017 // Similar behavior is observed with MSVC. An alternative ABI could use
13018 // StrongODR/AvailableExternally to match the function, but none are
13019 // known/supported currently.
13020 if (StaticLocalLinkage == GVA_StrongODR ||
13021 StaticLocalLinkage == GVA_AvailableExternally)
13022 return GVA_DiscardableODR;
13023 return StaticLocalLinkage;
13024 }
13025
13026 // MSVC treats in-class initialized static data members as definitions.
13027 // By giving them non-strong linkage, out-of-line definitions won't
13028 // cause link errors.
13030 return GVA_DiscardableODR;
13031
13032 // Most non-template variables have strong linkage; inline variables are
13033 // linkonce_odr or (occasionally, for compatibility) weak_odr.
13034 GVALinkage StrongLinkage;
13035 switch (Context.getInlineVariableDefinitionKind(VD)) {
13037 StrongLinkage = GVA_StrongExternal;
13038 break;
13041 StrongLinkage = GVA_DiscardableODR;
13042 break;
13044 StrongLinkage = GVA_StrongODR;
13045 break;
13046 }
13047
13048 switch (VD->getTemplateSpecializationKind()) {
13049 case TSK_Undeclared:
13050 return StrongLinkage;
13051
13053 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13054 VD->isStaticDataMember()
13056 : StrongLinkage;
13057
13059 return GVA_StrongODR;
13060
13063
13065 return GVA_DiscardableODR;
13066 }
13067
13068 llvm_unreachable("Invalid Linkage!");
13069}
13070
13074 basicGVALinkageForVariable(*this, VD)));
13075}
13076
13078 if (const auto *VD = dyn_cast<VarDecl>(D)) {
13079 if (!VD->isFileVarDecl())
13080 return false;
13081 // Global named register variables (GNU extension) are never emitted.
13082 if (VD->getStorageClass() == SC_Register)
13083 return false;
13084 if (VD->getDescribedVarTemplate() ||
13085 isa<VarTemplatePartialSpecializationDecl>(VD))
13086 return false;
13087 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13088 // We never need to emit an uninstantiated function template.
13089 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13090 return false;
13091 } else if (isa<PragmaCommentDecl>(D))
13092 return true;
13093 else if (isa<PragmaDetectMismatchDecl>(D))
13094 return true;
13095 else if (isa<OMPRequiresDecl>(D))
13096 return true;
13097 else if (isa<OMPThreadPrivateDecl>(D))
13098 return !D->getDeclContext()->isDependentContext();
13099 else if (isa<OMPAllocateDecl>(D))
13100 return !D->getDeclContext()->isDependentContext();
13101 else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D))
13102 return !D->getDeclContext()->isDependentContext();
13103 else if (isa<ImportDecl>(D))
13104 return true;
13105 else
13106 return false;
13107
13108 // If this is a member of a class template, we do not need to emit it.
13110 return false;
13111
13112 // Weak references don't produce any output by themselves.
13113 if (D->hasAttr<WeakRefAttr>())
13114 return false;
13115
13116 // SYCL device compilation requires that functions defined with the
13117 // sycl_kernel_entry_point or sycl_external attributes be emitted. All
13118 // other entities are emitted only if they are used by a function
13119 // defined with one of those attributes.
13120 if (LangOpts.SYCLIsDevice)
13121 return isa<FunctionDecl>(D) && (D->hasAttr<SYCLKernelEntryPointAttr>() ||
13122 D->hasAttr<SYCLExternalAttr>());
13123
13124 // Aliases and used decls are required.
13125 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
13126 return true;
13127
13128 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13129 // Forward declarations aren't required.
13130 if (!FD->doesThisDeclarationHaveABody())
13131 return FD->doesDeclarationForceExternallyVisibleDefinition();
13132
13133 // Constructors and destructors are required.
13134 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
13135 return true;
13136
13137 // The key function for a class is required. This rule only comes
13138 // into play when inline functions can be key functions, though.
13140 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13141 const CXXRecordDecl *RD = MD->getParent();
13142 if (MD->isOutOfLine() && RD->isDynamicClass()) {
13143 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
13144 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
13145 return true;
13146 }
13147 }
13148 }
13149
13151
13152 // static, static inline, always_inline, and extern inline functions can
13153 // always be deferred. Normal inline functions can be deferred in C99/C++.
13154 // Implicit template instantiations can also be deferred in C++.
13156 }
13157
13158 const auto *VD = cast<VarDecl>(D);
13159 assert(VD->isFileVarDecl() && "Expected file scoped var");
13160
13161 // If the decl is marked as `declare target to`, it should be emitted for the
13162 // host and for the device.
13163 if (LangOpts.OpenMP &&
13164 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
13165 return true;
13166
13167 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
13169 return false;
13170
13171 if (VD->shouldEmitInExternalSource())
13172 return false;
13173
13174 // Variables that can be needed in other TUs are required.
13177 return true;
13178
13179 // We never need to emit a variable that is available in another TU.
13181 return false;
13182
13183 // Variables that have destruction with side-effects are required.
13184 if (VD->needsDestruction(*this))
13185 return true;
13186
13187 // Variables that have initialization with side-effects are required.
13188 if (VD->hasInitWithSideEffects())
13189 return true;
13190
13191 // Likewise, variables with tuple-like bindings are required if their
13192 // bindings have side-effects.
13193 if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) {
13194 for (const auto *BD : DD->flat_bindings())
13195 if (const auto *BindingVD = BD->getHoldingVar())
13196 if (DeclMustBeEmitted(BindingVD))
13197 return true;
13198 }
13199
13200 return false;
13201}
13202
13204 const FunctionDecl *FD,
13205 llvm::function_ref<void(FunctionDecl *)> Pred) const {
13206 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
13207 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
13208 FD = FD->getMostRecentDecl();
13209 // FIXME: The order of traversal here matters and depends on the order of
13210 // lookup results, which happens to be (mostly) oldest-to-newest, but we
13211 // shouldn't rely on that.
13212 for (auto *CurDecl :
13214 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
13215 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
13216 SeenDecls.insert(CurFD).second) {
13217 Pred(CurFD);
13218 }
13219 }
13220}
13221
13223 bool IsCXXMethod) const {
13224 // Pass through to the C++ ABI object
13225 if (IsCXXMethod)
13226 return ABI->getDefaultMethodCallConv(IsVariadic);
13227
13228 switch (LangOpts.getDefaultCallingConv()) {
13230 break;
13232 return CC_C;
13234 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
13235 return CC_X86FastCall;
13236 break;
13238 if (!IsVariadic)
13239 return CC_X86StdCall;
13240 break;
13242 // __vectorcall cannot be applied to variadic functions.
13243 if (!IsVariadic)
13244 return CC_X86VectorCall;
13245 break;
13247 // __regcall cannot be applied to variadic functions.
13248 if (!IsVariadic)
13249 return CC_X86RegCall;
13250 break;
13252 if (!IsVariadic)
13253 return CC_M68kRTD;
13254 break;
13255 }
13256 return Target->getDefaultCallingConv();
13257}
13258
13260 // Pass through to the C++ ABI object
13261 return ABI->isNearlyEmpty(RD);
13262}
13263
13265 if (!VTContext) {
13266 auto ABI = Target->getCXXABI();
13267 if (ABI.isMicrosoft())
13268 VTContext.reset(new MicrosoftVTableContext(*this));
13269 else {
13270 auto ComponentLayout = getLangOpts().RelativeCXXABIVTables
13273 VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout));
13274 }
13275 }
13276 return VTContext.get();
13277}
13278
13280 if (!T)
13281 T = Target;
13282 switch (T->getCXXABI().getKind()) {
13283 case TargetCXXABI::AppleARM64:
13284 case TargetCXXABI::Fuchsia:
13285 case TargetCXXABI::GenericAArch64:
13286 case TargetCXXABI::GenericItanium:
13287 case TargetCXXABI::GenericARM:
13288 case TargetCXXABI::GenericMIPS:
13289 case TargetCXXABI::iOS:
13290 case TargetCXXABI::WebAssembly:
13291 case TargetCXXABI::WatchOS:
13292 case TargetCXXABI::XL:
13294 case TargetCXXABI::Microsoft:
13296 }
13297 llvm_unreachable("Unsupported ABI");
13298}
13299
13301 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
13302 "Device mangle context does not support Microsoft mangling.");
13303 switch (T.getCXXABI().getKind()) {
13304 case TargetCXXABI::AppleARM64:
13305 case TargetCXXABI::Fuchsia:
13306 case TargetCXXABI::GenericAArch64:
13307 case TargetCXXABI::GenericItanium:
13308 case TargetCXXABI::GenericARM:
13309 case TargetCXXABI::GenericMIPS:
13310 case TargetCXXABI::iOS:
13311 case TargetCXXABI::WebAssembly:
13312 case TargetCXXABI::WatchOS:
13313 case TargetCXXABI::XL:
13315 *this, getDiagnostics(),
13316 [](ASTContext &, const NamedDecl *ND) -> UnsignedOrNone {
13317 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
13318 return RD->getDeviceLambdaManglingNumber();
13319 return std::nullopt;
13320 },
13321 /*IsAux=*/true);
13322 case TargetCXXABI::Microsoft:
13324 /*IsAux=*/true);
13325 }
13326 llvm_unreachable("Unsupported ABI");
13327}
13328
13329CXXABI::~CXXABI() = default;
13330
13332 return ASTRecordLayouts.getMemorySize() +
13333 llvm::capacity_in_bytes(ObjCLayouts) +
13334 llvm::capacity_in_bytes(KeyFunctions) +
13335 llvm::capacity_in_bytes(ObjCImpls) +
13336 llvm::capacity_in_bytes(BlockVarCopyInits) +
13337 llvm::capacity_in_bytes(DeclAttrs) +
13338 llvm::capacity_in_bytes(TemplateOrInstantiation) +
13339 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
13340 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
13341 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
13342 llvm::capacity_in_bytes(OverriddenMethods) +
13343 llvm::capacity_in_bytes(Types) +
13344 llvm::capacity_in_bytes(VariableArrayTypes);
13345}
13346
13347/// getIntTypeForBitwidth -
13348/// sets integer QualTy according to specified details:
13349/// bitwidth, signed/unsigned.
13350/// Returns empty type if there is no appropriate target types.
13352 unsigned Signed) const {
13354 CanQualType QualTy = getFromTargetType(Ty);
13355 if (!QualTy && DestWidth == 128)
13356 return Signed ? Int128Ty : UnsignedInt128Ty;
13357 return QualTy;
13358}
13359
13360/// getRealTypeForBitwidth -
13361/// sets floating point QualTy according to specified bitwidth.
13362/// Returns empty type if there is no appropriate target types.
13364 FloatModeKind ExplicitType) const {
13365 FloatModeKind Ty =
13366 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType);
13367 switch (Ty) {
13369 return HalfTy;
13371 return FloatTy;
13373 return DoubleTy;
13375 return LongDoubleTy;
13377 return Float128Ty;
13379 return Ibm128Ty;
13381 return {};
13382 }
13383
13384 llvm_unreachable("Unhandled TargetInfo::RealType value");
13385}
13386
13387void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
13388 if (Number <= 1)
13389 return;
13390
13391 MangleNumbers[ND] = Number;
13392
13393 if (Listener)
13394 Listener->AddedManglingNumber(ND, Number);
13395}
13396
13398 bool ForAuxTarget) const {
13399 auto I = MangleNumbers.find(ND);
13400 unsigned Res = I != MangleNumbers.end() ? I->second : 1;
13401 // CUDA/HIP host compilation encodes host and device mangling numbers
13402 // as lower and upper half of 32 bit integer.
13403 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
13404 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
13405 } else {
13406 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
13407 "number for aux target");
13408 }
13409 return Res > 1 ? Res : 1;
13410}
13411
13412void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
13413 if (Number <= 1)
13414 return;
13415
13416 StaticLocalNumbers[VD] = Number;
13417
13418 if (Listener)
13419 Listener->AddedStaticLocalNumbers(VD, Number);
13420}
13421
13423 auto I = StaticLocalNumbers.find(VD);
13424 return I != StaticLocalNumbers.end() ? I->second : 1;
13425}
13426
13428 bool IsDestroying) {
13429 if (!IsDestroying) {
13430 assert(!DestroyingOperatorDeletes.contains(FD->getCanonicalDecl()));
13431 return;
13432 }
13433 DestroyingOperatorDeletes.insert(FD->getCanonicalDecl());
13434}
13435
13437 return DestroyingOperatorDeletes.contains(FD->getCanonicalDecl());
13438}
13439
13441 bool IsTypeAware) {
13442 if (!IsTypeAware) {
13443 assert(!TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl()));
13444 return;
13445 }
13446 TypeAwareOperatorNewAndDeletes.insert(FD->getCanonicalDecl());
13447}
13448
13450 return TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl());
13451}
13452
13455 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13456 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
13457 if (!MCtx)
13459 return *MCtx;
13460}
13461
13464 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13465 std::unique_ptr<MangleNumberingContext> &MCtx =
13466 ExtraMangleNumberingContexts[D];
13467 if (!MCtx)
13469 return *MCtx;
13470}
13471
13472std::unique_ptr<MangleNumberingContext>
13474 return ABI->createMangleNumberingContext();
13475}
13476
13477const CXXConstructorDecl *
13479 return ABI->getCopyConstructorForExceptionObject(
13480 cast<CXXRecordDecl>(RD->getFirstDecl()));
13481}
13482
13484 CXXConstructorDecl *CD) {
13485 return ABI->addCopyConstructorForExceptionObject(
13486 cast<CXXRecordDecl>(RD->getFirstDecl()),
13487 cast<CXXConstructorDecl>(CD->getFirstDecl()));
13488}
13489
13491 TypedefNameDecl *DD) {
13492 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
13493}
13494
13497 return ABI->getTypedefNameForUnnamedTagDecl(TD);
13498}
13499
13501 DeclaratorDecl *DD) {
13502 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
13503}
13504
13506 return ABI->getDeclaratorForUnnamedTagDecl(TD);
13507}
13508
13509void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
13510 ParamIndices[D] = index;
13511}
13512
13514 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
13515 assert(I != ParamIndices.end() &&
13516 "ParmIndices lacks entry set by ParmVarDecl");
13517 return I->second;
13518}
13519
13521 unsigned Length) const {
13522 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
13523 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
13524 EltTy = EltTy.withConst();
13525
13526 EltTy = adjustStringLiteralBaseType(EltTy);
13527
13528 // Get an array type for the string, according to C99 6.4.5. This includes
13529 // the null terminator character.
13530 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
13531 ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0);
13532}
13533
13536 StringLiteral *&Result = StringLiteralCache[Key];
13537 if (!Result)
13539 *this, Key, StringLiteralKind::Ordinary,
13540 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
13541 SourceLocation());
13542 return Result;
13543}
13544
13545MSGuidDecl *
13547 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
13548
13549 llvm::FoldingSetNodeID ID;
13550 MSGuidDecl::Profile(ID, Parts);
13551
13552 void *InsertPos;
13553 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
13554 return Existing;
13555
13556 QualType GUIDType = getMSGuidType().withConst();
13557 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
13558 MSGuidDecls.InsertNode(New, InsertPos);
13559 return New;
13560}
13561
13564 const APValue &APVal) const {
13565 llvm::FoldingSetNodeID ID;
13567
13568 void *InsertPos;
13569 if (UnnamedGlobalConstantDecl *Existing =
13570 UnnamedGlobalConstantDecls.FindNodeOrInsertPos(ID, InsertPos))
13571 return Existing;
13572
13574 UnnamedGlobalConstantDecl::Create(*this, Ty, APVal);
13575 UnnamedGlobalConstantDecls.InsertNode(New, InsertPos);
13576 return New;
13577}
13578
13581 assert(T->isRecordType() && "template param object of unexpected type");
13582
13583 // C++ [temp.param]p8:
13584 // [...] a static storage duration object of type 'const T' [...]
13585 T.addConst();
13586
13587 llvm::FoldingSetNodeID ID;
13589
13590 void *InsertPos;
13591 if (TemplateParamObjectDecl *Existing =
13592 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
13593 return Existing;
13594
13595 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
13596 TemplateParamObjectDecls.InsertNode(New, InsertPos);
13597 return New;
13598}
13599
13601 const llvm::Triple &T = getTargetInfo().getTriple();
13602 if (!T.isOSDarwin())
13603 return false;
13604
13605 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
13606 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
13607 return false;
13608
13609 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
13610 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
13611 uint64_t Size = sizeChars.getQuantity();
13612 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
13613 unsigned Align = alignChars.getQuantity();
13614 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
13615 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
13616}
13617
13618bool
13620 const ObjCMethodDecl *MethodImpl) {
13621 // No point trying to match an unavailable/deprecated mothod.
13622 if (MethodDecl->hasAttr<UnavailableAttr>()
13623 || MethodDecl->hasAttr<DeprecatedAttr>())
13624 return false;
13625 if (MethodDecl->getObjCDeclQualifier() !=
13626 MethodImpl->getObjCDeclQualifier())
13627 return false;
13628 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
13629 return false;
13630
13631 if (MethodDecl->param_size() != MethodImpl->param_size())
13632 return false;
13633
13634 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
13635 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
13636 EF = MethodDecl->param_end();
13637 IM != EM && IF != EF; ++IM, ++IF) {
13638 const ParmVarDecl *DeclVar = (*IF);
13639 const ParmVarDecl *ImplVar = (*IM);
13640 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
13641 return false;
13642 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
13643 return false;
13644 }
13645
13646 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
13647}
13648
13650 LangAS AS;
13652 AS = LangAS::Default;
13653 else
13654 AS = QT->getPointeeType().getAddressSpace();
13655
13657}
13658
13661}
13662
13663bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
13664 if (X == Y)
13665 return true;
13666 if (!X || !Y)
13667 return false;
13668 llvm::FoldingSetNodeID IDX, IDY;
13669 X->Profile(IDX, *this, /*Canonical=*/true);
13670 Y->Profile(IDY, *this, /*Canonical=*/true);
13671 return IDX == IDY;
13672}
13673
13674// The getCommon* helpers return, for given 'same' X and Y entities given as
13675// inputs, another entity which is also the 'same' as the inputs, but which
13676// is closer to the canonical form of the inputs, each according to a given
13677// criteria.
13678// The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
13679// the regular ones.
13680
13682 if (!declaresSameEntity(X, Y))
13683 return nullptr;
13684 for (const Decl *DX : X->redecls()) {
13685 // If we reach Y before reaching the first decl, that means X is older.
13686 if (DX == Y)
13687 return X;
13688 // If we reach the first decl, then Y is older.
13689 if (DX->isFirstDecl())
13690 return Y;
13691 }
13692 llvm_unreachable("Corrupt redecls chain");
13693}
13694
13695template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13696static T *getCommonDecl(T *X, T *Y) {
13697 return cast_or_null<T>(
13698 getCommonDecl(const_cast<Decl *>(cast_or_null<Decl>(X)),
13699 const_cast<Decl *>(cast_or_null<Decl>(Y))));
13700}
13701
13702template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13703static T *getCommonDeclChecked(T *X, T *Y) {
13704 return cast<T>(getCommonDecl(const_cast<Decl *>(cast<Decl>(X)),
13705 const_cast<Decl *>(cast<Decl>(Y))));
13706}
13707
13709 TemplateName Y,
13710 bool IgnoreDeduced = false) {
13711 if (X.getAsVoidPointer() == Y.getAsVoidPointer())
13712 return X;
13713 // FIXME: There are cases here where we could find a common template name
13714 // with more sugar. For example one could be a SubstTemplateTemplate*
13715 // replacing the other.
13716 TemplateName CX = Ctx.getCanonicalTemplateName(X, IgnoreDeduced);
13717 if (CX.getAsVoidPointer() !=
13719 return TemplateName();
13720 return CX;
13721}
13722
13725 bool IgnoreDeduced) {
13726 TemplateName R = getCommonTemplateName(Ctx, X, Y, IgnoreDeduced);
13727 assert(R.getAsVoidPointer() != nullptr);
13728 return R;
13729}
13730
13732 ArrayRef<QualType> Ys, bool Unqualified = false) {
13733 assert(Xs.size() == Ys.size());
13734 SmallVector<QualType, 8> Rs(Xs.size());
13735 for (size_t I = 0; I < Rs.size(); ++I)
13736 Rs[I] = Ctx.getCommonSugaredType(Xs[I], Ys[I], Unqualified);
13737 return Rs;
13738}
13739
13740template <class T>
13741static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
13742 return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
13743 : SourceLocation();
13744}
13745
13747 const TemplateArgument &X,
13748 const TemplateArgument &Y) {
13749 if (X.getKind() != Y.getKind())
13750 return TemplateArgument();
13751
13752 switch (X.getKind()) {
13754 if (!Ctx.hasSameType(X.getAsType(), Y.getAsType()))
13755 return TemplateArgument();
13756 return TemplateArgument(
13757 Ctx.getCommonSugaredType(X.getAsType(), Y.getAsType()));
13759 if (!Ctx.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
13760 return TemplateArgument();
13761 return TemplateArgument(
13762 Ctx.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
13763 /*Unqualified=*/true);
13765 if (!Ctx.hasSameType(X.getAsExpr()->getType(), Y.getAsExpr()->getType()))
13766 return TemplateArgument();
13767 // FIXME: Try to keep the common sugar.
13768 return X;
13770 TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
13771 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
13772 if (!CTN.getAsVoidPointer())
13773 return TemplateArgument();
13774 return TemplateArgument(CTN);
13775 }
13777 TemplateName TX = X.getAsTemplateOrTemplatePattern(),
13779 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
13780 if (!CTN.getAsVoidPointer())
13781 return TemplateName();
13782 auto NExpX = X.getNumTemplateExpansions();
13783 assert(NExpX == Y.getNumTemplateExpansions());
13784 return TemplateArgument(CTN, NExpX);
13785 }
13786 default:
13787 // FIXME: Handle the other argument kinds.
13788 return X;
13789 }
13790}
13791
13796 if (Xs.size() != Ys.size())
13797 return true;
13798 R.resize(Xs.size());
13799 for (size_t I = 0; I < R.size(); ++I) {
13800 R[I] = getCommonTemplateArgument(Ctx, Xs[I], Ys[I]);
13801 if (R[I].isNull())
13802 return true;
13803 }
13804 return false;
13805}
13806
13811 bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
13812 assert(!Different);
13813 (void)Different;
13814 return R;
13815}
13816
13817template <class T>
13819 bool IsSame) {
13820 ElaboratedTypeKeyword KX = X->getKeyword(), KY = Y->getKeyword();
13821 if (KX == KY)
13822 return KX;
13824 assert(!IsSame || KX == getCanonicalElaboratedTypeKeyword(KY));
13825 return KX;
13826}
13827
13828/// Returns a NestedNameSpecifier which has only the common sugar
13829/// present in both NNS1 and NNS2.
13832 NestedNameSpecifier NNS2, bool IsSame) {
13833 // If they are identical, all sugar is common.
13834 if (NNS1 == NNS2)
13835 return NNS1;
13836
13837 // IsSame implies both Qualifiers are equivalent.
13838 NestedNameSpecifier Canon = NNS1.getCanonical();
13839 if (Canon != NNS2.getCanonical()) {
13840 assert(!IsSame && "Should be the same NestedNameSpecifier");
13841 // If they are not the same, there is nothing to unify.
13842 return std::nullopt;
13843 }
13844
13845 NestedNameSpecifier R = std::nullopt;
13846 NestedNameSpecifier::Kind Kind = NNS1.getKind();
13847 assert(Kind == NNS2.getKind());
13848 switch (Kind) {
13850 auto [Namespace1, Prefix1] = NNS1.getAsNamespaceAndPrefix();
13851 auto [Namespace2, Prefix2] = NNS2.getAsNamespaceAndPrefix();
13852 auto Kind = Namespace1->getKind();
13853 if (Kind != Namespace2->getKind() ||
13854 (Kind == Decl::NamespaceAlias &&
13855 !declaresSameEntity(Namespace1, Namespace2))) {
13857 Ctx,
13858 ::getCommonDeclChecked(Namespace1->getNamespace(),
13859 Namespace2->getNamespace()),
13860 /*Prefix=*/std::nullopt);
13861 break;
13862 }
13863 // The prefixes for namespaces are not significant, its declaration
13864 // identifies it uniquely.
13865 NestedNameSpecifier Prefix = ::getCommonNNS(Ctx, Prefix1, Prefix2,
13866 /*IsSame=*/false);
13867 R = NestedNameSpecifier(Ctx, ::getCommonDeclChecked(Namespace1, Namespace2),
13868 Prefix);
13869 break;
13870 }
13872 const Type *T1 = NNS1.getAsType(), *T2 = NNS2.getAsType();
13873 const Type *T = Ctx.getCommonSugaredType(QualType(T1, 0), QualType(T2, 0),
13874 /*Unqualified=*/true)
13875 .getTypePtr();
13877 break;
13878 }
13880 // FIXME: Can __super even be used with data members?
13881 // If it's only usable in functions, we will never see it here,
13882 // unless we save the qualifiers used in function types.
13883 // In that case, it might be possible NNS2 is a type,
13884 // in which case we should degrade the result to
13885 // a CXXRecordType.
13887 NNS2.getAsMicrosoftSuper()));
13888 break;
13889 }
13892 // These are singletons.
13893 llvm_unreachable("singletons did not compare equal");
13894 }
13895 assert(R.getCanonical() == Canon);
13896 return R;
13897}
13898
13899template <class T>
13901 const T *Y, bool IsSame) {
13902 return ::getCommonNNS(Ctx, X->getQualifier(), Y->getQualifier(), IsSame);
13903}
13904
13905template <class T>
13906static QualType getCommonElementType(const ASTContext &Ctx, const T *X,
13907 const T *Y) {
13908 return Ctx.getCommonSugaredType(X->getElementType(), Y->getElementType());
13909}
13910
13911template <class T>
13913 Qualifiers &QX, const T *Y,
13914 Qualifiers &QY) {
13915 QualType EX = X->getElementType(), EY = Y->getElementType();
13916 QualType R = Ctx.getCommonSugaredType(EX, EY,
13917 /*Unqualified=*/true);
13918 // Qualifiers common to both element types.
13919 Qualifiers RQ = R.getQualifiers();
13920 // For each side, move to the top level any qualifiers which are not common to
13921 // both element types. The caller must assume top level qualifiers might
13922 // be different, even if they are the same type, and can be treated as sugar.
13923 QX += EX.getQualifiers() - RQ;
13924 QY += EY.getQualifiers() - RQ;
13925 return R;
13926}
13927
13928template <class T>
13929static QualType getCommonPointeeType(const ASTContext &Ctx, const T *X,
13930 const T *Y) {
13931 return Ctx.getCommonSugaredType(X->getPointeeType(), Y->getPointeeType());
13932}
13933
13934template <class T>
13935static auto *getCommonSizeExpr(const ASTContext &Ctx, T *X, T *Y) {
13936 assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
13937 return X->getSizeExpr();
13938}
13939
13940static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
13941 assert(X->getSizeModifier() == Y->getSizeModifier());
13942 return X->getSizeModifier();
13943}
13944
13946 const ArrayType *Y) {
13947 assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
13948 return X->getIndexTypeCVRQualifiers();
13949}
13950
13951// Merges two type lists such that the resulting vector will contain
13952// each type (in a canonical sense) only once, in the order they appear
13953// from X to Y. If they occur in both X and Y, the result will contain
13954// the common sugared type between them.
13955static void mergeTypeLists(const ASTContext &Ctx,
13958 llvm::DenseMap<QualType, unsigned> Found;
13959 for (auto Ts : {X, Y}) {
13960 for (QualType T : Ts) {
13961 auto Res = Found.try_emplace(Ctx.getCanonicalType(T), Out.size());
13962 if (!Res.second) {
13963 QualType &U = Out[Res.first->second];
13964 U = Ctx.getCommonSugaredType(U, T);
13965 } else {
13966 Out.emplace_back(T);
13967 }
13968 }
13969 }
13970}
13971
13975 SmallVectorImpl<QualType> &ExceptionTypeStorage,
13976 bool AcceptDependent) const {
13977 ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
13978
13979 // If either of them can throw anything, that is the result.
13980 for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
13981 if (EST1 == I)
13982 return ESI1;
13983 if (EST2 == I)
13984 return ESI2;
13985 }
13986
13987 // If either of them is non-throwing, the result is the other.
13988 for (auto I :
13990 if (EST1 == I)
13991 return ESI2;
13992 if (EST2 == I)
13993 return ESI1;
13994 }
13995
13996 // If we're left with value-dependent computed noexcept expressions, we're
13997 // stuck. Before C++17, we can just drop the exception specification entirely,
13998 // since it's not actually part of the canonical type. And this should never
13999 // happen in C++17, because it would mean we were computing the composite
14000 // pointer type of dependent types, which should never happen.
14001 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
14002 assert(AcceptDependent &&
14003 "computing composite pointer type of dependent types");
14005 }
14006
14007 // Switch over the possibilities so that people adding new values know to
14008 // update this function.
14009 switch (EST1) {
14010 case EST_None:
14011 case EST_DynamicNone:
14012 case EST_MSAny:
14013 case EST_BasicNoexcept:
14015 case EST_NoexceptFalse:
14016 case EST_NoexceptTrue:
14017 case EST_NoThrow:
14018 llvm_unreachable("These ESTs should be handled above");
14019
14020 case EST_Dynamic: {
14021 // This is the fun case: both exception specifications are dynamic. Form
14022 // the union of the two lists.
14023 assert(EST2 == EST_Dynamic && "other cases should already be handled");
14024 mergeTypeLists(*this, ExceptionTypeStorage, ESI1.Exceptions,
14025 ESI2.Exceptions);
14027 Result.Exceptions = ExceptionTypeStorage;
14028 return Result;
14029 }
14030
14031 case EST_Unevaluated:
14032 case EST_Uninstantiated:
14033 case EST_Unparsed:
14034 llvm_unreachable("shouldn't see unresolved exception specifications here");
14035 }
14036
14037 llvm_unreachable("invalid ExceptionSpecificationType");
14038}
14039
14041 Qualifiers &QX, const Type *Y,
14042 Qualifiers &QY) {
14043 Type::TypeClass TC = X->getTypeClass();
14044 assert(TC == Y->getTypeClass());
14045 switch (TC) {
14046#define UNEXPECTED_TYPE(Class, Kind) \
14047 case Type::Class: \
14048 llvm_unreachable("Unexpected " Kind ": " #Class);
14049
14050#define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
14051#define TYPE(Class, Base)
14052#include "clang/AST/TypeNodes.inc"
14053
14054#define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
14056 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
14057 SUGAR_FREE_TYPE(DependentBitInt)
14059 SUGAR_FREE_TYPE(ObjCInterface)
14060 SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
14061 SUGAR_FREE_TYPE(SubstBuiltinTemplatePack)
14062 SUGAR_FREE_TYPE(UnresolvedUsing)
14063 SUGAR_FREE_TYPE(HLSLAttributedResource)
14064 SUGAR_FREE_TYPE(HLSLInlineSpirv)
14065#undef SUGAR_FREE_TYPE
14066#define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
14067 NON_UNIQUE_TYPE(TypeOfExpr)
14068 NON_UNIQUE_TYPE(VariableArray)
14069#undef NON_UNIQUE_TYPE
14070
14071 UNEXPECTED_TYPE(TypeOf, "sugar")
14072
14073#undef UNEXPECTED_TYPE
14074
14075 case Type::Auto: {
14076 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14077 assert(AX->getDeducedType().isNull());
14078 assert(AY->getDeducedType().isNull());
14079 assert(AX->getKeyword() == AY->getKeyword());
14080 assert(AX->isInstantiationDependentType() ==
14081 AY->isInstantiationDependentType());
14082 auto As = getCommonTemplateArguments(Ctx, AX->getTypeConstraintArguments(),
14083 AY->getTypeConstraintArguments());
14084 return Ctx.getAutoType(QualType(), AX->getKeyword(),
14086 AX->containsUnexpandedParameterPack(),
14087 getCommonDeclChecked(AX->getTypeConstraintConcept(),
14088 AY->getTypeConstraintConcept()),
14089 As);
14090 }
14091 case Type::IncompleteArray: {
14092 const auto *AX = cast<IncompleteArrayType>(X),
14093 *AY = cast<IncompleteArrayType>(Y);
14094 return Ctx.getIncompleteArrayType(
14095 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14097 }
14098 case Type::DependentSizedArray: {
14099 const auto *AX = cast<DependentSizedArrayType>(X),
14100 *AY = cast<DependentSizedArrayType>(Y);
14101 return Ctx.getDependentSizedArrayType(
14102 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14103 getCommonSizeExpr(Ctx, AX, AY), getCommonSizeModifier(AX, AY),
14105 }
14106 case Type::ConstantArray: {
14107 const auto *AX = cast<ConstantArrayType>(X),
14108 *AY = cast<ConstantArrayType>(Y);
14109 assert(AX->getSize() == AY->getSize());
14110 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14111 ? AX->getSizeExpr()
14112 : nullptr;
14113 return Ctx.getConstantArrayType(
14114 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14116 }
14117 case Type::ArrayParameter: {
14118 const auto *AX = cast<ArrayParameterType>(X),
14119 *AY = cast<ArrayParameterType>(Y);
14120 assert(AX->getSize() == AY->getSize());
14121 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14122 ? AX->getSizeExpr()
14123 : nullptr;
14124 auto ArrayTy = Ctx.getConstantArrayType(
14125 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14127 return Ctx.getArrayParameterType(ArrayTy);
14128 }
14129 case Type::Atomic: {
14130 const auto *AX = cast<AtomicType>(X), *AY = cast<AtomicType>(Y);
14131 return Ctx.getAtomicType(
14132 Ctx.getCommonSugaredType(AX->getValueType(), AY->getValueType()));
14133 }
14134 case Type::Complex: {
14135 const auto *CX = cast<ComplexType>(X), *CY = cast<ComplexType>(Y);
14136 return Ctx.getComplexType(getCommonArrayElementType(Ctx, CX, QX, CY, QY));
14137 }
14138 case Type::Pointer: {
14139 const auto *PX = cast<PointerType>(X), *PY = cast<PointerType>(Y);
14140 return Ctx.getPointerType(getCommonPointeeType(Ctx, PX, PY));
14141 }
14142 case Type::BlockPointer: {
14143 const auto *PX = cast<BlockPointerType>(X), *PY = cast<BlockPointerType>(Y);
14144 return Ctx.getBlockPointerType(getCommonPointeeType(Ctx, PX, PY));
14145 }
14146 case Type::ObjCObjectPointer: {
14147 const auto *PX = cast<ObjCObjectPointerType>(X),
14148 *PY = cast<ObjCObjectPointerType>(Y);
14149 return Ctx.getObjCObjectPointerType(getCommonPointeeType(Ctx, PX, PY));
14150 }
14151 case Type::MemberPointer: {
14152 const auto *PX = cast<MemberPointerType>(X),
14153 *PY = cast<MemberPointerType>(Y);
14154 assert(declaresSameEntity(PX->getMostRecentCXXRecordDecl(),
14155 PY->getMostRecentCXXRecordDecl()));
14156 return Ctx.getMemberPointerType(
14157 getCommonPointeeType(Ctx, PX, PY),
14158 getCommonQualifier(Ctx, PX, PY, /*IsSame=*/true),
14159 PX->getMostRecentCXXRecordDecl());
14160 }
14161 case Type::LValueReference: {
14162 const auto *PX = cast<LValueReferenceType>(X),
14163 *PY = cast<LValueReferenceType>(Y);
14164 // FIXME: Preserve PointeeTypeAsWritten.
14165 return Ctx.getLValueReferenceType(getCommonPointeeType(Ctx, PX, PY),
14166 PX->isSpelledAsLValue() ||
14167 PY->isSpelledAsLValue());
14168 }
14169 case Type::RValueReference: {
14170 const auto *PX = cast<RValueReferenceType>(X),
14171 *PY = cast<RValueReferenceType>(Y);
14172 // FIXME: Preserve PointeeTypeAsWritten.
14173 return Ctx.getRValueReferenceType(getCommonPointeeType(Ctx, PX, PY));
14174 }
14175 case Type::DependentAddressSpace: {
14176 const auto *PX = cast<DependentAddressSpaceType>(X),
14177 *PY = cast<DependentAddressSpaceType>(Y);
14178 assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
14179 return Ctx.getDependentAddressSpaceType(getCommonPointeeType(Ctx, PX, PY),
14180 PX->getAddrSpaceExpr(),
14181 getCommonAttrLoc(PX, PY));
14182 }
14183 case Type::FunctionNoProto: {
14184 const auto *FX = cast<FunctionNoProtoType>(X),
14185 *FY = cast<FunctionNoProtoType>(Y);
14186 assert(FX->getExtInfo() == FY->getExtInfo());
14187 return Ctx.getFunctionNoProtoType(
14188 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType()),
14189 FX->getExtInfo());
14190 }
14191 case Type::FunctionProto: {
14192 const auto *FX = cast<FunctionProtoType>(X),
14193 *FY = cast<FunctionProtoType>(Y);
14194 FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
14195 EPIY = FY->getExtProtoInfo();
14196 assert(EPIX.ExtInfo == EPIY.ExtInfo);
14197 assert(EPIX.ExtParameterInfos == EPIY.ExtParameterInfos);
14198 assert(EPIX.RefQualifier == EPIY.RefQualifier);
14199 assert(EPIX.TypeQuals == EPIY.TypeQuals);
14200 assert(EPIX.Variadic == EPIY.Variadic);
14201
14202 // FIXME: Can we handle an empty EllipsisLoc?
14203 // Use emtpy EllipsisLoc if X and Y differ.
14204
14205 EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
14206
14207 QualType R =
14208 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType());
14209 auto P = getCommonTypes(Ctx, FX->param_types(), FY->param_types(),
14210 /*Unqualified=*/true);
14211
14212 SmallVector<QualType, 8> Exceptions;
14214 EPIX.ExceptionSpec, EPIY.ExceptionSpec, Exceptions, true);
14215 return Ctx.getFunctionType(R, P, EPIX);
14216 }
14217 case Type::ObjCObject: {
14218 const auto *OX = cast<ObjCObjectType>(X), *OY = cast<ObjCObjectType>(Y);
14219 assert(
14220 std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
14221 OY->getProtocols().begin(), OY->getProtocols().end(),
14222 [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
14223 return P0->getCanonicalDecl() == P1->getCanonicalDecl();
14224 }) &&
14225 "protocol lists must be the same");
14226 auto TAs = getCommonTypes(Ctx, OX->getTypeArgsAsWritten(),
14227 OY->getTypeArgsAsWritten());
14228 return Ctx.getObjCObjectType(
14229 Ctx.getCommonSugaredType(OX->getBaseType(), OY->getBaseType()), TAs,
14230 OX->getProtocols(),
14231 OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
14232 }
14233 case Type::ConstantMatrix: {
14234 const auto *MX = cast<ConstantMatrixType>(X),
14235 *MY = cast<ConstantMatrixType>(Y);
14236 assert(MX->getNumRows() == MY->getNumRows());
14237 assert(MX->getNumColumns() == MY->getNumColumns());
14238 return Ctx.getConstantMatrixType(getCommonElementType(Ctx, MX, MY),
14239 MX->getNumRows(), MX->getNumColumns());
14240 }
14241 case Type::DependentSizedMatrix: {
14242 const auto *MX = cast<DependentSizedMatrixType>(X),
14243 *MY = cast<DependentSizedMatrixType>(Y);
14244 assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
14245 assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
14246 return Ctx.getDependentSizedMatrixType(
14247 getCommonElementType(Ctx, MX, MY), MX->getRowExpr(),
14248 MX->getColumnExpr(), getCommonAttrLoc(MX, MY));
14249 }
14250 case Type::Vector: {
14251 const auto *VX = cast<VectorType>(X), *VY = cast<VectorType>(Y);
14252 assert(VX->getNumElements() == VY->getNumElements());
14253 assert(VX->getVectorKind() == VY->getVectorKind());
14254 return Ctx.getVectorType(getCommonElementType(Ctx, VX, VY),
14255 VX->getNumElements(), VX->getVectorKind());
14256 }
14257 case Type::ExtVector: {
14258 const auto *VX = cast<ExtVectorType>(X), *VY = cast<ExtVectorType>(Y);
14259 assert(VX->getNumElements() == VY->getNumElements());
14260 return Ctx.getExtVectorType(getCommonElementType(Ctx, VX, VY),
14261 VX->getNumElements());
14262 }
14263 case Type::DependentSizedExtVector: {
14264 const auto *VX = cast<DependentSizedExtVectorType>(X),
14265 *VY = cast<DependentSizedExtVectorType>(Y);
14267 getCommonSizeExpr(Ctx, VX, VY),
14268 getCommonAttrLoc(VX, VY));
14269 }
14270 case Type::DependentVector: {
14271 const auto *VX = cast<DependentVectorType>(X),
14272 *VY = cast<DependentVectorType>(Y);
14273 assert(VX->getVectorKind() == VY->getVectorKind());
14274 return Ctx.getDependentVectorType(
14275 getCommonElementType(Ctx, VX, VY), getCommonSizeExpr(Ctx, VX, VY),
14276 getCommonAttrLoc(VX, VY), VX->getVectorKind());
14277 }
14278 case Type::Enum:
14279 case Type::Record:
14280 case Type::InjectedClassName: {
14281 const auto *TX = cast<TagType>(X), *TY = cast<TagType>(Y);
14282 return Ctx.getTagType(
14283 ::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14284 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false),
14285 ::getCommonDeclChecked(TX->getOriginalDecl(), TY->getOriginalDecl()),
14286 /*OwnedTag=*/false);
14287 }
14288 case Type::TemplateSpecialization: {
14289 const auto *TX = cast<TemplateSpecializationType>(X),
14290 *TY = cast<TemplateSpecializationType>(Y);
14291 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
14292 TY->template_arguments());
14294 getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14295 ::getCommonTemplateNameChecked(Ctx, TX->getTemplateName(),
14296 TY->getTemplateName(),
14297 /*IgnoreDeduced=*/true),
14298 As, /*CanonicalArgs=*/{}, X->getCanonicalTypeInternal());
14299 }
14300 case Type::Decltype: {
14301 const auto *DX = cast<DecltypeType>(X);
14302 [[maybe_unused]] const auto *DY = cast<DecltypeType>(Y);
14303 assert(DX->isDependentType());
14304 assert(DY->isDependentType());
14305 assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
14306 // As Decltype is not uniqued, building a common type would be wasteful.
14307 return QualType(DX, 0);
14308 }
14309 case Type::PackIndexing: {
14310 const auto *DX = cast<PackIndexingType>(X);
14311 [[maybe_unused]] const auto *DY = cast<PackIndexingType>(Y);
14312 assert(DX->isDependentType());
14313 assert(DY->isDependentType());
14314 assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr()));
14315 return QualType(DX, 0);
14316 }
14317 case Type::DependentName: {
14318 const auto *NX = cast<DependentNameType>(X),
14319 *NY = cast<DependentNameType>(Y);
14320 assert(NX->getIdentifier() == NY->getIdentifier());
14321 return Ctx.getDependentNameType(
14322 getCommonTypeKeyword(NX, NY, /*IsSame=*/true),
14323 getCommonQualifier(Ctx, NX, NY, /*IsSame=*/true), NX->getIdentifier());
14324 }
14325 case Type::DependentTemplateSpecialization: {
14326 const auto *TX = cast<DependentTemplateSpecializationType>(X),
14327 *TY = cast<DependentTemplateSpecializationType>(Y);
14328 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
14329 TY->template_arguments());
14330 const DependentTemplateStorage &SX = TX->getDependentTemplateName(),
14331 &SY = TY->getDependentTemplateName();
14332 assert(SX.getName() == SY.getName());
14334 getCommonNNS(Ctx, SX.getQualifier(), SY.getQualifier(),
14335 /*IsSame=*/true),
14336 SX.getName(), SX.hasTemplateKeyword() || SY.hasTemplateKeyword());
14338 getCommonTypeKeyword(TX, TY, /*IsSame=*/true), Name, As);
14339 }
14340 case Type::UnaryTransform: {
14341 const auto *TX = cast<UnaryTransformType>(X),
14342 *TY = cast<UnaryTransformType>(Y);
14343 assert(TX->getUTTKind() == TY->getUTTKind());
14344 return Ctx.getUnaryTransformType(
14345 Ctx.getCommonSugaredType(TX->getBaseType(), TY->getBaseType()),
14346 Ctx.getCommonSugaredType(TX->getUnderlyingType(),
14347 TY->getUnderlyingType()),
14348 TX->getUTTKind());
14349 }
14350 case Type::PackExpansion: {
14351 const auto *PX = cast<PackExpansionType>(X),
14352 *PY = cast<PackExpansionType>(Y);
14353 assert(PX->getNumExpansions() == PY->getNumExpansions());
14354 return Ctx.getPackExpansionType(
14355 Ctx.getCommonSugaredType(PX->getPattern(), PY->getPattern()),
14356 PX->getNumExpansions(), false);
14357 }
14358 case Type::Pipe: {
14359 const auto *PX = cast<PipeType>(X), *PY = cast<PipeType>(Y);
14360 assert(PX->isReadOnly() == PY->isReadOnly());
14361 auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
14363 return (Ctx.*MP)(getCommonElementType(Ctx, PX, PY));
14364 }
14365 case Type::TemplateTypeParm: {
14366 const auto *TX = cast<TemplateTypeParmType>(X),
14367 *TY = cast<TemplateTypeParmType>(Y);
14368 assert(TX->getDepth() == TY->getDepth());
14369 assert(TX->getIndex() == TY->getIndex());
14370 assert(TX->isParameterPack() == TY->isParameterPack());
14371 return Ctx.getTemplateTypeParmType(
14372 TX->getDepth(), TX->getIndex(), TX->isParameterPack(),
14373 getCommonDecl(TX->getDecl(), TY->getDecl()));
14374 }
14375 }
14376 llvm_unreachable("Unknown Type Class");
14377}
14378
14380 const Type *Y,
14381 SplitQualType Underlying) {
14382 Type::TypeClass TC = X->getTypeClass();
14383 if (TC != Y->getTypeClass())
14384 return QualType();
14385 switch (TC) {
14386#define UNEXPECTED_TYPE(Class, Kind) \
14387 case Type::Class: \
14388 llvm_unreachable("Unexpected " Kind ": " #Class);
14389#define TYPE(Class, Base)
14390#define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
14391#include "clang/AST/TypeNodes.inc"
14392
14393#define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
14396 CANONICAL_TYPE(BlockPointer)
14399 CANONICAL_TYPE(ConstantArray)
14400 CANONICAL_TYPE(ArrayParameter)
14401 CANONICAL_TYPE(ConstantMatrix)
14403 CANONICAL_TYPE(ExtVector)
14404 CANONICAL_TYPE(FunctionNoProto)
14405 CANONICAL_TYPE(FunctionProto)
14406 CANONICAL_TYPE(IncompleteArray)
14407 CANONICAL_TYPE(HLSLAttributedResource)
14408 CANONICAL_TYPE(HLSLInlineSpirv)
14409 CANONICAL_TYPE(LValueReference)
14410 CANONICAL_TYPE(ObjCInterface)
14411 CANONICAL_TYPE(ObjCObject)
14412 CANONICAL_TYPE(ObjCObjectPointer)
14416 CANONICAL_TYPE(RValueReference)
14417 CANONICAL_TYPE(VariableArray)
14419#undef CANONICAL_TYPE
14420
14421#undef UNEXPECTED_TYPE
14422
14423 case Type::Adjusted: {
14424 const auto *AX = cast<AdjustedType>(X), *AY = cast<AdjustedType>(Y);
14425 QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
14426 if (!Ctx.hasSameType(OX, OY))
14427 return QualType();
14428 // FIXME: It's inefficient to have to unify the original types.
14429 return Ctx.getAdjustedType(Ctx.getCommonSugaredType(OX, OY),
14430 Ctx.getQualifiedType(Underlying));
14431 }
14432 case Type::Decayed: {
14433 const auto *DX = cast<DecayedType>(X), *DY = cast<DecayedType>(Y);
14434 QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
14435 if (!Ctx.hasSameType(OX, OY))
14436 return QualType();
14437 // FIXME: It's inefficient to have to unify the original types.
14438 return Ctx.getDecayedType(Ctx.getCommonSugaredType(OX, OY),
14439 Ctx.getQualifiedType(Underlying));
14440 }
14441 case Type::Attributed: {
14442 const auto *AX = cast<AttributedType>(X), *AY = cast<AttributedType>(Y);
14443 AttributedType::Kind Kind = AX->getAttrKind();
14444 if (Kind != AY->getAttrKind())
14445 return QualType();
14446 QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
14447 if (!Ctx.hasSameType(MX, MY))
14448 return QualType();
14449 // FIXME: It's inefficient to have to unify the modified types.
14450 return Ctx.getAttributedType(Kind, Ctx.getCommonSugaredType(MX, MY),
14451 Ctx.getQualifiedType(Underlying),
14452 AX->getAttr());
14453 }
14454 case Type::BTFTagAttributed: {
14455 const auto *BX = cast<BTFTagAttributedType>(X);
14456 const BTFTypeTagAttr *AX = BX->getAttr();
14457 // The attribute is not uniqued, so just compare the tag.
14458 if (AX->getBTFTypeTag() !=
14459 cast<BTFTagAttributedType>(Y)->getAttr()->getBTFTypeTag())
14460 return QualType();
14461 return Ctx.getBTFTagAttributedType(AX, Ctx.getQualifiedType(Underlying));
14462 }
14463 case Type::Auto: {
14464 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14465
14466 AutoTypeKeyword KW = AX->getKeyword();
14467 if (KW != AY->getKeyword())
14468 return QualType();
14469
14470 TemplateDecl *CD = ::getCommonDecl(AX->getTypeConstraintConcept(),
14471 AY->getTypeConstraintConcept());
14473 if (CD &&
14474 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
14475 AY->getTypeConstraintArguments())) {
14476 CD = nullptr; // The arguments differ, so make it unconstrained.
14477 As.clear();
14478 }
14479
14480 // Both auto types can't be dependent, otherwise they wouldn't have been
14481 // sugar. This implies they can't contain unexpanded packs either.
14482 return Ctx.getAutoType(Ctx.getQualifiedType(Underlying), AX->getKeyword(),
14483 /*IsDependent=*/false, /*IsPack=*/false, CD, As);
14484 }
14485 case Type::PackIndexing:
14486 case Type::Decltype:
14487 return QualType();
14488 case Type::DeducedTemplateSpecialization:
14489 // FIXME: Try to merge these.
14490 return QualType();
14491 case Type::MacroQualified: {
14492 const auto *MX = cast<MacroQualifiedType>(X),
14493 *MY = cast<MacroQualifiedType>(Y);
14494 const IdentifierInfo *IX = MX->getMacroIdentifier();
14495 if (IX != MY->getMacroIdentifier())
14496 return QualType();
14497 return Ctx.getMacroQualifiedType(Ctx.getQualifiedType(Underlying), IX);
14498 }
14499 case Type::SubstTemplateTypeParm: {
14500 const auto *SX = cast<SubstTemplateTypeParmType>(X),
14501 *SY = cast<SubstTemplateTypeParmType>(Y);
14502 Decl *CD =
14503 ::getCommonDecl(SX->getAssociatedDecl(), SY->getAssociatedDecl());
14504 if (!CD)
14505 return QualType();
14506 unsigned Index = SX->getIndex();
14507 if (Index != SY->getIndex())
14508 return QualType();
14509 auto PackIndex = SX->getPackIndex();
14510 if (PackIndex != SY->getPackIndex())
14511 return QualType();
14512 return Ctx.getSubstTemplateTypeParmType(Ctx.getQualifiedType(Underlying),
14513 CD, Index, PackIndex,
14514 SX->getFinal() && SY->getFinal());
14515 }
14516 case Type::ObjCTypeParam:
14517 // FIXME: Try to merge these.
14518 return QualType();
14519 case Type::Paren:
14520 return Ctx.getParenType(Ctx.getQualifiedType(Underlying));
14521
14522 case Type::TemplateSpecialization: {
14523 const auto *TX = cast<TemplateSpecializationType>(X),
14524 *TY = cast<TemplateSpecializationType>(Y);
14525 TemplateName CTN =
14526 ::getCommonTemplateName(Ctx, TX->getTemplateName(),
14527 TY->getTemplateName(), /*IgnoreDeduced=*/true);
14528 if (!CTN.getAsVoidPointer())
14529 return QualType();
14531 if (getCommonTemplateArguments(Ctx, As, TX->template_arguments(),
14532 TY->template_arguments()))
14533 return QualType();
14535 getCommonTypeKeyword(TX, TY, /*IsSame=*/false), CTN, As,
14536 /*CanonicalArgs=*/{}, Ctx.getQualifiedType(Underlying));
14537 }
14538 case Type::Typedef: {
14539 const auto *TX = cast<TypedefType>(X), *TY = cast<TypedefType>(Y);
14540 const TypedefNameDecl *CD = ::getCommonDecl(TX->getDecl(), TY->getDecl());
14541 if (!CD)
14542 return QualType();
14543 return Ctx.getTypedefType(
14544 ::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14545 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false), CD,
14546 Ctx.getQualifiedType(Underlying));
14547 }
14548 case Type::TypeOf: {
14549 // The common sugar between two typeof expressions, where one is
14550 // potentially a typeof_unqual and the other is not, we unify to the
14551 // qualified type as that retains the most information along with the type.
14552 // We only return a typeof_unqual type when both types are unqual types.
14554 if (cast<TypeOfType>(X)->getKind() == cast<TypeOfType>(Y)->getKind() &&
14555 cast<TypeOfType>(X)->getKind() == TypeOfKind::Unqualified)
14557 return Ctx.getTypeOfType(Ctx.getQualifiedType(Underlying), Kind);
14558 }
14559 case Type::TypeOfExpr:
14560 return QualType();
14561
14562 case Type::UnaryTransform: {
14563 const auto *UX = cast<UnaryTransformType>(X),
14564 *UY = cast<UnaryTransformType>(Y);
14565 UnaryTransformType::UTTKind KX = UX->getUTTKind();
14566 if (KX != UY->getUTTKind())
14567 return QualType();
14568 QualType BX = UX->getBaseType(), BY = UY->getBaseType();
14569 if (!Ctx.hasSameType(BX, BY))
14570 return QualType();
14571 // FIXME: It's inefficient to have to unify the base types.
14572 return Ctx.getUnaryTransformType(Ctx.getCommonSugaredType(BX, BY),
14573 Ctx.getQualifiedType(Underlying), KX);
14574 }
14575 case Type::Using: {
14576 const auto *UX = cast<UsingType>(X), *UY = cast<UsingType>(Y);
14577 const UsingShadowDecl *CD = ::getCommonDecl(UX->getDecl(), UY->getDecl());
14578 if (!CD)
14579 return QualType();
14580 return Ctx.getUsingType(::getCommonTypeKeyword(UX, UY, /*IsSame=*/false),
14581 ::getCommonQualifier(Ctx, UX, UY, /*IsSame=*/false),
14582 CD, Ctx.getQualifiedType(Underlying));
14583 }
14584 case Type::MemberPointer: {
14585 const auto *PX = cast<MemberPointerType>(X),
14586 *PY = cast<MemberPointerType>(Y);
14587 CXXRecordDecl *Cls = PX->getMostRecentCXXRecordDecl();
14588 assert(Cls == PY->getMostRecentCXXRecordDecl());
14589 return Ctx.getMemberPointerType(
14590 ::getCommonPointeeType(Ctx, PX, PY),
14591 ::getCommonQualifier(Ctx, PX, PY, /*IsSame=*/false), Cls);
14592 }
14593 case Type::CountAttributed: {
14594 const auto *DX = cast<CountAttributedType>(X),
14595 *DY = cast<CountAttributedType>(Y);
14596 if (DX->isCountInBytes() != DY->isCountInBytes())
14597 return QualType();
14598 if (DX->isOrNull() != DY->isOrNull())
14599 return QualType();
14600 Expr *CEX = DX->getCountExpr();
14601 Expr *CEY = DY->getCountExpr();
14602 ArrayRef<clang::TypeCoupledDeclRefInfo> CDX = DX->getCoupledDecls();
14603 if (Ctx.hasSameExpr(CEX, CEY))
14604 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14605 DX->isCountInBytes(), DX->isOrNull(),
14606 CDX);
14607 if (!CEX->isIntegerConstantExpr(Ctx) || !CEY->isIntegerConstantExpr(Ctx))
14608 return QualType();
14609 // Two declarations with the same integer constant may still differ in their
14610 // expression pointers, so we need to evaluate them.
14611 llvm::APSInt VX = *CEX->getIntegerConstantExpr(Ctx);
14612 llvm::APSInt VY = *CEY->getIntegerConstantExpr(Ctx);
14613 if (VX != VY)
14614 return QualType();
14615 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14616 DX->isCountInBytes(), DX->isOrNull(),
14617 CDX);
14618 }
14619 case Type::PredefinedSugar:
14620 assert(cast<PredefinedSugarType>(X)->getKind() !=
14621 cast<PredefinedSugarType>(Y)->getKind());
14622 return QualType();
14623 }
14624 llvm_unreachable("Unhandled Type Class");
14625}
14626
14627static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
14629 while (true) {
14630 QTotal.addConsistentQualifiers(T.Quals);
14632 if (NT == QualType(T.Ty, 0))
14633 break;
14634 R.push_back(T);
14635 T = NT.split();
14636 }
14637 return R;
14638}
14639
14641 bool Unqualified) const {
14642 assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
14643 if (X == Y)
14644 return X;
14645 if (!Unqualified) {
14646 if (X.isCanonical())
14647 return X;
14648 if (Y.isCanonical())
14649 return Y;
14650 }
14651
14652 SplitQualType SX = X.split(), SY = Y.split();
14653 Qualifiers QX, QY;
14654 // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
14655 // until we reach their underlying "canonical nodes". Note these are not
14656 // necessarily canonical types, as they may still have sugared properties.
14657 // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
14658 auto Xs = ::unwrapSugar(SX, QX), Ys = ::unwrapSugar(SY, QY);
14659
14660 // If this is an ArrayType, the element qualifiers are interchangeable with
14661 // the top level qualifiers.
14662 // * In case the canonical nodes are the same, the elements types are already
14663 // the same.
14664 // * Otherwise, the element types will be made the same, and any different
14665 // element qualifiers will be moved up to the top level qualifiers, per
14666 // 'getCommonArrayElementType'.
14667 // In both cases, this means there may be top level qualifiers which differ
14668 // between X and Y. If so, these differing qualifiers are redundant with the
14669 // element qualifiers, and can be removed without changing the canonical type.
14670 // The desired behaviour is the same as for the 'Unqualified' case here:
14671 // treat the redundant qualifiers as sugar, remove the ones which are not
14672 // common to both sides.
14673 bool KeepCommonQualifiers = Unqualified || isa<ArrayType>(SX.Ty);
14674
14675 if (SX.Ty != SY.Ty) {
14676 // The canonical nodes differ. Build a common canonical node out of the two,
14677 // unifying their sugar. This may recurse back here.
14678 SX.Ty =
14679 ::getCommonNonSugarTypeNode(*this, SX.Ty, QX, SY.Ty, QY).getTypePtr();
14680 } else {
14681 // The canonical nodes were identical: We may have desugared too much.
14682 // Add any common sugar back in.
14683 while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
14684 QX -= SX.Quals;
14685 QY -= SY.Quals;
14686 SX = Xs.pop_back_val();
14687 SY = Ys.pop_back_val();
14688 }
14689 }
14690 if (KeepCommonQualifiers)
14692 else
14693 assert(QX == QY);
14694
14695 // Even though the remaining sugar nodes in Xs and Ys differ, some may be
14696 // related. Walk up these nodes, unifying them and adding the result.
14697 while (!Xs.empty() && !Ys.empty()) {
14698 auto Underlying = SplitQualType(
14699 SX.Ty, Qualifiers::removeCommonQualifiers(SX.Quals, SY.Quals));
14700 SX = Xs.pop_back_val();
14701 SY = Ys.pop_back_val();
14702 SX.Ty = ::getCommonSugarTypeNode(*this, SX.Ty, SY.Ty, Underlying)
14704 // Stop at the first pair which is unrelated.
14705 if (!SX.Ty) {
14706 SX.Ty = Underlying.Ty;
14707 break;
14708 }
14709 QX -= Underlying.Quals;
14710 };
14711
14712 // Add back the missing accumulated qualifiers, which were stripped off
14713 // with the sugar nodes we could not unify.
14714 QualType R = getQualifiedType(SX.Ty, QX);
14715 assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
14716 return R;
14717}
14718
14720 assert(Ty->isFixedPointType());
14721
14723 return Ty;
14724
14725 switch (Ty->castAs<BuiltinType>()->getKind()) {
14726 default:
14727 llvm_unreachable("Not a saturated fixed point type!");
14728 case BuiltinType::SatShortAccum:
14729 return ShortAccumTy;
14730 case BuiltinType::SatAccum:
14731 return AccumTy;
14732 case BuiltinType::SatLongAccum:
14733 return LongAccumTy;
14734 case BuiltinType::SatUShortAccum:
14735 return UnsignedShortAccumTy;
14736 case BuiltinType::SatUAccum:
14737 return UnsignedAccumTy;
14738 case BuiltinType::SatULongAccum:
14739 return UnsignedLongAccumTy;
14740 case BuiltinType::SatShortFract:
14741 return ShortFractTy;
14742 case BuiltinType::SatFract:
14743 return FractTy;
14744 case BuiltinType::SatLongFract:
14745 return LongFractTy;
14746 case BuiltinType::SatUShortFract:
14747 return UnsignedShortFractTy;
14748 case BuiltinType::SatUFract:
14749 return UnsignedFractTy;
14750 case BuiltinType::SatULongFract:
14751 return UnsignedLongFractTy;
14752 }
14753}
14754
14756 assert(Ty->isFixedPointType());
14757
14758 if (Ty->isSaturatedFixedPointType()) return Ty;
14759
14760 switch (Ty->castAs<BuiltinType>()->getKind()) {
14761 default:
14762 llvm_unreachable("Not a fixed point type!");
14763 case BuiltinType::ShortAccum:
14764 return SatShortAccumTy;
14765 case BuiltinType::Accum:
14766 return SatAccumTy;
14767 case BuiltinType::LongAccum:
14768 return SatLongAccumTy;
14769 case BuiltinType::UShortAccum:
14771 case BuiltinType::UAccum:
14772 return SatUnsignedAccumTy;
14773 case BuiltinType::ULongAccum:
14775 case BuiltinType::ShortFract:
14776 return SatShortFractTy;
14777 case BuiltinType::Fract:
14778 return SatFractTy;
14779 case BuiltinType::LongFract:
14780 return SatLongFractTy;
14781 case BuiltinType::UShortFract:
14783 case BuiltinType::UFract:
14784 return SatUnsignedFractTy;
14785 case BuiltinType::ULongFract:
14787 }
14788}
14789
14791 if (LangOpts.OpenCL)
14793
14794 if (LangOpts.CUDA)
14796
14797 return getLangASFromTargetAS(AS);
14798}
14799
14800// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
14801// doesn't include ASTContext.h
14802template
14804 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
14806 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
14807 const clang::ASTContext &Ctx, Decl *Value);
14808
14810 assert(Ty->isFixedPointType());
14811
14812 const TargetInfo &Target = getTargetInfo();
14813 switch (Ty->castAs<BuiltinType>()->getKind()) {
14814 default:
14815 llvm_unreachable("Not a fixed point type!");
14816 case BuiltinType::ShortAccum:
14817 case BuiltinType::SatShortAccum:
14818 return Target.getShortAccumScale();
14819 case BuiltinType::Accum:
14820 case BuiltinType::SatAccum:
14821 return Target.getAccumScale();
14822 case BuiltinType::LongAccum:
14823 case BuiltinType::SatLongAccum:
14824 return Target.getLongAccumScale();
14825 case BuiltinType::UShortAccum:
14826 case BuiltinType::SatUShortAccum:
14827 return Target.getUnsignedShortAccumScale();
14828 case BuiltinType::UAccum:
14829 case BuiltinType::SatUAccum:
14830 return Target.getUnsignedAccumScale();
14831 case BuiltinType::ULongAccum:
14832 case BuiltinType::SatULongAccum:
14833 return Target.getUnsignedLongAccumScale();
14834 case BuiltinType::ShortFract:
14835 case BuiltinType::SatShortFract:
14836 return Target.getShortFractScale();
14837 case BuiltinType::Fract:
14838 case BuiltinType::SatFract:
14839 return Target.getFractScale();
14840 case BuiltinType::LongFract:
14841 case BuiltinType::SatLongFract:
14842 return Target.getLongFractScale();
14843 case BuiltinType::UShortFract:
14844 case BuiltinType::SatUShortFract:
14845 return Target.getUnsignedShortFractScale();
14846 case BuiltinType::UFract:
14847 case BuiltinType::SatUFract:
14848 return Target.getUnsignedFractScale();
14849 case BuiltinType::ULongFract:
14850 case BuiltinType::SatULongFract:
14851 return Target.getUnsignedLongFractScale();
14852 }
14853}
14854
14856 assert(Ty->isFixedPointType());
14857
14858 const TargetInfo &Target = getTargetInfo();
14859 switch (Ty->castAs<BuiltinType>()->getKind()) {
14860 default:
14861 llvm_unreachable("Not a fixed point type!");
14862 case BuiltinType::ShortAccum:
14863 case BuiltinType::SatShortAccum:
14864 return Target.getShortAccumIBits();
14865 case BuiltinType::Accum:
14866 case BuiltinType::SatAccum:
14867 return Target.getAccumIBits();
14868 case BuiltinType::LongAccum:
14869 case BuiltinType::SatLongAccum:
14870 return Target.getLongAccumIBits();
14871 case BuiltinType::UShortAccum:
14872 case BuiltinType::SatUShortAccum:
14873 return Target.getUnsignedShortAccumIBits();
14874 case BuiltinType::UAccum:
14875 case BuiltinType::SatUAccum:
14876 return Target.getUnsignedAccumIBits();
14877 case BuiltinType::ULongAccum:
14878 case BuiltinType::SatULongAccum:
14879 return Target.getUnsignedLongAccumIBits();
14880 case BuiltinType::ShortFract:
14881 case BuiltinType::SatShortFract:
14882 case BuiltinType::Fract:
14883 case BuiltinType::SatFract:
14884 case BuiltinType::LongFract:
14885 case BuiltinType::SatLongFract:
14886 case BuiltinType::UShortFract:
14887 case BuiltinType::SatUShortFract:
14888 case BuiltinType::UFract:
14889 case BuiltinType::SatUFract:
14890 case BuiltinType::ULongFract:
14891 case BuiltinType::SatULongFract:
14892 return 0;
14893 }
14894}
14895
14896llvm::FixedPointSemantics
14898 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
14899 "Can only get the fixed point semantics for a "
14900 "fixed point or integer type.");
14901 if (Ty->isIntegerType())
14902 return llvm::FixedPointSemantics::GetIntegerSemantics(
14903 getIntWidth(Ty), Ty->isSignedIntegerType());
14904
14905 bool isSigned = Ty->isSignedFixedPointType();
14906 return llvm::FixedPointSemantics(
14907 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
14909 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
14910}
14911
14912llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
14913 assert(Ty->isFixedPointType());
14914 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
14915}
14916
14917llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
14918 assert(Ty->isFixedPointType());
14919 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
14920}
14921
14923 assert(Ty->isUnsignedFixedPointType() &&
14924 "Expected unsigned fixed point type");
14925
14926 switch (Ty->castAs<BuiltinType>()->getKind()) {
14927 case BuiltinType::UShortAccum:
14928 return ShortAccumTy;
14929 case BuiltinType::UAccum:
14930 return AccumTy;
14931 case BuiltinType::ULongAccum:
14932 return LongAccumTy;
14933 case BuiltinType::SatUShortAccum:
14934 return SatShortAccumTy;
14935 case BuiltinType::SatUAccum:
14936 return SatAccumTy;
14937 case BuiltinType::SatULongAccum:
14938 return SatLongAccumTy;
14939 case BuiltinType::UShortFract:
14940 return ShortFractTy;
14941 case BuiltinType::UFract:
14942 return FractTy;
14943 case BuiltinType::ULongFract:
14944 return LongFractTy;
14945 case BuiltinType::SatUShortFract:
14946 return SatShortFractTy;
14947 case BuiltinType::SatUFract:
14948 return SatFractTy;
14949 case BuiltinType::SatULongFract:
14950 return SatLongFractTy;
14951 default:
14952 llvm_unreachable("Unexpected unsigned fixed point type");
14953 }
14954}
14955
14956// Given a list of FMV features, return a concatenated list of the
14957// corresponding backend features (which may contain duplicates).
14958static std::vector<std::string> getFMVBackendFeaturesFor(
14959 const llvm::SmallVectorImpl<StringRef> &FMVFeatStrings) {
14960 std::vector<std::string> BackendFeats;
14961 llvm::AArch64::ExtensionSet FeatureBits;
14962 for (StringRef F : FMVFeatStrings)
14963 if (auto FMVExt = llvm::AArch64::parseFMVExtension(F))
14964 if (FMVExt->ID)
14965 FeatureBits.enable(*FMVExt->ID);
14966 FeatureBits.toLLVMFeatureList(BackendFeats);
14967 return BackendFeats;
14968}
14969
14971ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
14972 assert(TD != nullptr);
14973 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TD->getFeaturesStr());
14974
14975 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) {
14976 return !Target->isValidFeatureName(StringRef{Feat}.substr(1));
14977 });
14978 return ParsedAttr;
14979}
14980
14981void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
14982 const FunctionDecl *FD) const {
14983 if (FD)
14984 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
14985 else
14986 Target->initFeatureMap(FeatureMap, getDiagnostics(),
14987 Target->getTargetOpts().CPU,
14988 Target->getTargetOpts().Features);
14989}
14990
14991// Fills in the supplied string map with the set of target features for the
14992// passed in function.
14993void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
14994 GlobalDecl GD) const {
14995 StringRef TargetCPU = Target->getTargetOpts().CPU;
14996 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
14997 if (const auto *TD = FD->getAttr<TargetAttr>()) {
14999
15000 // Make a copy of the features as passed on the command line into the
15001 // beginning of the additional features from the function to override.
15002 // AArch64 handles command line option features in parseTargetAttr().
15003 if (!Target->getTriple().isAArch64())
15004 ParsedAttr.Features.insert(
15005 ParsedAttr.Features.begin(),
15006 Target->getTargetOpts().FeaturesAsWritten.begin(),
15007 Target->getTargetOpts().FeaturesAsWritten.end());
15008
15009 if (ParsedAttr.CPU != "" && Target->isValidCPUName(ParsedAttr.CPU))
15010 TargetCPU = ParsedAttr.CPU;
15011
15012 // Now populate the feature map, first with the TargetCPU which is either
15013 // the default or a new one from the target attribute string. Then we'll use
15014 // the passed in features (FeaturesAsWritten) along with the new ones from
15015 // the attribute.
15016 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
15017 ParsedAttr.Features);
15018 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
15020 Target->getCPUSpecificCPUDispatchFeatures(
15021 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
15022 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
15023 Features.insert(Features.begin(),
15024 Target->getTargetOpts().FeaturesAsWritten.begin(),
15025 Target->getTargetOpts().FeaturesAsWritten.end());
15026 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15027 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
15028 if (Target->getTriple().isAArch64()) {
15030 TC->getFeatures(Feats, GD.getMultiVersionIndex());
15031 std::vector<std::string> Features = getFMVBackendFeaturesFor(Feats);
15032 Features.insert(Features.begin(),
15033 Target->getTargetOpts().FeaturesAsWritten.begin(),
15034 Target->getTargetOpts().FeaturesAsWritten.end());
15035 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15036 } else if (Target->getTriple().isRISCV()) {
15037 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15038 std::vector<std::string> Features;
15039 if (VersionStr != "default") {
15040 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(VersionStr);
15041 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
15042 ParsedAttr.Features.end());
15043 }
15044 Features.insert(Features.begin(),
15045 Target->getTargetOpts().FeaturesAsWritten.begin(),
15046 Target->getTargetOpts().FeaturesAsWritten.end());
15047 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15048 } else {
15049 std::vector<std::string> Features;
15050 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15051 if (VersionStr.starts_with("arch="))
15052 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
15053 else if (VersionStr != "default")
15054 Features.push_back((StringRef{"+"} + VersionStr).str());
15055 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15056 }
15057 } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
15058 std::vector<std::string> Features;
15059 if (Target->getTriple().isRISCV()) {
15060 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TV->getName());
15061 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
15062 ParsedAttr.Features.end());
15063 } else {
15064 assert(Target->getTriple().isAArch64());
15066 TV->getFeatures(Feats);
15067 Features = getFMVBackendFeaturesFor(Feats);
15068 }
15069 Features.insert(Features.begin(),
15070 Target->getTargetOpts().FeaturesAsWritten.begin(),
15071 Target->getTargetOpts().FeaturesAsWritten.end());
15072 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15073 } else {
15074 FeatureMap = Target->getTargetOpts().FeatureMap;
15075 }
15076}
15077
15079 CanQualType KernelNameType,
15080 const FunctionDecl *FD) {
15081 // Host and device compilation may use different ABIs and different ABIs
15082 // may allocate name mangling discriminators differently. A discriminator
15083 // override is used to ensure consistent discriminator allocation across
15084 // host and device compilation.
15085 auto DeviceDiscriminatorOverrider =
15086 [](ASTContext &Ctx, const NamedDecl *ND) -> UnsignedOrNone {
15087 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
15088 if (RD->isLambda())
15089 return RD->getDeviceLambdaManglingNumber();
15090 return std::nullopt;
15091 };
15092 std::unique_ptr<MangleContext> MC{ItaniumMangleContext::create(
15093 Context, Context.getDiagnostics(), DeviceDiscriminatorOverrider)};
15094
15095 // Construct a mangled name for the SYCL kernel caller offload entry point.
15096 // FIXME: The Itanium typeinfo mangling (_ZTS<type>) is currently used to
15097 // name the SYCL kernel caller offload entry point function. This mangling
15098 // does not suffice to clearly identify symbols that correspond to SYCL
15099 // kernel caller functions, nor is this mangling natural for targets that
15100 // use a non-Itanium ABI.
15101 std::string Buffer;
15102 Buffer.reserve(128);
15103 llvm::raw_string_ostream Out(Buffer);
15104 MC->mangleCanonicalTypeName(KernelNameType, Out);
15105 std::string KernelName = Out.str();
15106
15107 return {KernelNameType, FD, KernelName};
15108}
15109
15111 // If the function declaration to register is invalid or dependent, the
15112 // registration attempt is ignored.
15113 if (FD->isInvalidDecl() || FD->isTemplated())
15114 return;
15115
15116 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
15117 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
15118
15119 // Be tolerant of multiple registration attempts so long as each attempt
15120 // is for the same entity. Callers are obligated to detect and diagnose
15121 // conflicting kernel names prior to calling this function.
15122 CanQualType KernelNameType = getCanonicalType(SKEPAttr->getKernelName());
15123 auto IT = SYCLKernels.find(KernelNameType);
15124 assert((IT == SYCLKernels.end() ||
15125 declaresSameEntity(FD, IT->second.getKernelEntryPointDecl())) &&
15126 "SYCL kernel name conflict");
15127 (void)IT;
15128 SYCLKernels.insert(std::make_pair(
15129 KernelNameType, BuildSYCLKernelInfo(*this, KernelNameType, FD)));
15130}
15131
15133 CanQualType KernelNameType = getCanonicalType(T);
15134 return SYCLKernels.at(KernelNameType);
15135}
15136
15138 CanQualType KernelNameType = getCanonicalType(T);
15139 auto IT = SYCLKernels.find(KernelNameType);
15140 if (IT != SYCLKernels.end())
15141 return &IT->second;
15142 return nullptr;
15143}
15144
15146 OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
15147 return *OMPTraitInfoVector.back();
15148}
15149
15152 const ASTContext::SectionInfo &Section) {
15153 if (Section.Decl)
15154 return DB << Section.Decl;
15155 return DB << "a prior #pragma section";
15156}
15157
15159 bool IsInternalVar =
15160 isa<VarDecl>(D) &&
15161 basicGVALinkageForVariable(*this, cast<VarDecl>(D)) == GVA_Internal;
15162 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
15163 !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
15164 (D->hasAttr<CUDAConstantAttr>() &&
15165 !D->getAttr<CUDAConstantAttr>()->isImplicit());
15166 // CUDA/HIP: managed variables need to be externalized since it is
15167 // a declaration in IR, therefore cannot have internal linkage. Kernels in
15168 // anonymous name space needs to be externalized to avoid duplicate symbols.
15169 return (IsInternalVar &&
15170 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
15171 (D->hasAttr<CUDAGlobalAttr>() &&
15172 basicGVALinkageForFunction(*this, cast<FunctionDecl>(D)) ==
15173 GVA_Internal);
15174}
15175
15177 return mayExternalize(D) &&
15178 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
15179 CUDADeviceVarODRUsedByHost.count(cast<VarDecl>(D)));
15180}
15181
15182StringRef ASTContext::getCUIDHash() const {
15183 if (!CUIDHash.empty())
15184 return CUIDHash;
15185 if (LangOpts.CUID.empty())
15186 return StringRef();
15187 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
15188 return CUIDHash;
15189}
15190
15191const CXXRecordDecl *
15193 assert(ThisClass);
15194 assert(ThisClass->isPolymorphic());
15195 const CXXRecordDecl *PrimaryBase = ThisClass;
15196 while (1) {
15197 assert(PrimaryBase);
15198 assert(PrimaryBase->isPolymorphic());
15199 auto &Layout = getASTRecordLayout(PrimaryBase);
15200 auto Base = Layout.getPrimaryBase();
15201 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
15202 break;
15203 PrimaryBase = Base;
15204 }
15205 return PrimaryBase;
15206}
15207
15209 StringRef MangledName) {
15210 auto *Method = cast<CXXMethodDecl>(VirtualMethodDecl.getDecl());
15211 assert(Method->isVirtual());
15212 bool DefaultIncludesPointerAuth =
15213 LangOpts.PointerAuthCalls || LangOpts.PointerAuthIntrinsics;
15214
15215 if (!DefaultIncludesPointerAuth)
15216 return true;
15217
15218 auto Existing = ThunksToBeAbbreviated.find(VirtualMethodDecl);
15219 if (Existing != ThunksToBeAbbreviated.end())
15220 return Existing->second.contains(MangledName.str());
15221
15222 std::unique_ptr<MangleContext> Mangler(createMangleContext());
15223 llvm::StringMap<llvm::SmallVector<std::string, 2>> Thunks;
15224 auto VtableContext = getVTableContext();
15225 if (const auto *ThunkInfos = VtableContext->getThunkInfo(VirtualMethodDecl)) {
15226 auto *Destructor = dyn_cast<CXXDestructorDecl>(Method);
15227 for (const auto &Thunk : *ThunkInfos) {
15228 SmallString<256> ElidedName;
15229 llvm::raw_svector_ostream ElidedNameStream(ElidedName);
15230 if (Destructor)
15231 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15232 Thunk, /* elideOverrideInfo */ true,
15233 ElidedNameStream);
15234 else
15235 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ true,
15236 ElidedNameStream);
15237 SmallString<256> MangledName;
15238 llvm::raw_svector_ostream mangledNameStream(MangledName);
15239 if (Destructor)
15240 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15241 Thunk, /* elideOverrideInfo */ false,
15242 mangledNameStream);
15243 else
15244 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ false,
15245 mangledNameStream);
15246
15247 Thunks[ElidedName].push_back(std::string(MangledName));
15248 }
15249 }
15250 llvm::StringSet<> SimplifiedThunkNames;
15251 for (auto &ThunkList : Thunks) {
15252 llvm::sort(ThunkList.second);
15253 SimplifiedThunkNames.insert(ThunkList.second[0]);
15254 }
15255 bool Result = SimplifiedThunkNames.contains(MangledName);
15256 ThunksToBeAbbreviated[VirtualMethodDecl] = std::move(SimplifiedThunkNames);
15257 return Result;
15258}
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.
Definition: ASTContext.cpp:357
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)
Definition: ASTContext.cpp:923
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
Definition: ASTContext.cpp:106
@ FloatRank
Definition: ASTContext.cpp:110
@ LongDoubleRank
Definition: ASTContext.cpp:112
@ Float16Rank
Definition: ASTContext.cpp:108
@ Ibm128Rank
Definition: ASTContext.cpp:114
@ Float128Rank
Definition: ASTContext.cpp:113
@ BFloat16Rank
Definition: ASTContext.cpp:107
@ HalfRank
Definition: ASTContext.cpp:109
@ DoubleRank
Definition: ASTContext.cpp:111
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)
Definition: ASTContext.cpp:515
static SmallVector< SourceLocation, 2 > getDeclLocsForCommentSearch(const Decl *D, SourceManager &SourceMgr)
Definition: ASTContext.cpp:141
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)
Definition: ASTContext.h:3597
#define BuiltinTemplate(BTName)
Definition: ASTContext.h:2199
NodeId Parent
Definition: ASTDiff.cpp:191
StringRef P
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
const Decl * D
IndirectLocalPath & Path
Expr * E
Defines the clang::CommentOptions interface.
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1192
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.
unsigned Iter
Definition: HTMLLogger.cpp:153
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
static const Decl * getCanonicalDecl(const Decl *D)
#define X(type, name)
Definition: Value.h:145
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
llvm::MachO::Target Target
Definition: MachO.h:51
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)
Definition: OffloadArch.cpp:16
static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y)
static QualType getUnderlyingType(const SubRegion *R)
uint32_t Id
Definition: SemaARM.cpp:1179
SourceRange Range
Definition: SemaObjC.cpp:753
SourceLocation Loc
Definition: SemaObjC.cpp:754
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.
static const TemplateArgument & getArgument(const TemplateArgument &A)
C Language Family Type Representation.
SourceLocation Begin
__device__ __2f16 float c
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
bool isMemberPointerToDerivedMember() const
Definition: APValue.cpp: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
Definition: ASTContext.h:1235
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, const ObjCMethodDecl *MethodImp)
CanQualType ObjCBuiltinSelTy
Definition: ASTContext.h:1254
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1201
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:3056
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.
llvm::PointerUnion< VarTemplateDecl *, MemberSpecializationInfo * > TemplateOrSpecializationInfo
A type synonym for the TemplateOrInstantiation mapping.
Definition: ASTContext.h:516
LangAS getOpenCLTypeAddrSpace(const Type *T) const
Get address space for OpenCL type.
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
void InitBuiltinTypes(const TargetInfo &Target, const TargetInfo *AuxTarget=nullptr)
Initialize built-in types.
ParentMapContext & getParentMapContext()
Returns the dynamic AST node parent map context.
Definition: ASTContext.cpp:917
QualType getParenType(QualType NamedType) const
size_t getSideTableAllocatedMemory() const
Return the total memory used for various side tables.
MemberSpecializationInfo * getInstantiatedFromStaticDataMember(const VarDecl *Var)
If this variable is an instantiated static data member of a class template specialization,...
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
CanQualType ARCUnbridgedCastTy
Definition: ASTContext.h:1253
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:956
unsigned getManglingNumber(const NamedDecl *ND, bool ForAuxTarget=false) const
CanQualType LongTy
Definition: ASTContext.h:1231
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
Definition: ASTContext.h:1227
@ Weak
Weak definition of inline variable.
@ WeakUnknown
Weak for now, might become strong later in this TU.
void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl)
TypedefDecl * getObjCClassDecl() const
Retrieve the typedef declaration corresponding to the predefined Objective-C 'Class' type.
TypedefNameDecl * getTypedefNameForUnnamedTagDecl(const TagDecl *TD)
TypedefDecl * getCFConstantStringDecl() const
CanQualType Int128Ty
Definition: ASTContext.h:1231
CanQualType SatUnsignedFractTy
Definition: ASTContext.h:1244
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
Definition: ASTContext.h:1237
TypedefDecl * getObjCInstanceTypeDecl()
Retrieve the typedef declaration corresponding to the Objective-C "instancetype" type.
uint64_t getFieldOffset(const ValueDecl *FD) const
Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
QualType 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 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 getBuiltinVaListType() const
Retrieve the type of the __builtin_va_list type.
Definition: ASTContext.h:2394
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:744
comments::FullComment * cloneFullComment(comments::FullComment *FC, const Decl *D) const
Definition: ASTContext.cpp:594
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
Definition: ASTContext.h:1240
QualType getUnsignedPointerDiffType() const
Return the unique unsigned counterpart of "ptrdiff_t" integer type.
QualType getucontext_tType() const
Retrieve the C ucontext_t type.
Definition: ASTContext.h:2261
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 getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, const DependentTemplateStorage &Name, ArrayRef< TemplateArgumentLoc > Args) const
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
CanQualType ShortAccumTy
Definition: ASTContext.h:1235
ASTMutationListener * getASTMutationListener() const
Retrieve a pointer to the AST mutation listener associated with this AST context, if any.
Definition: ASTContext.h:1360
unsigned NumImplicitCopyAssignmentOperatorsDeclared
The number of implicitly-declared copy assignment operators for which declarations were built.
Definition: ASTContext.h:3547
uint64_t getTargetNullPointerValue(QualType QT) const
Get target-dependent integer value for null pointer which is used for constant folding.
unsigned getTypeUnadjustedAlign(QualType T) const
Return the ABI-specified natural alignment of a (complete) type T, before alignment adjustments,...
Definition: ASTContext.h:2664
unsigned char getFixedPointIBits(QualType Ty) const
QualType getSubstBuiltinTemplatePack(const TemplateArgument &ArgPack)
QualType getCorrespondingSignedFixedPointType(QualType Ty) const
CanQualType FloatTy
Definition: ASTContext.h:1234
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 ...
Definition: ASTContext.h:2851
unsigned NumImplicitDestructorsDeclared
The number of implicitly-declared destructors for which declarations were built.
Definition: ASTContext.h:3561
bool mergeExtParameterInfo(const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType, bool &CanUseFirst, bool &CanUseSecond, SmallVectorImpl< FunctionProtoType::ExtParameterInfo > &NewParamInfos)
This function merges the ExtParameterInfo lists of two functions.
bool ObjCQualifiedClassTypesAreCompatible(const ObjCObjectPointerType *LHS, const ObjCObjectPointerType *RHS)
ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and Class<pr1, ...>.
bool shouldExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel should be externalized.
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2867
bool propertyTypesAreCompatible(QualType, QualType)
void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, UsingShadowDecl *Pattern)
CanQualType DoubleTy
Definition: ASTContext.h:1234
QualType getDependentVectorType(QualType VectorType, Expr *SizeExpr, SourceLocation AttrLoc, VectorKind VecKind) const
Return the unique reference to the type for a dependently sized vector of the specified element type.
CanQualType SatLongAccumTy
Definition: ASTContext.h:1240
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.
QualType getCanonicalTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > CanonicalArgs) const
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...
QualType getFILEType() const
Retrieve the C FILE type.
Definition: ASTContext.h:2222
ArrayRef< Decl * > getModuleInitializers(Module *M)
Get the initializations to perform when importing a module, if any.
void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, std::string &S) const
Put the string version of the type qualifiers QT into S.
unsigned getPreferredTypeAlign(QualType T) const
Return the "preferred" alignment of the specified type T for the current target, in bits.
Definition: ASTContext.h:2716
std::string getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, bool Extended=false) const
Emit the encoded type for the method declaration Decl into S.
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
CanQualType LongDoubleTy
Definition: ASTContext.h:1234
CanQualType OMPArrayShapingTy
Definition: ASTContext.h:1263
ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents, SelectorTable &sels, Builtin::Context &builtins, TranslationUnitKind TUKind)
Definition: ASTContext.cpp:936
QualType getReadPipeType(QualType T) const
Return a read_only pipe type for the specified type.
std::string getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, const Decl *Container) const
getObjCEncodingForPropertyDecl - Return the encoded type for this method declaration.
CanQualType Char16Ty
Definition: ASTContext.h:1229
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)
Definition: ASTContext.cpp:348
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
Definition: ASTContext.h:1239
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
Definition: ASTContext.h:1249
QualType getReferenceQualifiedType(const Expr *e) const
getReferenceQualifiedType - Given an expr, will return the type for that expression,...
bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U) const
Determine whether two function types are the same, ignoring exception specifications in cases where t...
QualType getBlockDescriptorExtendedType() const
Gets the struct used to keep track of the extended descriptor for pointer to blocks.
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
Definition: ASTContext.h:1250
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
Definition: ASTContext.h:1249
QualType getUsingType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UsingShadowDecl *D, QualType UnderlyingType=QualType()) const
CanQualType WideCharTy
Definition: ASTContext.h:1226
CanQualType OMPIteratorTy
Definition: ASTContext.h:1263
IdentifierTable & Idents
Definition: ASTContext.h:740
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:742
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:894
QualType getFunctionTypeWithoutPtrSizes(QualType T)
Get a function type and produce the equivalent function type where pointer size address spaces in the...
llvm::iterator_range< overridden_cxx_method_iterator > overridden_method_range
Definition: ASTContext.h:1123
uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID, const ObjCIvarDecl *Ivar) const
Get the offset of an ObjCIvarDecl in bits.
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...
Definition: ASTContext.cpp:878
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:927
bool isSameDefaultTemplateArgument(const NamedDecl *X, const NamedDecl *Y) const
Determine whether two default template arguments are similar enough that they may be used in declarat...
QualType applyObjCProtocolQualifiers(QualType type, ArrayRef< ObjCProtocolDecl * > protocols, bool &hasError, bool allowOnPointerType=false) const
Apply Objective-C protocol qualifiers to the given type.
QualType getMacroQualifiedType(QualType UnderlyingTy, const IdentifierInfo *MacroII) const
QualType removePtrSizeAddrSpace(QualType T) const
Remove the existing address space on the type if it is a pointer size address space and return the ty...
bool areLaxCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible RISC-V vector types as defined by -flax-vect...
CanQualType SatShortFractTy
Definition: ASTContext.h:1243
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
Definition: ASTContext.cpp:863
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
Definition: ASTContext.h:1234
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
Definition: ASTContext.h:1241
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
Definition: ASTContext.h:1262
CanQualType ObjCBuiltinIdTy
Definition: ASTContext.h:1254
overridden_cxx_method_iterator overridden_methods_end(const CXXMethodDecl *Method) const
VTableContextBase * getVTableContext()
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const
ObjCPropertyImplDecl * getObjCPropertyImplDeclForPropertyDecl(const ObjCPropertyDecl *PD, const Decl *Container) const
bool isNearlyEmpty(const CXXRecordDecl *RD) const
PointerAuthQualifier getObjCMemberSelTypePtrAuth()
QualType AutoDeductTy
Definition: ASTContext.h:1285
CanQualType BoolTy
Definition: ASTContext.h:1223
void cacheRawCommentForDecl(const Decl &OriginalD, const RawComment &Comment) const
Attaches Comment to OriginalD and to its redeclaration chain and removes the redeclaration chain from...
Definition: ASTContext.cpp:506
void attachCommentsToJustParsedDecls(ArrayRef< Decl * > Decls, const Preprocessor *PP)
Searches existing comments for doc comments that should be attached to Decls.
Definition: ASTContext.cpp:532
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
QualType getObjCSelType() const
Retrieve the type that corresponds to the predefined Objective-C 'SEL' type.
Definition: ASTContext.h:2344
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
Definition: ASTContext.h:1239
QualType getjmp_bufType() const
Retrieve the C jmp_buf type.
Definition: ASTContext.h:2235
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
QualType mergeFunctionParameterTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false)
mergeFunctionParameterTypes - merge two types which appear as function parameter types
QualType getsigjmp_bufType() const
Retrieve the C sigjmp_buf type.
Definition: ASTContext.h:2248
void addOverriddenMethod(const CXXMethodDecl *Method, const CXXMethodDecl *Overridden)
Note that the given C++ Method overrides the given Overridden method.
TemplateTemplateParmDecl * findCanonicalTemplateTemplateParmDeclInternal(TemplateTemplateParmDecl *TTP) const
Definition: ASTContext.cpp:852
CanQualType Float128Ty
Definition: ASTContext.h:1234
CanQualType ObjCBuiltinClassTy
Definition: ASTContext.h:1254
unsigned NumImplicitDefaultConstructorsDeclared
The number of implicitly-declared default constructors for which declarations were built.
Definition: ASTContext.h:3526
CanQualType UnresolvedTemplateTy
Definition: ASTContext.h:1250
OMPTraitInfo & getNewOMPTraitInfo()
Return a new OMPTraitInfo object owned by this context.
CanQualType UnsignedLongTy
Definition: ASTContext.h:1232
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...
CanQualType UnsignedLongAccumTy
Definition: ASTContext.h:1237
QualType AutoRRefDeductTy
Definition: ASTContext.h:1286
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
CanQualType ShortFractTy
Definition: ASTContext.h:1238
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
Definition: ASTContext.h:1250
CanQualType SatUnsignedShortFractTy
Definition: ASTContext.h:1244
CanQualType CharTy
Definition: ASTContext.h:1224
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:930
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.
Definition: ASTContext.h:3540
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.
Definition: ASTContext.h:3533
CanQualType IntTy
Definition: ASTContext.h:1231
llvm::DenseSet< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
Definition: ASTContext.h:1302
CanQualType PseudoObjectTy
Definition: ASTContext.h:1253
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.
Definition: ASTContext.cpp:609
unsigned NumImplicitDestructors
The number of implicitly-declared destructors.
Definition: ASTContext.h:3557
CanQualType Float16Ty
Definition: ASTContext.h:1248
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2442
bool isAlignmentRequired(const Type *T) const
Determine if the alignment the type has was required using an alignment attribute.
TagDecl * MSGuidTagDecl
Definition: ASTContext.h:1293
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
Definition: ASTContext.h:1231
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
ASTMutationListener * Listener
Definition: ASTContext.h:746
CanQualType ObjCBuiltinBoolTy
Definition: ASTContext.h:1255
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
Definition: ASTContext.h:1250
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.
Definition: ASTContext.cpp:766
CanQualType OCLClkEventTy
Definition: ASTContext.h:1259
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:793
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
Definition: ASTContext.h:1241
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false, bool IsConditionalOperator=false)
const RawComment * getRawCommentForAnyRedecl(const Decl *D, const Decl **OriginalDecl=nullptr) const
Return the documentation comment attached to a given declaration.
Definition: ASTContext.cpp:424
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.
Definition: ASTContext.h:2605
GVALinkage GetGVALinkageForVariable(const VarDecl *VD) const
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.
Definition: ASTContext.h:2333
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.
Definition: ASTContext.h:2898
QualType getCorrespondingUnsaturatedType(QualType Ty) const
comments::FullComment * getCommentForDecl(const Decl *D, const Preprocessor *PP) const
Return parsed documentation comment attached to a given declaration.
Definition: ASTContext.cpp:614
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.
Definition: ASTContext.h:1315
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.
Definition: ASTContext.h:2625
CanQualType UnsignedInt128Ty
Definition: ASTContext.h:1233
CanQualType BuiltinFnTy
Definition: ASTContext.h:1252
ObjCInterfaceDecl * getObjCProtocolDecl() const
Retrieve the Objective-C class declaration corresponding to the predefined Protocol class.
unsigned NumImplicitDefaultConstructors
The number of implicitly-declared default constructors.
Definition: ASTContext.h:3522
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
unsigned NumImplicitMoveAssignmentOperatorsDeclared
The number of implicitly-declared move assignment operators for which declarations were built.
Definition: ASTContext.h:3554
void setManglingNumber(const NamedDecl *ND, unsigned Number)
llvm::DenseMap< const Decl *, const RawComment * > DeclRawComments
Mapping from declaration to directly attached comment.
Definition: ASTContext.h:936
CanQualType OCLSamplerTy
Definition: ASTContext.h:1259
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
Definition: ASTContext.h:1222
QualType getPackExpansionType(QualType Pattern, UnsignedOrNone NumExpansions, bool ExpectPackInType=true) const
Form a pack expansion type with the given pattern.
CanQualType UnsignedCharTy
Definition: ASTContext.h:1232
CanQualType UnsignedShortFractTy
Definition: ASTContext.h:1239
BuiltinTemplateDecl * buildBuiltinTemplateDecl(BuiltinTemplateKind BTK, const IdentifierInfo *II) const
void * Allocate(size_t Size, unsigned Align=8) const
Definition: ASTContext.h:814
bool canBuiltinBeRedeclared(const FunctionDecl *) const
Return whether a declaration to a builtin is allowed to be overloaded/redeclared.
CanQualType UnsignedIntTy
Definition: ASTContext.h:1232
unsigned NumImplicitMoveConstructors
The number of implicitly-declared move constructors.
Definition: ASTContext.h:3536
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
QualType getVolatileType(QualType T) const
Return the uniqued reference to the type for a volatile qualified type.
Definition: ASTContext.h:1450
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
Definition: ASTContext.h:1251
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
Definition: ASTContext.h:1233
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
CanQualType OCLReserveIDTy
Definition: ASTContext.h:1260
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
Definition: ASTContext.h:1232
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.
Definition: ASTContext.h:1750
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
Definition: ASTContext.h:1245
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.
Definition: ASTContext.cpp:315
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.
Definition: ASTContext.h:2418
const VariableArrayType * getAsVariableArrayType(QualType T) const
Definition: ASTContext.h:3059
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
Definition: ASTContext.h:1231
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
Definition: ASTContext.h:1238
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
Definition: ASTContext.h:1236
interp::Context & getInterpContext()
Returns the clang bytecode interpreter context.
Definition: ASTContext.cpp:910
CanQualType Char32Ty
Definition: ASTContext.h:1230
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
Definition: ASTContext.h:1243
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
Definition: ASTContext.h:1243
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:859
void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl)
CanQualType OCLQueueTy
Definition: ASTContext.h:1260
CanQualType LongFractTy
Definition: ASTContext.h:1238
CanQualType SatShortAccumTy
Definition: ASTContext.h:1240
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
CanQualType BFloat16Ty
Definition: ASTContext.h:1247
unsigned NumImplicitCopyConstructors
The number of implicitly-declared copy constructors.
Definition: ASTContext.h:3529
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType IncompleteMatrixIdxTy
Definition: ASTContext.h:1261
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.
Definition: ASTContext.cpp:884
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.
Definition: ASTContext.h:1339
uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const
Return number of constant array elements.
CanQualType SatUnsignedLongAccumTy
Definition: ASTContext.h:1242
QualType getUnconstrainedType(QualType T) const
Remove any type constraints from a template parameter type, for equivalence comparison of template pa...
CanQualType LongLongTy
Definition: ASTContext.h:1231
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:952
uint64_t getArrayInitLoopExprElementCount(const ArrayInitLoopExpr *AILE) const
Return number of elements initialized in an ArrayInitLoopExpr.
unsigned getTargetAddressSpace(LangAS AS) const
QualType getWideCharType() const
Return the type of wide characters.
Definition: ASTContext.h:2060
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()
Definition: ASTContext.h:1206
CanQualType WCharTy
Definition: ASTContext.h:1225
void getObjCEncodingForPropertyType(QualType T, std::string &S) const
Emit the Objective-C property type encoding for the given type T into S.
unsigned NumImplicitCopyAssignmentOperators
The number of implicitly-declared copy assignment operators.
Definition: ASTContext.h:3543
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:943
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>.
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.
Definition: ASTContext.h:2536
@ GE_Missing_stdio
Missing a type from <stdio.h>
Definition: ASTContext.h:2542
@ GE_Missing_type
Missing a type.
Definition: ASTContext.h:2539
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
Definition: ASTContext.h:2548
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
Definition: ASTContext.h:2545
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
Definition: ASTContext.h:1228
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
Definition: ASTContext.h:1246
CanQualType UnsignedAccumTy
Definition: ASTContext.h:1237
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
Definition: ASTContext.h:1259
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
Definition: ASTContext.h:1113
RawComment * getRawCommentForDeclNoCacheImpl(const Decl *D, const SourceLocation RepresentativeLocForDecl, const std::map< unsigned, RawComment * > &CommentsInFile) const
Definition: ASTContext.cpp:237
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
Definition: ASTContext.h:2656
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.
Definition: ASTContext.h:2629
QualType getBitIntType(bool Unsigned, unsigned NumBits) const
Return a bit-precise integer type with the specified signedness and bit count.
unsigned NumImplicitMoveAssignmentOperators
The number of implicitly-declared move assignment operators.
Definition: ASTContext.h:3550
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
virtual void AddedStaticLocalNumbers(const Decl *D, unsigned Number)
An static local number was added to a Decl.
virtual void RedefinedHiddenDefinition(const NamedDecl *D, Module *M)
A definition has been made visible by being redefined locally.
virtual void AddedManglingNumber(const Decl *D, unsigned Number)
An mangling number was added to a Decl.
virtual void DeducedReturnType(const FunctionDecl *FD, QualType ReturnType)
A function's return type has been deduced.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
CharUnits getAlignment() const
getAlignment - Get the record alignment in characters.
Definition: RecordLayout.h:183
const CXXRecordDecl * getBaseSharingVBPtr() const
Definition: RecordLayout.h:330
CharUnits getSize() const
getSize - Get the record size in characters.
Definition: RecordLayout.h:194
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:201
CharUnits getDataSize() const
getDataSize() - Get the record data size, which is the record size without tail padding,...
Definition: RecordLayout.h:207
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:250
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:260
CharUnits getNonVirtualSize() const
getNonVirtualSize - Get the non-virtual size (in chars) of an object, which is the size of the object...
Definition: RecordLayout.h:211
CharUnits getUnadjustedAlignment() const
getUnadjustedAlignment - Get the record alignment in characters, before alignment adjustment.
Definition: RecordLayout.h:191
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons.
Definition: TypeBase.h:3507
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TypeBase.h:3526
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:3908
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: TypeBase.h:3738
ArraySizeModifier getSizeModifier() const
Definition: TypeBase.h:3752
Qualifiers getIndexTypeQualifiers() const
Definition: TypeBase.h:3756
QualType getElementType() const
Definition: TypeBase.h:3750
unsigned getIndexTypeCVRQualifiers() const
Definition: TypeBase.h:3760
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
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: TypeBase.h:8142
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TypeBase.h:8147
Attr - This represents one attribute.
Definition: Attr.h:44
An attributed type is a type to which a type attribute has been applied.
Definition: TypeBase.h:6585
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TypeBase.h:6657
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: TypeBase.h:7180
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.cpp:5555
bool isConstrained() const
Definition: TypeBase.h:7199
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TypeBase.h:6694
A fixed int type of a specified bitwidth.
Definition: TypeBase.h:8195
void Profile(llvm::FoldingSetNodeID &ID) const
Definition: TypeBase.h:8212
unsigned getNumBits() const
Definition: TypeBase.h:8207
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4630
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6560
Pointer to a block type.
Definition: TypeBase.h:3558
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TypeBase.h:3575
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:3182
Kind getKind() const
Definition: TypeBase.h:3230
StringRef getName(const PrintingPolicy &Policy) const
Definition: Type.cpp:3398
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition: Builtins.h:228
bool isTSBuiltin(unsigned ID) const
Return true if this function is a target-specific builtin.
Definition: Builtins.h:264
bool hasCustomTypechecking(unsigned ID) const
Determines whether this builtin has custom typechecking.
Definition: Builtins.h:349
bool canBeRedeclared(unsigned ID) const
Returns true if this is a builtin that can be redeclared.
Definition: Builtins.cpp:323
const char * getTypeString(unsigned ID) const
Get the type descriptor string for the specified builtin.
Definition: Builtins.cpp:92
bool isNoReturn(unsigned ID) const
Return true if we know this builtin never returns.
Definition: Builtins.h:285
bool isNoThrow(unsigned ID) const
Return true if we know this builtin never throws an exception.
Definition: Builtins.h:280
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)
Builds a canonical type from a QualType.
QualType withConst() const
Retrieves a version of this type with const applied.
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
bool isNull() const
Definition: CanonicalType.h:98
Qualifiers getQualifiers() const
Retrieve all qualifiers.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:84
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:3293
QualType getElementType() const
Definition: TypeBase.h:3303
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TypeBase.h:3308
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:3776
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition: TypeBase.h:3872
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: TypeBase.h:3832
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: TypeBase.h:3891
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition: TypeBase.h:3852
Represents a concrete matrix type with constant number of rows and columns.
Definition: TypeBase.h:4389
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition: TypeBase.h:4410
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TypeBase.h:4427
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition: TypeBase.h:4407
static constexpr bool isDimensionValid(size_t NumElements)
Returns true if NumElements is a valid matrix dimension.
Definition: TypeBase.h:4418
Represents a sugar type with __counted_by or __sized_by annotations, including their _or_null variant...
Definition: TypeBase.h:3454
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TypeBase.h:3490
Represents a pointer type decayed from an array or function type.
Definition: TypeBase.h:3541
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.
Definition: DeclBase.cpp:1358
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.
Definition: DeclBase.cpp:1879
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:2022
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1793
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.
Definition: DeclBase.cpp:1130
T * getAttr() const
Definition: DeclBase.h:573
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:524
void addAttr(Attr *A)
Definition: DeclBase.cpp:1022
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 *)
Definition: DeclBase.cpp:1050
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
@ OBJC_TQ_Byref
Definition: DeclBase.h:204
@ OBJC_TQ_Oneway
Definition: DeclBase.h:205
@ OBJC_TQ_Bycopy
Definition: DeclBase.h:203
@ OBJC_TQ_None
Definition: DeclBase.h:199
@ OBJC_TQ_Inout
Definition: DeclBase.h:201
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
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition: DeclBase.cpp:234
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.
DeclarationName getIdentifier(const IdentifierInfo *ID)
Create a declaration name that is a simple identifier.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
The name of a declaration.
static int compare(DeclarationName LHS, DeclarationName RHS)
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:779
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:808
Represents the type decltype(expr) (C++11).
Definition: TypeBase.h:6270
Represents a C++17 deduced template specialization type.
Definition: TypeBase.h:7228
void Profile(llvm::FoldingSetNodeID &ID) const
Definition: TypeBase.h:7250
TemplateName getUnderlying() const
Definition: TemplateName.h:471
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) const
DefaultArguments getDefaultArguments() const
Definition: TemplateName.h:473
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: TypeBase.h:7146
Represents an extended address space qualifier where the input address space value is dependent.
Definition: TypeBase.h:4077
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: TypeBase.h:4099
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: TypeBase.h:8240
Internal representation of canonical, dependent decltype(expr) types.
Definition: TypeBase.h:6298
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: TypeBase.h:6302
Represents a qualified type name for which the type name is dependent.
Definition: TypeBase.h:7414
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TypeBase.h:7446
Represents an array type in C++ whose size is a value-dependent expression.
Definition: TypeBase.h:4027
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: TypeBase.h:4056
Represents an extended vector type where either the type or size is dependent.
Definition: TypeBase.h:4117
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: TypeBase.h:4142
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition: TypeBase.h:4448
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: TypeBase.h:4468
Represents a template specialization type whose template cannot be resolved, e.g.
Definition: TypeBase.h:7465
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: TypeBase.h:7488
Represents a dependent template name that cannot be resolved prior to template instantiation.
Definition: TemplateName.h:590
IdentifierOrOverloadedOperator getName() const
Definition: TemplateName.h:609
NestedNameSpecifier getQualifier() const
Return the nested name specifier that qualifies this name.
Definition: TemplateName.h:607
bool hasTemplateKeyword() const
Was this template name was preceeded by the template keyword?
Definition: TemplateName.h:612
Internal representation of canonical, dependent typeof(expr) types.
Definition: TypeBase.h:6227
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: TypeBase.h:6232
Represents a vector type where either the type or size is dependent.
Definition: TypeBase.h:4243
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: TypeBase.h:4268
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.
Definition: Diagnostic.h:1529
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
Wrap a function effect's condition expression in another struct so that FunctionProtoType's TrailingO...
Definition: TypeBase.h:5002
Represents an enum.
Definition: Decl.h:4000
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4209
bool isComplete() const
Returns true if this can be considered a complete type.
Definition: Decl.h:4223
EnumDecl * getDefinitionOrSelf() const
Definition: Decl.h:4107
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4164
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:5029
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: TypeBase.h:6522
EnumDecl * getOriginalDecl() const
Definition: TypeBase.h:6529
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:4283
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:5412
Abstract interface for external sources of AST nodes.
virtual ExtKind hasExternalDefinitions(const Decl *D)
virtual void ReadComments()
Loads comment ranges.
virtual void CompleteRedeclChain(const Decl *D)
Gives the external AST source an opportunity to complete the redeclaration chain for a declaration.
virtual void PrintStats()
Print any statistics that have been gathered regarding the external AST source.
Represents a member of a struct/union/class.
Definition: Decl.h:3153
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3256
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition: Decl.cpp:4689
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.h:3238
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3389
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:4637
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:2682
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3699
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2914
bool isMSExternInline() const
The combination of the extern and inline keywords under MSVC forces the function to be required.
Definition: Decl.cpp:3828
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3684
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:4354
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:4102
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:4015
static FunctionEffectSet getIntersection(FunctionEffectsRef LHS, FunctionEffectsRef RHS)
Definition: Type.cpp:5686
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition: Type.cpp:5724
Represents an abstract function effect, using just an enumeration describing its kind.
Definition: TypeBase.h:4895
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition: TypeBase.h:5082
size_t size() const
Definition: TypeBase.h:5113
ArrayRef< EffectConditionExpr > conditions() const
Definition: TypeBase.h:5116
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition: TypeBase.h:4860
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TypeBase.h:4876
Represents a prototype with parameter type info, e.g.
Definition: TypeBase.h:5282
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: TypeBase.h:5786
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: TypeBase.h:5589
unsigned getNumParams() const
Definition: TypeBase.h:5560
QualType getParamType(unsigned i) const
Definition: TypeBase.h:5562
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.cpp:3991
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: TypeBase.h:5595
bool isVariadic() const
Whether this function prototype is variadic.
Definition: TypeBase.h:5686
ExtProtoInfo getExtProtoInfo() const
Definition: TypeBase.h:5571
ArrayRef< QualType > getParamTypes() const
Definition: TypeBase.h:5567
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
Definition: TypeBase.h:5755
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition: TypeBase.h:5751
Declaration of a template function.
Definition: DeclTemplate.h:952
A class which abstracts out some details necessary for making a call.
Definition: TypeBase.h:4589
CallingConv getCC() const
Definition: TypeBase.h:4648
unsigned getRegParm() const
Definition: TypeBase.h:4641
bool getNoCallerSavedRegs() const
Definition: TypeBase.h:4637
ExtInfo withNoReturn(bool noReturn) const
Definition: TypeBase.h:4660
bool getProducesResult() const
Definition: TypeBase.h:4635
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition: TypeBase.h:4504
ExtParameterInfo withIsNoEscape(bool NoEscape) const
Definition: TypeBase.h:4544
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: TypeBase.h:4478
ExtInfo getExtInfo() const
Definition: TypeBase.h:4834
QualType getReturnType() const
Definition: TypeBase.h:4818
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
QualType getWrappedType() const
Definition: TypeBase.h:6751
const Attributes & getAttrs() const
Definition: TypeBase.h:6754
QualType getContainedType() const
Definition: TypeBase.h:6752
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TypeBase.h:6759
Represents an arbitrary, user-specified SPIR-V type instruction.
Definition: TypeBase.h:6860
uint32_t getAlignment() const
Definition: TypeBase.h:6885
uint32_t getSize() const
Definition: TypeBase.h:6884
uint32_t getOpcode() const
Definition: TypeBase.h:6883
ArrayRef< SpirvOperand > getOperands() const
Definition: TypeBase.h:6886
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TypeBase.h:6893
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.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
Describes a module import declaration, which makes the contents of the named module visible in the cu...
Definition: Decl.h:5011
Represents a C array with an unspecified size.
Definition: TypeBase.h:3925
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TypeBase.h:3942
The injected class name of a C++ class template or class template partial specialization.
Definition: TypeBase.h:6553
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:3633
@ Swift
Interoperability with the latest known version of the Swift runtime.
@ Swift4_2
Interoperability with the Swift 4.2 runtime.
@ Swift4_1
Interoperability with the Swift 4.1 runtime.
@ Integer
Permit vector bitcasts between integer vectors with different numbers of elements but the same total ...
@ All
Permit vector bitcasts between all vectors with the same total bit-width.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:434
std::optional< TargetCXXABI::Kind > CXXABI
C++ ABI to compile with, if specified by the frontend through -fc++-abi=.
Definition: LangOptions.h:522
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:469
CoreFoundationABI CFRuntime
Definition: LangOptions.h:471
CommentOptions CommentOpts
Options for parsing comments.
Definition: LangOptions.h:498
std::string CUID
The user provided compilation unit ID, if non-empty.
Definition: LangOptions.h:518
A global _GUID constant.
Definition: DeclCXX.h:4392
static void Profile(llvm::FoldingSetNodeID &ID, Parts P)
Definition: DeclCXX.h:4429
Sugar type that represents a type that was qualified by a qualifier written as a macro invocation.
Definition: TypeBase.h:6161
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:4367
static bool isValidElementType(QualType T)
Valid elements types are the following:
Definition: TypeBase.h:4374
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: TypeBase.h:3669
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TypeBase.h:3712
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:614
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.
@ Type
A type, stored as a Type*.
@ 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)
Definition: DeclObjC.cpp:1539
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,...
Definition: DeclObjC.cpp:1785
StringRef getObjCRuntimeNameAsString() const
Produce a name to be used for class's metadata.
Definition: DeclObjC.cpp:1610
ObjCImplementationDecl * getImplementation() const
Definition: DeclObjC.cpp:1626
ObjCInterfaceDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this Objective-C class.
Definition: DeclObjC.h:1915
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
Interfaces are the core concept in Objective-C for object oriented design.
Definition: TypeBase.h:7905
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:7961
bool isObjCQualifiedClassType() const
True if this is equivalent to 'Class.
Definition: TypeBase.h:8042
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:8036
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TypeBase.h:8118
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition: TypeBase.h:7998
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition: TypeBase.h:8019
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: TypeBase.h:7973
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition: TypeBase.h:8013
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:8080
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition: TypeBase.h:8025
A class providing a concrete implementation of ObjCObjectType, so as to not increase the footprint of...
Definition: TypeBase.h:7858
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.cpp:4740
Represents a class type in Objective C.
Definition: TypeBase.h:7707
bool isKindOfTypeAsWritten() const
Whether this is a "__kindof" type as written.
Definition: TypeBase.h:7822
bool isSpecialized() const
Determine whether this object type is "specialized", meaning that it has type arguments.
Definition: Type.cpp:880
ArrayRef< QualType > getTypeArgsAsWritten() const
Retrieve the type arguments of this object type as they were written.
Definition: TypeBase.h:7817
bool isObjCQualifiedClass() const
Definition: TypeBase.h:7789
QualType getBaseType() const
Gets the base type of this object type.
Definition: TypeBase.h:7769
bool isObjCClass() const
Definition: TypeBase.h:7775
bool isKindOfType() const
Whether this ia a "__kindof" type (semantically).
Definition: Type.cpp:916
bool isObjCQualifiedId() const
Definition: TypeBase.h:7788
ArrayRef< QualType > getTypeArgs() const
Retrieve the type arguments of this object type (semantically).
Definition: Type.cpp:898
bool isObjCUnqualifiedId() const
Definition: TypeBase.h:7779
ObjCInterfaceDecl * getInterface() const
Gets the interface declaration for this object type, if the base type really is an interface.
Definition: TypeBase.h:7940
QualType getSuperClassType() const
Retrieve the type of the superclass of this object type.
Definition: TypeBase.h:7833
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
unsigned getNumProtocols() const
Return the number of qualifying protocols in this type, or 0 if there are none.
Definition: TypeBase.h:7613
qual_iterator qual_end() const
Definition: TypeBase.h:7607
qual_iterator qual_begin() const
Definition: TypeBase.h:7606
qual_range quals() const
Definition: TypeBase.h:7605
bool isGNUFamily() const
Is this runtime basically of the GNU family of runtimes?
Definition: ObjCRuntime.h:127
Represents the declaration of an Objective-C type parameter.
Definition: DeclObjC.h:578
ObjCTypeParamVariance getVariance() const
Determine the variance of this type parameter.
Definition: DeclObjC.h:623
Stores a list of Objective-C type parameters for a parameterized class or a category/extension thereo...
Definition: DeclObjC.h:662
Represents a type parameter type in Objective C.
Definition: TypeBase.h:7633
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.cpp:4757
A structure for storing the information associated with an overloaded template name.
Definition: TemplateName.h:118
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition: ExprCXX.h:4357
Represents a pack expansion of types.
Definition: TypeBase.h:7524
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TypeBase.h:7558
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.cpp:4250
Sugar for parentheses used when specifying types.
Definition: TypeBase.h:3320
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TypeBase.h:3334
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
PipeType - OpenCL20.
Definition: TypeBase.h:8161
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TypeBase.h:8178
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:3346
QualType getPointeeType() const
Definition: TypeBase.h:3356
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TypeBase.h:3361
PredefinedSugarKind Kind
Definition: TypeBase.h:8254
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:145
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:8427
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2871
Qualifiers::GC getObjCGCAttr() const
Returns gc attribute of this type.
Definition: TypeBase.h:8474
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: TypeBase.h:8432
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:8343
LangAS getAddressSpace() const
Return the address space of this type.
Definition: TypeBase.h:8469
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: TypeBase.h:8383
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: TypeBase.h:1438
QualType getCanonicalType() const
Definition: TypeBase.h:8395
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: TypeBase.h:8437
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition: TypeBase.h:8364
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: TypeBase.h:8416
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:8400
const Type * getTypePtrOrNull() const
Definition: TypeBase.h:8347
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:2994
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: TypeBase.h:8375
Represents a template name as written in source code.
Definition: TemplateName.h:504
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TemplateName.h:541
A qualifier set is used to build a set of qualifiers.
Definition: TypeBase.h:8283
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: TypeBase.h:8290
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
void setAddressSpace(LangAS space)
Definition: TypeBase.h:591
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:3651
unsigned getCommentBeginLine(RawComment *C, FileID File, unsigned Offset) const
const std::map< unsigned, RawComment * > * getCommentsInFile(FileID File) const
unsigned getCommentEndOffset(RawComment *C) const
void addComment(const RawComment &RC, const CommentOptions &CommentOpts, llvm::BumpPtrAllocator &Allocator)
bool isTrailingComment() const LLVM_READONLY
Returns true if it is a comment that should be put after a member:
SourceRange getSourceRange() const LLVM_READONLY
bool isDocumentation() const LLVM_READONLY
Returns true if this comment any kind of a documentation comment.
comments::FullComment * parse(const ASTContext &Context, const Preprocessor *PP, const Decl *D) const
Parse the comment, assuming it is attached to decl D.
Represents a struct/union/class.
Definition: Decl.h:4305
bool isLambda() const
Determine whether this record is a class describing a lambda function object.
Definition: Decl.cpp:5121
bool hasFlexibleArrayMember() const
Definition: Decl.h:4338
field_range fields() const
Definition: Decl.h:4508
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition: Decl.cpp:5107
RecordDecl * getMostRecentDecl()
Definition: Decl.h:4331
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition: Decl.cpp:5162
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4489
bool field_empty() const
Definition: Decl.h:4516
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: TypeBase.h:6502
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:213
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:201
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:223
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:293
Base for LValueReferenceType and RValueReferenceType.
Definition: TypeBase.h:3589
QualType getPointeeType() const
Definition: TypeBase.h:3607
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TypeBase.h:3615
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.
FileIDAndOffset getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
DiagnosticsEngine & getDiagnostics() const
StringRef getBufferData(FileID FID, bool *Invalid=nullptr) const
Return a StringRef to the source buffer data for the specified FileID.
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
unsigned getLineNumber(FileID FID, unsigned FilePos, bool *Invalid=nullptr) const
Given a SourceLocation, return the spelling line number for the position indicated.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical, bool ProfileLambdaExpr=false) const
Produce a unique representation of the given statement.
The streaming interface shared between DiagnosticBuilder and PartialDiagnostic.
Definition: Diagnostic.h:1115
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h: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
Represents the result of substituting a builtin template as a pack.
Definition: TypeBase.h:7062
void Profile(llvm::FoldingSetNodeID &ID)
Mark that we reuse the Profile. We do not introduce new fields.
Definition: Type.cpp:4536
A structure for storing an already-substituted template template parameter pack.
Definition: TemplateName.h:151
Decl * getAssociatedDecl() const
A template-like entity which owns the whole pattern being substituted.
void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context)
TemplateTemplateParmDecl * getParameterPack() const
Retrieve the template template parameter pack being substituted.
TemplateArgument getArgumentPack() const
Retrieve the template template argument pack with which this parameter was substituted.
unsigned getIndex() const
Returns the index of the replaced parameter in the associated declaration.
Definition: TemplateName.h:166
A structure for storing the information associated with a substituted template template parameter.
Definition: TemplateName.h:418
void Profile(llvm::FoldingSetNodeID &ID)
TemplateTemplateParmDecl * getParameter() const
Represents the result of substituting a set of types for a template type parameter pack.
Definition: TypeBase.h:7091
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.cpp:4577
Represents the result of substituting a type for a template type parameter.
Definition: TypeBase.h:6972
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TypeBase.h:7015
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3710
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition: Decl.h:3941
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4843
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:4836
bool isUnion() const
Definition: Decl.h:3915
TagKind getTagKind() const
Definition: Decl.h:3904
TagDecl * getDefinitionOrSelf() const
Definition: Decl.h:3887
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
bool canKeyFunctionBeInline() const
Can an out-of-line inline function serve as a key function?
Definition: TargetCXXABI.h:238
Kind
The basic C++ ABI kind.
Definition: TargetCXXABI.h:31
static Kind getKind(StringRef Name)
Definition: TargetCXXABI.h:59
Exposes information about the current target.
Definition: TargetInfo.h: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.
Definition: TargetInfo.h:1288
IntType getInt64Type() const
Definition: TargetInfo.h:419
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.
Definition: TargetInfo.h:1679
virtual LangAS getOpenCLBuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space.
Definition: TargetInfo.h:1673
unsigned getDefaultAlignForAttributeAligned() const
Return the default alignment for attribute((aligned)) on this target, to be used if no alignment valu...
Definition: TargetInfo.h:746
unsigned getBFloat16Width() const
getBFloat16Width/Align/Format - Return the size/align/format of '__bf16'.
Definition: TargetInfo.h:791
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 std::optional< std::pair< unsigned, unsigned > > getVScaleRange(const LangOptions &LangOpts, ArmStreamingKind Mode, llvm::StringMap< bool > *FeatureMap=nullptr) const
Returns target-specific min and max values VScale_Range.
Definition: TargetInfo.h:1045
virtual uint64_t getNullPointerValue(LangAS AddrSpace) const
Get integer value for null pointer.
Definition: TargetInfo.h:502
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:486
static bool isTypeSigned(IntType T)
Returns true if the type is signed; false otherwise.
Definition: TargetInfo.cpp:393
unsigned getHalfAlign() const
Definition: TargetInfo.h:782
unsigned getBFloat16Align() const
Definition: TargetInfo.h:792
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.
Definition: TargetInfo.cpp:339
virtual IntType getIntTypeByWidth(unsigned BitWidth, bool IsSigned) const
Return integer type with specified width.
Definition: TargetInfo.cpp:309
unsigned getHalfWidth() const
getHalfWidth/Align/Format - Return the size/align/format of 'half'.
Definition: TargetInfo.h:781
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
Definition: TargetInfo.h:1660
unsigned getFloat128Width() const
getFloat128Width/Align/Format - Return the size/align/format of '__float128'.
Definition: TargetInfo.h:810
IntType getSignedSizeType() const
Definition: TargetInfo.h:386
const llvm::fltSemantics & getLongDoubleFormat() const
Definition: TargetInfo.h:804
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1360
bool hasAArch64ACLETypes() const
Returns whether or not the AArch64 ACLE built-in types are available on this target.
Definition: TargetInfo.h:1066
bool useAddressSpaceMapMangling() const
Specify if mangling based on address space map should be used or not for language specific address sp...
Definition: TargetInfo.h:1021
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
Definition: TargetInfo.h:532
unsigned getFloat128Align() const
Definition: TargetInfo.h:811
virtual bool hasBFloat16Type() const
Determine whether the _BFloat16 type is supported on this target.
Definition: TargetInfo.h:718
const llvm::fltSemantics & getFloat128Format() const
Definition: TargetInfo.h:812
unsigned getLongDoubleWidth() const
getLongDoubleWidth/Align/Format - Return the size/align/format of 'long double'.
Definition: TargetInfo.h:802
unsigned getLongDoubleAlign() const
Definition: TargetInfo.h:803
llvm::StringMap< bool > FeatureMap
The map of which features have been enabled disabled based on the command line.
Definition: TargetOptions.h:62
A convenient class for passing around template argument information.
Definition: TemplateBase.h:634
ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:661
A template argument list.
Definition: DeclTemplate.h:250
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:280
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:528
Represents a template argument.
Definition: TemplateBase.h:61
ArrayRef< TemplateArgument > getPackAsArray() const
Return the array of arguments in this template argument pack.
Definition: TemplateBase.h:452
QualType getStructuralValueType() const
Get the type of a StructuralValue.
Definition: TemplateBase.h:402
QualType getParamTypeForDecl() const
Definition: TemplateBase.h:334
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:411
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.
Definition: TemplateBase.h:322
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
Definition: TemplateBase.h:366
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
Definition: TemplateBase.h:340
static TemplateArgument CreatePackCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument pack by copying the given set of template arguments.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
Definition: TemplateBase.h:346
bool structurallyEquals(const TemplateArgument &Other) const
Determines whether two template arguments are superficially the same.
QualType getIntegralType() const
Retrieve the type of the integral value.
Definition: TemplateBase.h:380
bool getIsDefaulted() const
If returns 'true', this TemplateArgument corresponds to a default template parameter.
Definition: TemplateBase.h:396
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:329
ArrayRef< TemplateArgument > pack_elements() const
Iterator range referencing all of the elements of a template argument pack.
Definition: TemplateBase.h:440
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:74
@ Template
The template argument is a template name that was provided for a template template parameter.
Definition: TemplateBase.h:93
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
Definition: TemplateBase.h:89
@ Pack
The template argument is actually a parameter pack.
Definition: TemplateBase.h:107
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
Definition: TemplateBase.h:97
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:78
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
Definition: TemplateBase.h:67
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
Definition: TemplateBase.h:82
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
Definition: TemplateBase.h:103
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:296
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion,...
Definition: TemplateBase.h:353
const APValue & getAsStructuralValue() const
Get the value of a StructuralValue.
Definition: TemplateBase.h:399
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:396
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:415
Represents a C++ template name within the type system.
Definition: TemplateName.h:222
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
void * getAsVoidPointer() const
Retrieve the template name as a void pointer.
Definition: TemplateName.h:398
@ UsingTemplate
A template name that refers to a template declaration found through a specific using shadow declarati...
Definition: TemplateName.h:267
@ OverloadedTemplate
A set of overloaded template declarations.
Definition: TemplateName.h:242
@ Template
A single template declaration.
Definition: TemplateName.h:239
@ DependentTemplate
A dependent template name that has not been resolved to a template (or set of templates).
Definition: TemplateName.h:254
@ SubstTemplateTemplateParm
A template template parameter that has been substituted for some other template name.
Definition: TemplateName.h:258
@ SubstTemplateTemplateParmPack
A template template parameter pack that has been substituted for a template template argument pack,...
Definition: TemplateName.h:263
@ DeducedTemplate
A template name that refers to another TemplateName with deduced default arguments.
Definition: TemplateName.h:271
@ QualifiedTemplate
A qualified template name, where the qualification is kept to describe the source code as written.
Definition: TemplateName.h:250
@ AssumedTemplate
An unqualified-id that has been assumed to name a function template that will be found by ADL.
Definition: TemplateName.h:246
A template parameter object.
static void Profile(llvm::FoldingSetNodeID &ID, QualType T, const APValue &V)
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:74
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:146
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
NamedDecl *const * const_iterator
Iterates through the template parameters in this list.
Definition: DeclTemplate.h:133
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
Definition: DeclTemplate.h:182
ArrayRef< NamedDecl * > asArray()
Definition: DeclTemplate.h:143
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: TypeBase.h:7290
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.cpp:4691
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)
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TypeBase.h:6944
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:3506
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:6193
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition: TypeBase.h:6243
A container of type source information.
Definition: TypeBase.h:8314
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:8600
bool isVoidType() const
Definition: TypeBase.h:8936
bool isBooleanType() const
Definition: TypeBase.h:9066
bool isFunctionReferenceType() const
Definition: TypeBase.h:8654
bool isObjCBuiltinType() const
Definition: TypeBase.h:8800
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2229
QualType getRVVEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an RVV builtin type.
Definition: Type.cpp:2682
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:787
bool isIncompleteArrayType() const
Definition: TypeBase.h:8687
bool isPlaceholderType() const
Test for a type which does not represent an actual type-system type but is instead used as a placehol...
Definition: TypeBase.h:8912
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2209
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:8683
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.h:41
bool hasIntegerRepresentation() const
Determine whether this type has an integer representation of some sort, e.g., it is an integer type o...
Definition: Type.cpp:2070
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition: Type.cpp:2430
bool isArrayType() const
Definition: TypeBase.h:8679
bool isCharType() const
Definition: Type.cpp:2136
QualType getLocallyUnqualifiedSingleStepDesugaredType() const
Pull a single level of sugar off of this locally-unqualified type.
Definition: Type.cpp:521
bool isFunctionPointerType() const
Definition: TypeBase.h:8647
bool isPointerType() const
Definition: TypeBase.h:8580
bool isArrayParameterType() const
Definition: TypeBase.h:8695
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: TypeBase.h:8980
const T * castAs() const
Member-template castAs<specific type>.
Definition: TypeBase.h:9226
bool isSpecificPlaceholderType(unsigned K) const
Test for a specific placeholder type.
Definition: TypeBase.h:8925
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:9020
bool isEnumeralType() const
Definition: TypeBase.h:8711
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2107
bool isObjCQualifiedIdType() const
Definition: TypeBase.h:8770
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:9054
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e....
Definition: Type.cpp:2295
TagDecl * getAsTagDecl() const
Retrieves the TagDecl that this type refers to, either because the type is a TagType or because it is...
Definition: Type.h:65
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: TypeBase.h:2917
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: TypeBase.h:2808
bool isBitIntType() const
Definition: TypeBase.h:8845
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: TypeBase.h:8905
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: TypeBase.h:8703
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: TypeBase.h:2800
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: TypeBase.h:8992
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: TypeBase.h:9008
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: TypeBase.h:2423
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition: Type.cpp:2247
QualType getCanonicalTypeInternal() const
Definition: TypeBase.h:3137
@ PtrdiffT
The "ptrdiff_t" type.
@ SignedSizeT
The signed integer type corresponding to "size_t".
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: TypeBase.h:9109
bool isMemberPointerType() const
Definition: TypeBase.h:8661
bool isObjCIdType() const
Definition: TypeBase.h:8782
EnumDecl * castAsEnumDecl() const
Definition: Type.h:59
bool isUnsaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: TypeBase.h:9016
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: TypeBase.h:9212
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:2440
bool isFunctionType() const
Definition: TypeBase.h:8576
bool isObjCObjectPointerType() const
Definition: TypeBase.h:8749
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:9034
bool isVectorType() const
Definition: TypeBase.h:8719
bool isObjCClassType() const
Definition: TypeBase.h:8788
bool isRVVVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'riscv_rvv_vector_bits' type attribute,...
Definition: Type.cpp:2664
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2599
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition: TypeBase.h:2939
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:2257
const T * castAsCanonical() const
Return this type's canonical type cast to the specified type.
Definition: TypeBase.h:2946
bool isAnyPointerType() const
Definition: TypeBase.h:8588
TypeClass getTypeClass() const
Definition: TypeBase.h:2403
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition: TypeBase.h:2429
const T * getAs() const
Member-template getAs<specific type>'.
Definition: TypeBase.h:9159
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:8973
bool isRecordType() const
Definition: TypeBase.h:8707
bool isObjCRetainableType() const
Definition: Type.cpp:5336
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:5066
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition: Decl.h:3660
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5625
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3555
QualType getUnderlyingType() const
Definition: Decl.h:3610
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType Underlying)
Definition: TypeBase.h:6137
A unary type transform, which is a type constructed from another.
Definition: TypeBase.h:6375
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TypeBase.h:6410
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.
Definition: UnresolvedSet.h:35
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition: TypeBase.h:5998
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UnresolvedUsingTypenameDecl *D)
Definition: TypeBase.h:6035
Represents a dependent using declaration which was marked with typename.
Definition: DeclCXX.h:4031
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
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UsingShadowDecl *D, QualType UnderlyingType)
Definition: TypeBase.h:6075
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:5445
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
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:3982
Expr * getSizeExpr() const
Definition: TypeBase.h:3996
Represents a GCC generic vector type.
Definition: TypeBase.h:4191
unsigned getNumElements() const
Definition: TypeBase.h:4206
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TypeBase.h:4215
VectorKind getVectorKind() const
Definition: TypeBase.h:4211
QualType getElementType() const
Definition: TypeBase.h:4205
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 internal::VariadicAllOfMatcher< Attr > attr
Matches attributes.
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< ArrayType > arrayType
Matches all kinds of arrays.
const AstTypeMatcher< TagType > tagType
Matches tag types (record and enum types).
The JSON file list parser is used to communicate input to InstallAPI.
@ OpenCL
Definition: LangStandard.h:65
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
std::pair< FileID, unsigned > FileIDAndOffset
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:8478
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
NullabilityKind
Describes the nullability of a particular type.
Definition: Specifiers.h:348
@ Nullable
Values of this type can be null.
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
@ NonNull
Values of this type can never be null.
@ ICIS_NoInit
No in-class initializer.
Definition: Specifiers.h:272
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
@ 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.
@ TypeAlignment
Definition: TypeBase.h:76
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition: Linkage.h:24
@ External
External linkage, which indicates that the entity can be referred to from other translation units.
@ Result
The result type of a method or function.
ArraySizeModifier
Capture whether this is a normal array (e.g.
Definition: TypeBase.h:3735
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
@ Template
We are parsing a template declaration.
TagTypeKind
The kind of a tag type.
Definition: TypeBase.h:5906
@ Interface
The "__interface" keyword.
@ Struct
The "struct" keyword.
@ Class
The "class" keyword.
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.
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
TranslationUnitKind
Describes the kind of translation unit being processed.
Definition: LangOptions.h:1097
FloatModeKind
Definition: TargetInfo.h:75
bool isPtrSizeAddressSpace(LangAS AS)
Definition: AddressSpaces.h:95
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
const FunctionProtoType * T
void printTemplateArgumentList(raw_ostream &OS, ArrayRef< TemplateArgument > Args, const PrintingPolicy &Policy, const TemplateParameterList *TPL=nullptr)
Print a template argument list, including the '<' and '>' enclosing the template arguments.
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h: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_C
Definition: Specifiers.h:279
@ 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.
@ Contravariant
The parameter is contravariant, e.g., X<T> is a subtype of X when the type parameter is covariant and...
@ Covariant
The parameter is covariant, e.g., X<T> is a subtype of X when the type parameter is covariant and T i...
VectorKind
Definition: TypeBase.h:4150
@ AltiVecBool
is AltiVec 'vector bool ...'
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
@ AltiVecPixel
is AltiVec 'vector Pixel'
@ Generic
not a target-specific vector type
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
LangAS getLangASFromTargetAS(unsigned TargetAS)
Definition: AddressSpaces.h:90
AlignRequirementKind
Definition: ASTContext.h:144
@ None
The alignment was not explicit in code.
@ RequiredByEnum
The alignment comes from an alignment attribute on a enum type.
@ RequiredByTypedef
The alignment comes from an alignment attribute on a typedef.
@ RequiredByRecord
The alignment comes from an alignment attribute on a record type.
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: TypeBase.h:5881
@ Interface
The "__interface" keyword introduces the elaborated-type-specifier.
@ None
No keyword precedes the qualified type name.
@ Struct
The "struct" keyword introduces the elaborated-type-specifier.
@ Class
The "class" keyword introduces the elaborated-type-specifier.
@ Union
The "union" keyword introduces the elaborated-type-specifier.
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
@ EST_DependentNoexcept
noexcept(expression), value-dependent
@ EST_DynamicNone
throw()
@ EST_Uninstantiated
not instantiated yet
@ EST_Unparsed
not parsed yet
@ EST_NoThrow
Microsoft __declspec(nothrow) extension.
@ EST_None
no exception specification
@ EST_MSAny
Microsoft throw(...) extension.
@ EST_BasicNoexcept
noexcept
@ EST_NoexceptFalse
noexcept(expression), evals to 'false'
@ EST_Unevaluated
not evaluated yet, for special member function
@ EST_NoexceptTrue
noexcept(expression), evals to 'true'
@ EST_Dynamic
throw(T1, T2)
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.
Definition: TemplateBase.h:696
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
bool ParseAllComments
Treat ordinary comments as documentation comments.
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
ArrayRef< TemplateArgument > Args
Definition: TemplateName.h:189
Holds information about the various types of exception specification.
Definition: TypeBase.h:5339
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: TypeBase.h:5341
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition: TypeBase.h:5344
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition: TypeBase.h:5347
Extra information about a function prototype.
Definition: TypeBase.h:5367
bool requiresFunctionProtoTypeArmAttributes() const
Definition: TypeBase.h:5413
const ExtParameterInfo * ExtParameterInfos
Definition: TypeBase.h:5372
bool requiresFunctionProtoTypeExtraAttributeInfo() const
Definition: TypeBase.h:5417
bool requiresFunctionProtoTypeExtraBitfields() const
Definition: TypeBase.h:5406
A simple holder for a QualType representing a type in an exception specification.
Definition: TypeBase.h:4713
A holder for Arm type attributes as described in the Arm C/C++ Language extensions which are not part...
Definition: TypeBase.h:4794
A holder for extra information from attributes which aren't part of an AttributedType.
Definition: TypeBase.h:4742
A simple holder for various uncommon bits which do not fit in FunctionTypeBitfields.
Definition: TypeBase.h:4718
const IdentifierInfo * getIdentifier() const
Returns the identifier to which this template name refers.
Definition: TemplateName.h:559
OverloadedOperatorKind getOperator() const
Return the overloaded operator to which this template name refers.
Definition: TemplateName.h:566
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition: Type.cpp:3264
A lazy value (of type T) that is within an AST node of type Owner, where the value might change in la...
Parts of a decomposed MSGuidDecl.
Definition: DeclCXX.h:4367
Contains information gathered from parsing the contents of TargetAttr.
Definition: TargetInfo.h:60
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition: 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.
static constexpr size_t getOffset()
Definition: TypeBase.h:6464
static TagTypeFoldingSetPlaceholder * fromTagType(TagType *T)
Definition: TypeBase.h:6493
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TagDecl *Tag, bool OwnsTag, bool IsInjected)
Definition: TypeBase.h:6469
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
uint64_t Width
Definition: ASTContext.h:159
unsigned Align
Definition: ASTContext.h:160
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)
Definition: ASTContext.cpp:132
static FoldingSetNodeID getTombstoneKey()
Definition: ASTContext.cpp:120
static unsigned getHashValue(const FoldingSetNodeID &Val)
Definition: ASTContext.cpp:128