Thanks to visit codestin.com
Credit goes to clang.llvm.org

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
117/// \returns The locations that are relevant when searching for Doc comments
118/// related to \p D.
121 assert(D);
122
123 // User can not attach documentation to implicit declarations.
124 if (D->isImplicit())
125 return {};
126
127 // User can not attach documentation to implicit instantiations.
128 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
129 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
130 return {};
131 }
132
133 if (const auto *VD = dyn_cast<VarDecl>(D)) {
134 if (VD->isStaticDataMember() &&
135 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
136 return {};
137 }
138
139 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
140 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
141 return {};
142 }
143
144 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
145 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
146 if (TSK == TSK_ImplicitInstantiation ||
147 TSK == TSK_Undeclared)
148 return {};
149 }
150
151 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
152 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
153 return {};
154 }
155 if (const auto *TD = dyn_cast<TagDecl>(D)) {
156 // When tag declaration (but not definition!) is part of the
157 // decl-specifier-seq of some other declaration, it doesn't get comment
158 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
159 return {};
160 }
161 // TODO: handle comments for function parameters properly.
162 if (isa<ParmVarDecl>(D))
163 return {};
164
165 // TODO: we could look up template parameter documentation in the template
166 // documentation.
170 return {};
171
173 // Find declaration location.
174 // For Objective-C declarations we generally don't expect to have multiple
175 // declarators, thus use declaration starting location as the "declaration
176 // location".
177 // For all other declarations multiple declarators are used quite frequently,
178 // so we use the location of the identifier as the "declaration location".
179 SourceLocation BaseLocation;
183 // Allow association with Y across {} in `typedef struct X {} Y`.
185 BaseLocation = D->getBeginLoc();
186 else
187 BaseLocation = D->getLocation();
188
189 if (!D->getLocation().isMacroID()) {
190 Locations.emplace_back(BaseLocation);
191 } else {
192 const auto *DeclCtx = D->getDeclContext();
193
194 // When encountering definitions generated from a macro (that are not
195 // contained by another declaration in the macro) we need to try and find
196 // the comment at the location of the expansion but if there is no comment
197 // there we should retry to see if there is a comment inside the macro as
198 // well. To this end we return first BaseLocation to first look at the
199 // expansion site, the second value is the spelling location of the
200 // beginning of the declaration defined inside the macro.
201 if (!(DeclCtx &&
202 Decl::castFromDeclContext(DeclCtx)->getLocation().isMacroID())) {
203 Locations.emplace_back(SourceMgr.getExpansionLoc(BaseLocation));
204 }
205
206 // We use Decl::getBeginLoc() and not just BaseLocation here to ensure that
207 // we don't refer to the macro argument location at the expansion site (this
208 // can happen if the name's spelling is provided via macro argument), and
209 // always to the declaration itself.
210 Locations.emplace_back(SourceMgr.getSpellingLoc(D->getBeginLoc()));
211 }
212
213 return Locations;
214}
215
217 const Decl *D, const SourceLocation RepresentativeLocForDecl,
218 const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
219 // If the declaration doesn't map directly to a location in a file, we
220 // can't find the comment.
221 if (RepresentativeLocForDecl.isInvalid() ||
222 !RepresentativeLocForDecl.isFileID())
223 return nullptr;
224
225 // If there are no comments anywhere, we won't find anything.
226 if (CommentsInTheFile.empty())
227 return nullptr;
228
229 // Decompose the location for the declaration and find the beginning of the
230 // file buffer.
231 const FileIDAndOffset DeclLocDecomp =
232 SourceMgr.getDecomposedLoc(RepresentativeLocForDecl);
233
234 // Slow path.
235 auto OffsetCommentBehindDecl =
236 CommentsInTheFile.lower_bound(DeclLocDecomp.second);
237
238 // First check whether we have a trailing comment.
239 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
240 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
241 if ((CommentBehindDecl->isDocumentation() ||
242 LangOpts.CommentOpts.ParseAllComments) &&
243 CommentBehindDecl->isTrailingComment() &&
246
247 // Check that Doxygen trailing comment comes after the declaration, starts
248 // on the same line and in the same file as the declaration.
249 if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) ==
250 Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first,
251 OffsetCommentBehindDecl->first)) {
252 return CommentBehindDecl;
253 }
254 }
255 }
256
257 // The comment just after the declaration was not a trailing comment.
258 // Let's look at the previous comment.
259 if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
260 return nullptr;
261
262 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
263 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
264
265 // Check that we actually have a non-member Doxygen comment.
266 if (!(CommentBeforeDecl->isDocumentation() ||
267 LangOpts.CommentOpts.ParseAllComments) ||
268 CommentBeforeDecl->isTrailingComment())
269 return nullptr;
270
271 // Decompose the end of the comment.
272 const unsigned CommentEndOffset =
273 Comments.getCommentEndOffset(CommentBeforeDecl);
274
275 // Get the corresponding buffer.
276 bool Invalid = false;
277 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
278 &Invalid).data();
279 if (Invalid)
280 return nullptr;
281
282 // Extract text between the comment and declaration.
283 StringRef Text(Buffer + CommentEndOffset,
284 DeclLocDecomp.second - CommentEndOffset);
285
286 // There should be no other declarations or preprocessor directives between
287 // comment and declaration.
288 if (Text.find_last_of(";{}#@") != StringRef::npos)
289 return nullptr;
290
291 return CommentBeforeDecl;
292}
293
295 const auto DeclLocs = getDeclLocsForCommentSearch(D, SourceMgr);
296
297 for (const auto DeclLoc : DeclLocs) {
298 // If the declaration doesn't map directly to a location in a file, we
299 // can't find the comment.
300 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
301 continue;
302
304 ExternalSource->ReadComments();
305 CommentsLoaded = true;
306 }
307
308 if (Comments.empty())
309 continue;
310
311 const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first;
312 if (!File.isValid())
313 continue;
314
315 const auto CommentsInThisFile = Comments.getCommentsInFile(File);
316 if (!CommentsInThisFile || CommentsInThisFile->empty())
317 continue;
318
319 if (RawComment *Comment =
320 getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile))
321 return Comment;
322 }
323
324 return nullptr;
325}
326
328 assert(LangOpts.RetainCommentsFromSystemHeaders ||
329 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
330 Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
331}
332
333/// If we have a 'templated' declaration for a template, adjust 'D' to
334/// refer to the actual template.
335/// If we have an implicit instantiation, adjust 'D' to refer to template.
336static const Decl &adjustDeclToTemplate(const Decl &D) {
337 if (const auto *FD = dyn_cast<FunctionDecl>(&D)) {
338 // Is this function declaration part of a function template?
339 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
340 return *FTD;
341
342 // Nothing to do if function is not an implicit instantiation.
343 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
344 return D;
345
346 // Function is an implicit instantiation of a function template?
347 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
348 return *FTD;
349
350 // Function is instantiated from a member definition of a class template?
351 if (const FunctionDecl *MemberDecl =
353 return *MemberDecl;
354
355 return D;
356 }
357 if (const auto *VD = dyn_cast<VarDecl>(&D)) {
358 // Static data member is instantiated from a member definition of a class
359 // template?
360 if (VD->isStaticDataMember())
361 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
362 return *MemberDecl;
363
364 return D;
365 }
366 if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) {
367 // Is this class declaration part of a class template?
368 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
369 return *CTD;
370
371 // Class is an implicit instantiation of a class template or partial
372 // specialization?
373 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
374 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
375 return D;
376 llvm::PointerUnion<ClassTemplateDecl *,
379 return isa<ClassTemplateDecl *>(PU)
380 ? *static_cast<const Decl *>(cast<ClassTemplateDecl *>(PU))
381 : *static_cast<const Decl *>(
383 }
384
385 // Class is instantiated from a member definition of a class template?
386 if (const MemberSpecializationInfo *Info =
387 CRD->getMemberSpecializationInfo())
388 return *Info->getInstantiatedFrom();
389
390 return D;
391 }
392 if (const auto *ED = dyn_cast<EnumDecl>(&D)) {
393 // Enum is instantiated from a member definition of a class template?
394 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
395 return *MemberDecl;
396
397 return D;
398 }
399 // FIXME: Adjust alias templates?
400 return D;
401}
402
404 const Decl *D,
405 const Decl **OriginalDecl) const {
406 if (!D) {
407 if (OriginalDecl)
408 OriginalDecl = nullptr;
409 return nullptr;
410 }
411
412 D = &adjustDeclToTemplate(*D);
413
414 // Any comment directly attached to D?
415 {
416 auto DeclComment = DeclRawComments.find(D);
417 if (DeclComment != DeclRawComments.end()) {
418 if (OriginalDecl)
419 *OriginalDecl = D;
420 return DeclComment->second;
421 }
422 }
423
424 // Any comment attached to any redeclaration of D?
425 const Decl *CanonicalD = D->getCanonicalDecl();
426 if (!CanonicalD)
427 return nullptr;
428
429 {
430 auto RedeclComment = RedeclChainComments.find(CanonicalD);
431 if (RedeclComment != RedeclChainComments.end()) {
432 if (OriginalDecl)
433 *OriginalDecl = RedeclComment->second;
434 auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second);
435 assert(CommentAtRedecl != DeclRawComments.end() &&
436 "This decl is supposed to have comment attached.");
437 return CommentAtRedecl->second;
438 }
439 }
440
441 // Any redeclarations of D that we haven't checked for comments yet?
442 const Decl *LastCheckedRedecl = [&]() {
443 const Decl *LastChecked = CommentlessRedeclChains.lookup(CanonicalD);
444 bool CanUseCommentlessCache = false;
445 if (LastChecked) {
446 for (auto *Redecl : CanonicalD->redecls()) {
447 if (Redecl == D) {
448 CanUseCommentlessCache = true;
449 break;
450 }
451 if (Redecl == LastChecked)
452 break;
453 }
454 }
455 // FIXME: This could be improved so that even if CanUseCommentlessCache
456 // is false, once we've traversed past CanonicalD we still skip ahead
457 // LastChecked.
458 return CanUseCommentlessCache ? LastChecked : nullptr;
459 }();
460
461 for (const Decl *Redecl : D->redecls()) {
462 assert(Redecl);
463 // Skip all redeclarations that have been checked previously.
464 if (LastCheckedRedecl) {
465 if (LastCheckedRedecl == Redecl) {
466 LastCheckedRedecl = nullptr;
467 }
468 continue;
469 }
470 const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl);
471 if (RedeclComment) {
472 cacheRawCommentForDecl(*Redecl, *RedeclComment);
473 if (OriginalDecl)
474 *OriginalDecl = Redecl;
475 return RedeclComment;
476 }
477 CommentlessRedeclChains[CanonicalD] = Redecl;
478 }
479
480 if (OriginalDecl)
481 *OriginalDecl = nullptr;
482 return nullptr;
483}
484
486 const RawComment &Comment) const {
487 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
488 DeclRawComments.try_emplace(&OriginalD, &Comment);
489 const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl();
490 RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD);
491 CommentlessRedeclChains.erase(CanonicalDecl);
492}
493
494static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
496 const DeclContext *DC = ObjCMethod->getDeclContext();
497 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
498 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
499 if (!ID)
500 return;
501 // Add redeclared method here.
502 for (const auto *Ext : ID->known_extensions()) {
503 if (ObjCMethodDecl *RedeclaredMethod =
504 Ext->getMethod(ObjCMethod->getSelector(),
505 ObjCMethod->isInstanceMethod()))
506 Redeclared.push_back(RedeclaredMethod);
507 }
508 }
509}
510
512 const Preprocessor *PP) {
513 if (Comments.empty() || Decls.empty())
514 return;
515
516 FileID File;
517 for (const Decl *D : Decls) {
518 if (D->isInvalidDecl())
519 continue;
520
521 D = &adjustDeclToTemplate(*D);
522 SourceLocation Loc = D->getLocation();
523 if (Loc.isValid()) {
524 // See if there are any new comments that are not attached to a decl.
525 // The location doesn't have to be precise - we care only about the file.
526 File = SourceMgr.getDecomposedLoc(Loc).first;
527 break;
528 }
529 }
530
531 if (File.isInvalid())
532 return;
533
534 auto CommentsInThisFile = Comments.getCommentsInFile(File);
535 if (!CommentsInThisFile || CommentsInThisFile->empty() ||
536 CommentsInThisFile->rbegin()->second->isAttached())
537 return;
538
539 // There is at least one comment not attached to a decl.
540 // Maybe it should be attached to one of Decls?
541 //
542 // Note that this way we pick up not only comments that precede the
543 // declaration, but also comments that *follow* the declaration -- thanks to
544 // the lookahead in the lexer: we've consumed the semicolon and looked
545 // ahead through comments.
546 for (const Decl *D : Decls) {
547 assert(D);
548 if (D->isInvalidDecl())
549 continue;
550
551 D = &adjustDeclToTemplate(*D);
552
553 if (DeclRawComments.count(D) > 0)
554 continue;
555
556 const auto DeclLocs = getDeclLocsForCommentSearch(D, SourceMgr);
557
558 for (const auto DeclLoc : DeclLocs) {
559 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
560 continue;
561
562 if (RawComment *const DocComment = getRawCommentForDeclNoCacheImpl(
563 D, DeclLoc, *CommentsInThisFile)) {
564 cacheRawCommentForDecl(*D, *DocComment);
565 comments::FullComment *FC = DocComment->parse(*this, PP, D);
566 ParsedComments[D->getCanonicalDecl()] = FC;
567 break;
568 }
569 }
570 }
571}
572
574 const Decl *D) const {
575 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
576 ThisDeclInfo->CommentDecl = D;
577 ThisDeclInfo->IsFilled = false;
578 ThisDeclInfo->fill();
579 ThisDeclInfo->CommentDecl = FC->getDecl();
580 if (!ThisDeclInfo->TemplateParameters)
581 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
583 new (*this) comments::FullComment(FC->getBlocks(),
584 ThisDeclInfo);
585 return CFC;
586}
587
590 return RC ? RC->parse(*this, nullptr, D) : nullptr;
591}
592
594 const Decl *D,
595 const Preprocessor *PP) const {
596 if (!D || D->isInvalidDecl())
597 return nullptr;
598 D = &adjustDeclToTemplate(*D);
599
600 const Decl *Canonical = D->getCanonicalDecl();
601 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
602 ParsedComments.find(Canonical);
603
604 if (Pos != ParsedComments.end()) {
605 if (Canonical != D) {
606 comments::FullComment *FC = Pos->second;
608 return CFC;
609 }
610 return Pos->second;
611 }
612
613 const Decl *OriginalDecl = nullptr;
614
615 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
616 if (!RC) {
619 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
620 if (OMD && OMD->isPropertyAccessor())
621 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
622 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
623 return cloneFullComment(FC, D);
624 if (OMD)
625 addRedeclaredMethods(OMD, Overridden);
626 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
627 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
628 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
629 return cloneFullComment(FC, D);
630 }
631 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
632 // Attach any tag type's documentation to its typedef if latter
633 // does not have one of its own.
634 QualType QT = TD->getUnderlyingType();
635 if (const auto *TT = QT->getAs<TagType>())
636 if (comments::FullComment *FC =
637 getCommentForDecl(TT->getOriginalDecl(), PP))
638 return cloneFullComment(FC, D);
639 }
640 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
641 while (IC->getSuperClass()) {
642 IC = IC->getSuperClass();
644 return cloneFullComment(FC, D);
645 }
646 }
647 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
648 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
650 return cloneFullComment(FC, D);
651 }
652 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
653 if (!(RD = RD->getDefinition()))
654 return nullptr;
655 // Check non-virtual bases.
656 for (const auto &I : RD->bases()) {
657 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
658 continue;
659 QualType Ty = I.getType();
660 if (Ty.isNull())
661 continue;
663 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
664 continue;
665
667 return cloneFullComment(FC, D);
668 }
669 }
670 // Check virtual bases.
671 for (const auto &I : RD->vbases()) {
672 if (I.getAccessSpecifier() != AS_public)
673 continue;
674 QualType Ty = I.getType();
675 if (Ty.isNull())
676 continue;
677 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
678 if (!(VirtualBase= VirtualBase->getDefinition()))
679 continue;
681 return cloneFullComment(FC, D);
682 }
683 }
684 }
685 return nullptr;
686 }
687
688 // If the RawComment was attached to other redeclaration of this Decl, we
689 // should parse the comment in context of that other Decl. This is important
690 // because comments can contain references to parameter names which can be
691 // different across redeclarations.
692 if (D != OriginalDecl && OriginalDecl)
693 return getCommentForDecl(OriginalDecl, PP);
694
695 comments::FullComment *FC = RC->parse(*this, PP, D);
696 ParsedComments[Canonical] = FC;
697 return FC;
698}
699
700void ASTContext::CanonicalTemplateTemplateParm::Profile(
701 llvm::FoldingSetNodeID &ID, const ASTContext &C,
703 ID.AddInteger(Parm->getDepth());
704 ID.AddInteger(Parm->getPosition());
705 ID.AddBoolean(Parm->isParameterPack());
706 ID.AddInteger(Parm->templateParameterKind());
707
709 ID.AddInteger(Params->size());
711 PEnd = Params->end();
712 P != PEnd; ++P) {
713 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
714 ID.AddInteger(0);
715 ID.AddBoolean(TTP->isParameterPack());
716 ID.AddInteger(
717 TTP->getNumExpansionParameters().toInternalRepresentation());
718 continue;
719 }
720
721 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
722 ID.AddInteger(1);
723 ID.AddBoolean(NTTP->isParameterPack());
724 ID.AddPointer(C.getUnconstrainedType(C.getCanonicalType(NTTP->getType()))
725 .getAsOpaquePtr());
726 if (NTTP->isExpandedParameterPack()) {
727 ID.AddBoolean(true);
728 ID.AddInteger(NTTP->getNumExpansionTypes());
729 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
730 QualType T = NTTP->getExpansionType(I);
731 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
732 }
733 } else
734 ID.AddBoolean(false);
735 continue;
736 }
737
738 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
739 ID.AddInteger(2);
740 Profile(ID, C, TTP);
741 }
742}
743
744TemplateTemplateParmDecl *
746 TemplateTemplateParmDecl *TTP) const {
747 // Check if we already have a canonical template template parameter.
748 llvm::FoldingSetNodeID ID;
749 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
750 void *InsertPos = nullptr;
751 CanonicalTemplateTemplateParm *Canonical
752 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
753 if (Canonical)
754 return Canonical->getParam();
755
756 // Build a canonical template parameter list.
758 SmallVector<NamedDecl *, 4> CanonParams;
759 CanonParams.reserve(Params->size());
761 PEnd = Params->end();
762 P != PEnd; ++P) {
763 // Note that, per C++20 [temp.over.link]/6, when determining whether
764 // template-parameters are equivalent, constraints are ignored.
765 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
768 TTP->getDepth(), TTP->getIndex(), nullptr, false,
769 TTP->isParameterPack(), /*HasTypeConstraint=*/false,
770 TTP->getNumExpansionParameters());
771 CanonParams.push_back(NewTTP);
772 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
776 if (NTTP->isExpandedParameterPack()) {
777 SmallVector<QualType, 2> ExpandedTypes;
779 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
780 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
781 ExpandedTInfos.push_back(
782 getTrivialTypeSourceInfo(ExpandedTypes.back()));
783 }
784
788 NTTP->getDepth(),
789 NTTP->getPosition(), nullptr,
790 T,
791 TInfo,
792 ExpandedTypes,
793 ExpandedTInfos);
794 } else {
798 NTTP->getDepth(),
799 NTTP->getPosition(), nullptr,
800 T,
801 NTTP->isParameterPack(),
802 TInfo);
803 }
804 CanonParams.push_back(Param);
805 } else
806 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
808 }
809
812 TTP->getPosition(), TTP->isParameterPack(), nullptr,
814 /*Typename=*/false,
816 CanonParams, SourceLocation(),
817 /*RequiresClause=*/nullptr));
818
819 // Get the new insert position for the node we care about.
820 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
821 assert(!Canonical && "Shouldn't be in the map!");
822 (void)Canonical;
823
824 // Create the canonical template template parameter entry.
825 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
826 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
827 return CanonTTP;
828}
829
832 TemplateTemplateParmDecl *TTP) const {
833 llvm::FoldingSetNodeID ID;
834 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
835 void *InsertPos = nullptr;
836 CanonicalTemplateTemplateParm *Canonical =
837 CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
838 return Canonical ? Canonical->getParam() : nullptr;
839}
840
843 TemplateTemplateParmDecl *CanonTTP) const {
844 llvm::FoldingSetNodeID ID;
845 CanonicalTemplateTemplateParm::Profile(ID, *this, CanonTTP);
846 void *InsertPos = nullptr;
847 if (auto *Existing =
848 CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos))
849 return Existing->getParam();
850 CanonTemplateTemplateParms.InsertNode(
851 new (*this) CanonicalTemplateTemplateParm(CanonTTP), InsertPos);
852 return CanonTTP;
853}
854
855/// Check if a type can have its sanitizer instrumentation elided based on its
856/// presence within an ignorelist.
858 const QualType &Ty) const {
859 std::string TyName = Ty.getUnqualifiedType().getAsString(getPrintingPolicy());
860 return NoSanitizeL->containsType(Mask, TyName);
861}
862
864 auto Kind = getTargetInfo().getCXXABI().getKind();
865 return getLangOpts().CXXABI.value_or(Kind);
866}
867
868CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
869 if (!LangOpts.CPlusPlus) return nullptr;
870
871 switch (getCXXABIKind()) {
872 case TargetCXXABI::AppleARM64:
873 case TargetCXXABI::Fuchsia:
874 case TargetCXXABI::GenericARM: // Same as Itanium at this level
875 case TargetCXXABI::iOS:
876 case TargetCXXABI::WatchOS:
877 case TargetCXXABI::GenericAArch64:
878 case TargetCXXABI::GenericMIPS:
879 case TargetCXXABI::GenericItanium:
880 case TargetCXXABI::WebAssembly:
881 case TargetCXXABI::XL:
882 return CreateItaniumCXXABI(*this);
883 case TargetCXXABI::Microsoft:
884 return CreateMicrosoftCXXABI(*this);
885 }
886 llvm_unreachable("Invalid CXXABI type!");
887}
888
890 if (!InterpContext) {
891 InterpContext.reset(new interp::Context(*this));
892 }
893 return *InterpContext;
894}
895
897 if (!ParentMapCtx)
898 ParentMapCtx.reset(new ParentMapContext(*this));
899 return *ParentMapCtx;
900}
901
903 const LangOptions &LangOpts) {
904 switch (LangOpts.getAddressSpaceMapMangling()) {
906 return TI.useAddressSpaceMapMangling();
908 return true;
910 return false;
911 }
912 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
913}
914
916 IdentifierTable &idents, SelectorTable &sels,
918 : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize),
919 DependentSizedArrayTypes(this_()), DependentSizedExtVectorTypes(this_()),
920 DependentAddressSpaceTypes(this_()), DependentVectorTypes(this_()),
921 DependentSizedMatrixTypes(this_()),
922 FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize),
923 DependentTypeOfExprTypes(this_()), DependentDecltypeTypes(this_()),
924 DependentPackIndexingTypes(this_()), TemplateSpecializationTypes(this_()),
925 DependentBitIntTypes(this_()), SubstTemplateTemplateParmPacks(this_()),
926 DeducedTemplates(this_()), ArrayParameterTypes(this_()),
927 CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
928 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
929 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
930 LangOpts.XRayNeverInstrumentFiles,
931 LangOpts.XRayAttrListFiles, SM)),
932 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
933 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
934 BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this),
935 Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
936 CompCategories(this_()), LastSDM(nullptr, 0) {
938}
939
941 // Release the DenseMaps associated with DeclContext objects.
942 // FIXME: Is this the ideal solution?
943 ReleaseDeclContextMaps();
944
945 // Call all of the deallocation functions on all of their targets.
946 for (auto &Pair : Deallocations)
947 (Pair.first)(Pair.second);
948 Deallocations.clear();
949
950 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
951 // because they can contain DenseMaps.
952 for (llvm::DenseMap<const ObjCInterfaceDecl *,
954 I = ObjCLayouts.begin(),
955 E = ObjCLayouts.end();
956 I != E;)
957 // Increment in loop to prevent using deallocated memory.
958 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
959 R->Destroy(*this);
960 ObjCLayouts.clear();
961
962 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
963 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
964 // Increment in loop to prevent using deallocated memory.
965 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
966 R->Destroy(*this);
967 }
968 ASTRecordLayouts.clear();
969
970 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
971 AEnd = DeclAttrs.end();
972 A != AEnd; ++A)
973 A->second->~AttrVec();
974 DeclAttrs.clear();
975
976 for (const auto &Value : ModuleInitializers)
977 Value.second->~PerModuleInitializers();
978 ModuleInitializers.clear();
979}
980
982
983void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
984 TraversalScope = TopLevelDecls;
986}
987
988void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
989 Deallocations.push_back({Callback, Data});
990}
991
992void
996
998 llvm::errs() << "\n*** AST Context Stats:\n";
999 llvm::errs() << " " << Types.size() << " types total.\n";
1000
1001 unsigned counts[] = {
1002#define TYPE(Name, Parent) 0,
1003#define ABSTRACT_TYPE(Name, Parent)
1004#include "clang/AST/TypeNodes.inc"
1005 0 // Extra
1006 };
1007
1008 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1009 Type *T = Types[i];
1010 counts[(unsigned)T->getTypeClass()]++;
1011 }
1012
1013 unsigned Idx = 0;
1014 unsigned TotalBytes = 0;
1015#define TYPE(Name, Parent) \
1016 if (counts[Idx]) \
1017 llvm::errs() << " " << counts[Idx] << " " << #Name \
1018 << " types, " << sizeof(Name##Type) << " each " \
1019 << "(" << counts[Idx] * sizeof(Name##Type) \
1020 << " bytes)\n"; \
1021 TotalBytes += counts[Idx] * sizeof(Name##Type); \
1022 ++Idx;
1023#define ABSTRACT_TYPE(Name, Parent)
1024#include "clang/AST/TypeNodes.inc"
1025
1026 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
1027
1028 // Implicit special member functions.
1029 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1031 << " implicit default constructors created\n";
1032 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1034 << " implicit copy constructors created\n";
1035 if (getLangOpts().CPlusPlus)
1036 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1038 << " implicit move constructors created\n";
1039 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1041 << " implicit copy assignment operators created\n";
1042 if (getLangOpts().CPlusPlus)
1043 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1045 << " implicit move assignment operators created\n";
1046 llvm::errs() << NumImplicitDestructorsDeclared << "/"
1048 << " implicit destructors created\n";
1049
1050 if (ExternalSource) {
1051 llvm::errs() << "\n";
1052 ExternalSource->PrintStats();
1053 }
1054
1055 BumpAlloc.PrintStats();
1056}
1057
1059 bool NotifyListeners) {
1060 if (NotifyListeners)
1061 if (auto *Listener = getASTMutationListener();
1063 Listener->RedefinedHiddenDefinition(ND, M);
1064
1065 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
1066}
1067
1069 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1070 if (It == MergedDefModules.end())
1071 return;
1072
1073 auto &Merged = It->second;
1074 llvm::DenseSet<Module*> Found;
1075 for (Module *&M : Merged)
1076 if (!Found.insert(M).second)
1077 M = nullptr;
1078 llvm::erase(Merged, nullptr);
1079}
1080
1083 auto MergedIt =
1084 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
1085 if (MergedIt == MergedDefModules.end())
1086 return {};
1087 return MergedIt->second;
1088}
1089
1090void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1091 if (LazyInitializers.empty())
1092 return;
1093
1094 auto *Source = Ctx.getExternalSource();
1095 assert(Source && "lazy initializers but no external source");
1096
1097 auto LazyInits = std::move(LazyInitializers);
1098 LazyInitializers.clear();
1099
1100 for (auto ID : LazyInits)
1101 Initializers.push_back(Source->GetExternalDecl(ID));
1102
1103 assert(LazyInitializers.empty() &&
1104 "GetExternalDecl for lazy module initializer added more inits");
1105}
1106
1108 // One special case: if we add a module initializer that imports another
1109 // module, and that module's only initializer is an ImportDecl, simplify.
1110 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1111 auto It = ModuleInitializers.find(ID->getImportedModule());
1112
1113 // Maybe the ImportDecl does nothing at all. (Common case.)
1114 if (It == ModuleInitializers.end())
1115 return;
1116
1117 // Maybe the ImportDecl only imports another ImportDecl.
1118 auto &Imported = *It->second;
1119 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1120 Imported.resolve(*this);
1121 auto *OnlyDecl = Imported.Initializers.front();
1122 if (isa<ImportDecl>(OnlyDecl))
1123 D = OnlyDecl;
1124 }
1125 }
1126
1127 auto *&Inits = ModuleInitializers[M];
1128 if (!Inits)
1129 Inits = new (*this) PerModuleInitializers;
1130 Inits->Initializers.push_back(D);
1131}
1132
1135 auto *&Inits = ModuleInitializers[M];
1136 if (!Inits)
1137 Inits = new (*this) PerModuleInitializers;
1138 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1139 IDs.begin(), IDs.end());
1140}
1141
1143 auto It = ModuleInitializers.find(M);
1144 if (It == ModuleInitializers.end())
1145 return {};
1146
1147 auto *Inits = It->second;
1148 Inits->resolve(*this);
1149 return Inits->Initializers;
1150}
1151
1153 assert(M->isNamedModule());
1154 assert(!CurrentCXXNamedModule &&
1155 "We should set named module for ASTContext for only once");
1156 CurrentCXXNamedModule = M;
1157}
1158
1159bool ASTContext::isInSameModule(const Module *M1, const Module *M2) const {
1160 if (!M1 != !M2)
1161 return false;
1162
1163 /// Get the representative module for M. The representative module is the
1164 /// first module unit for a specific primary module name. So that the module
1165 /// units have the same representative module belongs to the same module.
1166 ///
1167 /// The process is helpful to reduce the expensive string operations.
1168 auto GetRepresentativeModule = [this](const Module *M) {
1169 auto Iter = SameModuleLookupSet.find(M);
1170 if (Iter != SameModuleLookupSet.end())
1171 return Iter->second;
1172
1173 const Module *RepresentativeModule =
1174 PrimaryModuleNameMap.try_emplace(M->getPrimaryModuleInterfaceName(), M)
1175 .first->second;
1176 SameModuleLookupSet[M] = RepresentativeModule;
1177 return RepresentativeModule;
1178 };
1179
1180 assert(M1 && "Shouldn't call `isInSameModule` if both M1 and M2 are none.");
1181 return GetRepresentativeModule(M1) == GetRepresentativeModule(M2);
1182}
1183
1185 if (!ExternCContext)
1186 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1187
1188 return ExternCContext;
1189}
1190
1201
1202#define BuiltinTemplate(BTName) \
1203 BuiltinTemplateDecl *ASTContext::get##BTName##Decl() const { \
1204 if (!Decl##BTName) \
1205 Decl##BTName = \
1206 buildBuiltinTemplateDecl(BTK##BTName, get##BTName##Name()); \
1207 return Decl##BTName; \
1208 }
1209#include "clang/Basic/BuiltinTemplates.inc"
1210
1212 RecordDecl::TagKind TK) const {
1213 SourceLocation Loc;
1214 RecordDecl *NewDecl;
1215 if (getLangOpts().CPlusPlus)
1216 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1217 Loc, &Idents.get(Name));
1218 else
1219 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1220 &Idents.get(Name));
1221 NewDecl->setImplicit();
1222 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1223 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1224 return NewDecl;
1225}
1226
1228 StringRef Name) const {
1231 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1232 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1233 NewDecl->setImplicit();
1234 return NewDecl;
1235}
1236
1238 if (!Int128Decl)
1239 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1240 return Int128Decl;
1241}
1242
1244 if (!UInt128Decl)
1245 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1246 return UInt128Decl;
1247}
1248
1249void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1250 auto *Ty = new (*this, alignof(BuiltinType)) BuiltinType(K);
1252 Types.push_back(Ty);
1253}
1254
1256 const TargetInfo *AuxTarget) {
1257 assert((!this->Target || this->Target == &Target) &&
1258 "Incorrect target reinitialization");
1259 assert(VoidTy.isNull() && "Context reinitialized?");
1260
1261 this->Target = &Target;
1262 this->AuxTarget = AuxTarget;
1263
1264 ABI.reset(createCXXABI(Target));
1265 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1266
1267 // C99 6.2.5p19.
1268 InitBuiltinType(VoidTy, BuiltinType::Void);
1269
1270 // C99 6.2.5p2.
1271 InitBuiltinType(BoolTy, BuiltinType::Bool);
1272 // C99 6.2.5p3.
1273 if (LangOpts.CharIsSigned)
1274 InitBuiltinType(CharTy, BuiltinType::Char_S);
1275 else
1276 InitBuiltinType(CharTy, BuiltinType::Char_U);
1277 // C99 6.2.5p4.
1278 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1279 InitBuiltinType(ShortTy, BuiltinType::Short);
1280 InitBuiltinType(IntTy, BuiltinType::Int);
1281 InitBuiltinType(LongTy, BuiltinType::Long);
1282 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1283
1284 // C99 6.2.5p6.
1285 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1286 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1287 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1288 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1289 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1290
1291 // C99 6.2.5p10.
1292 InitBuiltinType(FloatTy, BuiltinType::Float);
1293 InitBuiltinType(DoubleTy, BuiltinType::Double);
1294 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1295
1296 // GNU extension, __float128 for IEEE quadruple precision
1297 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1298
1299 // __ibm128 for IBM extended precision
1300 InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128);
1301
1302 // C11 extension ISO/IEC TS 18661-3
1303 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1304
1305 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1306 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1307 InitBuiltinType(AccumTy, BuiltinType::Accum);
1308 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1309 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1310 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1311 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1312 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1313 InitBuiltinType(FractTy, BuiltinType::Fract);
1314 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1315 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1316 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1317 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1318 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1319 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1320 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1321 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1322 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1323 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1324 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1325 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1326 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1327 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1328 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1329 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
1330
1331 // GNU extension, 128-bit integers.
1332 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1333 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1334
1335 // C++ 3.9.1p5
1336 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1337 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1338 else // -fshort-wchar makes wchar_t be unsigned.
1339 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1340 if (LangOpts.CPlusPlus && LangOpts.WChar)
1342 else {
1343 // C99 (or C++ using -fno-wchar).
1344 WideCharTy = getFromTargetType(Target.getWCharType());
1345 }
1346
1347 WIntTy = getFromTargetType(Target.getWIntType());
1348
1349 // C++20 (proposed)
1350 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1351
1352 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1353 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1354 else // C99
1355 Char16Ty = getFromTargetType(Target.getChar16Type());
1356
1357 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1358 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1359 else // C99
1360 Char32Ty = getFromTargetType(Target.getChar32Type());
1361
1362 // Placeholder type for type-dependent expressions whose type is
1363 // completely unknown. No code should ever check a type against
1364 // DependentTy and users should never see it; however, it is here to
1365 // help diagnose failures to properly check for type-dependent
1366 // expressions.
1367 InitBuiltinType(DependentTy, BuiltinType::Dependent);
1368
1369 // Placeholder type for functions.
1370 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1371
1372 // Placeholder type for bound members.
1373 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1374
1375 // Placeholder type for unresolved templates.
1376 InitBuiltinType(UnresolvedTemplateTy, BuiltinType::UnresolvedTemplate);
1377
1378 // Placeholder type for pseudo-objects.
1379 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1380
1381 // "any" type; useful for debugger-like clients.
1382 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1383
1384 // Placeholder type for unbridged ARC casts.
1385 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1386
1387 // Placeholder type for builtin functions.
1388 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1389
1390 // Placeholder type for OMP array sections.
1391 if (LangOpts.OpenMP) {
1392 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1393 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1394 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1395 }
1396 // Placeholder type for OpenACC array sections, if we are ALSO in OMP mode,
1397 // don't bother, as we're just using the same type as OMP.
1398 if (LangOpts.OpenACC && !LangOpts.OpenMP) {
1399 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1400 }
1401 if (LangOpts.MatrixTypes)
1402 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1403
1404 // Builtin types for 'id', 'Class', and 'SEL'.
1405 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1406 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1407 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1408
1409 if (LangOpts.OpenCL) {
1410#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1411 InitBuiltinType(SingletonId, BuiltinType::Id);
1412#include "clang/Basic/OpenCLImageTypes.def"
1413
1414 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1415 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1416 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1417 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1418 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1419
1420#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1421 InitBuiltinType(Id##Ty, BuiltinType::Id);
1422#include "clang/Basic/OpenCLExtensionTypes.def"
1423 }
1424
1425 if (LangOpts.HLSL) {
1426#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
1427 InitBuiltinType(SingletonId, BuiltinType::Id);
1428#include "clang/Basic/HLSLIntangibleTypes.def"
1429 }
1430
1431 if (Target.hasAArch64ACLETypes() ||
1432 (AuxTarget && AuxTarget->hasAArch64ACLETypes())) {
1433#define SVE_TYPE(Name, Id, SingletonId) \
1434 InitBuiltinType(SingletonId, BuiltinType::Id);
1435#include "clang/Basic/AArch64ACLETypes.def"
1436 }
1437
1438 if (Target.getTriple().isPPC64()) {
1439#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1440 InitBuiltinType(Id##Ty, BuiltinType::Id);
1441#include "clang/Basic/PPCTypes.def"
1442#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1443 InitBuiltinType(Id##Ty, BuiltinType::Id);
1444#include "clang/Basic/PPCTypes.def"
1445 }
1446
1447 if (Target.hasRISCVVTypes()) {
1448#define RVV_TYPE(Name, Id, SingletonId) \
1449 InitBuiltinType(SingletonId, BuiltinType::Id);
1450#include "clang/Basic/RISCVVTypes.def"
1451 }
1452
1453 if (Target.getTriple().isWasm() && Target.hasFeature("reference-types")) {
1454#define WASM_TYPE(Name, Id, SingletonId) \
1455 InitBuiltinType(SingletonId, BuiltinType::Id);
1456#include "clang/Basic/WebAssemblyReferenceTypes.def"
1457 }
1458
1459 if (Target.getTriple().isAMDGPU() ||
1460 (AuxTarget && AuxTarget->getTriple().isAMDGPU())) {
1461#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
1462 InitBuiltinType(SingletonId, BuiltinType::Id);
1463#include "clang/Basic/AMDGPUTypes.def"
1464 }
1465
1466 // Builtin type for __objc_yes and __objc_no
1467 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1469
1470 ObjCConstantStringType = QualType();
1471
1472 ObjCSuperType = QualType();
1473
1474 // void * type
1475 if (LangOpts.OpenCLGenericAddressSpace) {
1476 auto Q = VoidTy.getQualifiers();
1477 Q.setAddressSpace(LangAS::opencl_generic);
1479 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1480 } else {
1482 }
1483
1484 // nullptr type (C++0x 2.14.7)
1485 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1486
1487 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1488 InitBuiltinType(HalfTy, BuiltinType::Half);
1489
1490 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1491
1492 // Builtin type used to help define __builtin_va_list.
1493 VaListTagDecl = nullptr;
1494
1495 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1496 if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1499 }
1500}
1501
1503 return SourceMgr.getDiagnostics();
1504}
1505
1507 AttrVec *&Result = DeclAttrs[D];
1508 if (!Result) {
1509 void *Mem = Allocate(sizeof(AttrVec));
1510 Result = new (Mem) AttrVec;
1511 }
1512
1513 return *Result;
1514}
1515
1516/// Erase the attributes corresponding to the given declaration.
1518 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1519 if (Pos != DeclAttrs.end()) {
1520 Pos->second->~AttrVec();
1521 DeclAttrs.erase(Pos);
1522 }
1523}
1524
1525// FIXME: Remove ?
1528 assert(Var->isStaticDataMember() && "Not a static data member");
1530 .dyn_cast<MemberSpecializationInfo *>();
1531}
1532
1535 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1536 TemplateOrInstantiation.find(Var);
1537 if (Pos == TemplateOrInstantiation.end())
1538 return {};
1539
1540 return Pos->second;
1541}
1542
1543void
1546 SourceLocation PointOfInstantiation) {
1547 assert(Inst->isStaticDataMember() && "Not a static data member");
1548 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1550 Tmpl, TSK, PointOfInstantiation));
1551}
1552
1553void
1556 assert(!TemplateOrInstantiation[Inst] &&
1557 "Already noted what the variable was instantiated from");
1558 TemplateOrInstantiation[Inst] = TSI;
1559}
1560
1561NamedDecl *
1563 return InstantiatedFromUsingDecl.lookup(UUD);
1564}
1565
1566void
1568 assert((isa<UsingDecl>(Pattern) ||
1571 "pattern decl is not a using decl");
1572 assert((isa<UsingDecl>(Inst) ||
1575 "instantiation did not produce a using decl");
1576 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1577 InstantiatedFromUsingDecl[Inst] = Pattern;
1578}
1579
1582 return InstantiatedFromUsingEnumDecl.lookup(UUD);
1583}
1584
1586 UsingEnumDecl *Pattern) {
1587 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
1588 InstantiatedFromUsingEnumDecl[Inst] = Pattern;
1589}
1590
1593 return InstantiatedFromUsingShadowDecl.lookup(Inst);
1594}
1595
1596void
1598 UsingShadowDecl *Pattern) {
1599 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1600 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1601}
1602
1603FieldDecl *
1605 return InstantiatedFromUnnamedFieldDecl.lookup(Field);
1606}
1607
1609 FieldDecl *Tmpl) {
1610 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1611 "Instantiated field decl is not unnamed");
1612 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1613 "Template field decl is not unnamed");
1614 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1615 "Already noted what unnamed field was instantiated from");
1616
1617 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1618}
1619
1624
1629
1630unsigned
1632 auto Range = overridden_methods(Method);
1633 return Range.end() - Range.begin();
1634}
1635
1638 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1639 OverriddenMethods.find(Method->getCanonicalDecl());
1640 if (Pos == OverriddenMethods.end())
1641 return overridden_method_range(nullptr, nullptr);
1642 return overridden_method_range(Pos->second.begin(), Pos->second.end());
1643}
1644
1646 const CXXMethodDecl *Overridden) {
1647 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1648 OverriddenMethods[Method].push_back(Overridden);
1649}
1650
1652 const NamedDecl *D,
1653 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1654 assert(D);
1655
1656 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1657 Overridden.append(overridden_methods_begin(CXXMethod),
1658 overridden_methods_end(CXXMethod));
1659 return;
1660 }
1661
1662 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1663 if (!Method)
1664 return;
1665
1667 Method->getOverriddenMethods(OverDecls);
1668 Overridden.append(OverDecls.begin(), OverDecls.end());
1669}
1670
1671std::optional<ASTContext::CXXRecordDeclRelocationInfo>
1673 assert(RD);
1674 CXXRecordDecl *D = RD->getDefinition();
1675 auto it = RelocatableClasses.find(D);
1676 if (it != RelocatableClasses.end())
1677 return it->getSecond();
1678 return std::nullopt;
1679}
1680
1683 assert(RD);
1684 CXXRecordDecl *D = RD->getDefinition();
1685 assert(RelocatableClasses.find(D) == RelocatableClasses.end());
1686 RelocatableClasses.insert({D, Info});
1687}
1688
1690 const ASTContext &Context, const CXXRecordDecl *Class) {
1691 if (!Class->isPolymorphic())
1692 return false;
1693 const CXXRecordDecl *BaseType = Context.baseForVTableAuthentication(Class);
1694 using AuthAttr = VTablePointerAuthenticationAttr;
1695 const AuthAttr *ExplicitAuth = BaseType->getAttr<AuthAttr>();
1696 if (!ExplicitAuth)
1697 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1698 AuthAttr::AddressDiscriminationMode AddressDiscrimination =
1699 ExplicitAuth->getAddressDiscrimination();
1700 if (AddressDiscrimination == AuthAttr::DefaultAddressDiscrimination)
1701 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1702 return AddressDiscrimination == AuthAttr::AddressDiscrimination;
1703}
1704
1705ASTContext::PointerAuthContent
1706ASTContext::findPointerAuthContent(QualType T) const {
1707 assert(isPointerAuthenticationAvailable());
1708
1709 T = T.getCanonicalType();
1710 if (T->isDependentType())
1711 return PointerAuthContent::None;
1712
1713 if (T.hasAddressDiscriminatedPointerAuth())
1714 return PointerAuthContent::AddressDiscriminatedData;
1715 const RecordDecl *RD = T->getAsRecordDecl();
1716 if (!RD)
1717 return PointerAuthContent::None;
1718
1719 if (auto Existing = RecordContainsAddressDiscriminatedPointerAuth.find(RD);
1720 Existing != RecordContainsAddressDiscriminatedPointerAuth.end())
1721 return Existing->second;
1722
1723 PointerAuthContent Result = PointerAuthContent::None;
1724
1725 auto SaveResultAndReturn = [&]() -> PointerAuthContent {
1726 auto [ResultIter, DidAdd] =
1727 RecordContainsAddressDiscriminatedPointerAuth.try_emplace(RD, Result);
1728 (void)ResultIter;
1729 (void)DidAdd;
1730 assert(DidAdd);
1731 return Result;
1732 };
1733 auto ShouldContinueAfterUpdate = [&](PointerAuthContent NewResult) {
1734 static_assert(PointerAuthContent::None <
1735 PointerAuthContent::AddressDiscriminatedVTable);
1736 static_assert(PointerAuthContent::AddressDiscriminatedVTable <
1737 PointerAuthContent::AddressDiscriminatedData);
1738 if (NewResult > Result)
1739 Result = NewResult;
1740 return Result != PointerAuthContent::AddressDiscriminatedData;
1741 };
1742 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1744 !ShouldContinueAfterUpdate(
1745 PointerAuthContent::AddressDiscriminatedVTable))
1746 return SaveResultAndReturn();
1747 for (auto Base : CXXRD->bases()) {
1748 if (!ShouldContinueAfterUpdate(findPointerAuthContent(Base.getType())))
1749 return SaveResultAndReturn();
1750 }
1751 }
1752 for (auto *FieldDecl : RD->fields()) {
1753 if (!ShouldContinueAfterUpdate(
1754 findPointerAuthContent(FieldDecl->getType())))
1755 return SaveResultAndReturn();
1756 }
1757 return SaveResultAndReturn();
1758}
1759
1761 assert(!Import->getNextLocalImport() &&
1762 "Import declaration already in the chain");
1763 assert(!Import->isFromASTFile() && "Non-local import declaration");
1764 if (!FirstLocalImport) {
1765 FirstLocalImport = Import;
1766 LastLocalImport = Import;
1767 return;
1768 }
1769
1770 LastLocalImport->setNextLocalImport(Import);
1771 LastLocalImport = Import;
1772}
1773
1774//===----------------------------------------------------------------------===//
1775// Type Sizing and Analysis
1776//===----------------------------------------------------------------------===//
1777
1778/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1779/// scalar floating point type.
1780const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1781 switch (T->castAs<BuiltinType>()->getKind()) {
1782 default:
1783 llvm_unreachable("Not a floating point type!");
1784 case BuiltinType::BFloat16:
1785 return Target->getBFloat16Format();
1786 case BuiltinType::Float16:
1787 return Target->getHalfFormat();
1788 case BuiltinType::Half:
1789 return Target->getHalfFormat();
1790 case BuiltinType::Float: return Target->getFloatFormat();
1791 case BuiltinType::Double: return Target->getDoubleFormat();
1792 case BuiltinType::Ibm128:
1793 return Target->getIbm128Format();
1794 case BuiltinType::LongDouble:
1795 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1796 return AuxTarget->getLongDoubleFormat();
1797 return Target->getLongDoubleFormat();
1798 case BuiltinType::Float128:
1799 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1800 return AuxTarget->getFloat128Format();
1801 return Target->getFloat128Format();
1802 }
1803}
1804
1805CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1806 unsigned Align = Target->getCharWidth();
1807
1808 const unsigned AlignFromAttr = D->getMaxAlignment();
1809 if (AlignFromAttr)
1810 Align = AlignFromAttr;
1811
1812 // __attribute__((aligned)) can increase or decrease alignment
1813 // *except* on a struct or struct member, where it only increases
1814 // alignment unless 'packed' is also specified.
1815 //
1816 // It is an error for alignas to decrease alignment, so we can
1817 // ignore that possibility; Sema should diagnose it.
1818 bool UseAlignAttrOnly;
1819 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D))
1820 UseAlignAttrOnly =
1821 FD->hasAttr<PackedAttr>() || FD->getParent()->hasAttr<PackedAttr>();
1822 else
1823 UseAlignAttrOnly = AlignFromAttr != 0;
1824 // If we're using the align attribute only, just ignore everything
1825 // else about the declaration and its type.
1826 if (UseAlignAttrOnly) {
1827 // do nothing
1828 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1829 QualType T = VD->getType();
1830 if (const auto *RT = T->getAs<ReferenceType>()) {
1831 if (ForAlignof)
1832 T = RT->getPointeeType();
1833 else
1834 T = getPointerType(RT->getPointeeType());
1835 }
1836 QualType BaseT = getBaseElementType(T);
1837 if (T->isFunctionType())
1838 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1839 else if (!BaseT->isIncompleteType()) {
1840 // Adjust alignments of declarations with array type by the
1841 // large-array alignment on the target.
1842 if (const ArrayType *arrayType = getAsArrayType(T)) {
1843 unsigned MinWidth = Target->getLargeArrayMinWidth();
1844 if (!ForAlignof && MinWidth) {
1846 Align = std::max(Align, Target->getLargeArrayAlign());
1849 Align = std::max(Align, Target->getLargeArrayAlign());
1850 }
1851 }
1852 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1853 if (BaseT.getQualifiers().hasUnaligned())
1854 Align = Target->getCharWidth();
1855 }
1856
1857 // Ensure minimum alignment for global variables.
1858 if (const auto *VD = dyn_cast<VarDecl>(D))
1859 if (VD->hasGlobalStorage() && !ForAlignof) {
1860 uint64_t TypeSize =
1861 !BaseT->isIncompleteType() ? getTypeSize(T.getTypePtr()) : 0;
1862 Align = std::max(Align, getMinGlobalAlignOfVar(TypeSize, VD));
1863 }
1864
1865 // Fields can be subject to extra alignment constraints, like if
1866 // the field is packed, the struct is packed, or the struct has a
1867 // a max-field-alignment constraint (#pragma pack). So calculate
1868 // the actual alignment of the field within the struct, and then
1869 // (as we're expected to) constrain that by the alignment of the type.
1870 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1871 const RecordDecl *Parent = Field->getParent();
1872 // We can only produce a sensible answer if the record is valid.
1873 if (!Parent->isInvalidDecl()) {
1874 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1875
1876 // Start with the record's overall alignment.
1877 unsigned FieldAlign = toBits(Layout.getAlignment());
1878
1879 // Use the GCD of that and the offset within the record.
1880 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1881 if (Offset > 0) {
1882 // Alignment is always a power of 2, so the GCD will be a power of 2,
1883 // which means we get to do this crazy thing instead of Euclid's.
1884 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1885 if (LowBitOfOffset < FieldAlign)
1886 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1887 }
1888
1889 Align = std::min(Align, FieldAlign);
1890 }
1891 }
1892 }
1893
1894 // Some targets have hard limitation on the maximum requestable alignment in
1895 // aligned attribute for static variables.
1896 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1897 const auto *VD = dyn_cast<VarDecl>(D);
1898 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1899 Align = std::min(Align, MaxAlignedAttr);
1900
1901 return toCharUnitsFromBits(Align);
1902}
1903
1905 return toCharUnitsFromBits(Target->getExnObjectAlignment());
1906}
1907
1908// getTypeInfoDataSizeInChars - Return the size of a type, in
1909// chars. If the type is a record, its data size is returned. This is
1910// the size of the memcpy that's performed when assigning this type
1911// using a trivial copy/move assignment operator.
1914
1915 // In C++, objects can sometimes be allocated into the tail padding
1916 // of a base-class subobject. We decide whether that's possible
1917 // during class layout, so here we can just trust the layout results.
1918 if (getLangOpts().CPlusPlus) {
1919 if (const auto *RD = T->getAsCXXRecordDecl(); RD && !RD->isInvalidDecl()) {
1920 const ASTRecordLayout &layout = getASTRecordLayout(RD);
1921 Info.Width = layout.getDataSize();
1922 }
1923 }
1924
1925 return Info;
1926}
1927
1928/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1929/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1932 const ConstantArrayType *CAT) {
1933 TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
1934 uint64_t Size = CAT->getZExtSize();
1935 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1936 (uint64_t)(-1)/Size) &&
1937 "Overflow in array type char size evaluation");
1938 uint64_t Width = EltInfo.Width.getQuantity() * Size;
1939 unsigned Align = EltInfo.Align.getQuantity();
1940 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1941 Context.getTargetInfo().getPointerWidth(LangAS::Default) == 64)
1942 Width = llvm::alignTo(Width, Align);
1945 EltInfo.AlignRequirement);
1946}
1947
1949 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1950 return getConstantArrayInfoInChars(*this, CAT);
1951 TypeInfo Info = getTypeInfo(T);
1954}
1955
1959
1961 // HLSL doesn't promote all small integer types to int, it
1962 // just uses the rank-based promotion rules for all types.
1963 if (getLangOpts().HLSL)
1964 return false;
1965
1966 if (const auto *BT = T->getAs<BuiltinType>())
1967 switch (BT->getKind()) {
1968 case BuiltinType::Bool:
1969 case BuiltinType::Char_S:
1970 case BuiltinType::Char_U:
1971 case BuiltinType::SChar:
1972 case BuiltinType::UChar:
1973 case BuiltinType::Short:
1974 case BuiltinType::UShort:
1975 case BuiltinType::WChar_S:
1976 case BuiltinType::WChar_U:
1977 case BuiltinType::Char8:
1978 case BuiltinType::Char16:
1979 case BuiltinType::Char32:
1980 return true;
1981 default:
1982 return false;
1983 }
1984
1985 // Enumerated types are promotable to their compatible integer types
1986 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
1987 if (const auto *ED = T->getAsEnumDecl()) {
1988 if (T->isDependentType() || ED->getPromotionType().isNull() ||
1989 ED->isScoped())
1990 return false;
1991
1992 return true;
1993 }
1994
1995 return false;
1996}
1997
2001
2003 return isAlignmentRequired(T.getTypePtr());
2004}
2005
2007 bool NeedsPreferredAlignment) const {
2008 // An alignment on a typedef overrides anything else.
2009 if (const auto *TT = T->getAs<TypedefType>())
2010 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2011 return Align;
2012
2013 // If we have an (array of) complete type, we're done.
2015 if (!T->isIncompleteType())
2016 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
2017
2018 // If we had an array type, its element type might be a typedef
2019 // type with an alignment attribute.
2020 if (const auto *TT = T->getAs<TypedefType>())
2021 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2022 return Align;
2023
2024 // Otherwise, see if the declaration of the type had an attribute.
2025 if (const auto *TD = T->getAsTagDecl())
2026 return TD->getMaxAlignment();
2027
2028 return 0;
2029}
2030
2032 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
2033 if (I != MemoizedTypeInfo.end())
2034 return I->second;
2035
2036 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
2037 TypeInfo TI = getTypeInfoImpl(T);
2038 MemoizedTypeInfo[T] = TI;
2039 return TI;
2040}
2041
2042/// getTypeInfoImpl - Return the size of the specified type, in bits. This
2043/// method does not work on incomplete types.
2044///
2045/// FIXME: Pointers into different addr spaces could have different sizes and
2046/// alignment requirements: getPointerInfo should take an AddrSpace, this
2047/// should take a QualType, &c.
2048TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
2049 uint64_t Width = 0;
2050 unsigned Align = 8;
2053 switch (T->getTypeClass()) {
2054#define TYPE(Class, Base)
2055#define ABSTRACT_TYPE(Class, Base)
2056#define NON_CANONICAL_TYPE(Class, Base)
2057#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2058#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
2059 case Type::Class: \
2060 assert(!T->isDependentType() && "should not see dependent types here"); \
2061 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
2062#include "clang/AST/TypeNodes.inc"
2063 llvm_unreachable("Should not see dependent types");
2064
2065 case Type::FunctionNoProto:
2066 case Type::FunctionProto:
2067 // GCC extension: alignof(function) = 32 bits
2068 Width = 0;
2069 Align = 32;
2070 break;
2071
2072 case Type::IncompleteArray:
2073 case Type::VariableArray:
2074 case Type::ConstantArray:
2075 case Type::ArrayParameter: {
2076 // Model non-constant sized arrays as size zero, but track the alignment.
2077 uint64_t Size = 0;
2078 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
2079 Size = CAT->getZExtSize();
2080
2081 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
2082 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
2083 "Overflow in array type bit size evaluation");
2084 Width = EltInfo.Width * Size;
2085 Align = EltInfo.Align;
2086 AlignRequirement = EltInfo.AlignRequirement;
2087 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
2088 getTargetInfo().getPointerWidth(LangAS::Default) == 64)
2089 Width = llvm::alignTo(Width, Align);
2090 break;
2091 }
2092
2093 case Type::ExtVector:
2094 case Type::Vector: {
2095 const auto *VT = cast<VectorType>(T);
2096 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
2097 Width = VT->isPackedVectorBoolType(*this)
2098 ? VT->getNumElements()
2099 : EltInfo.Width * VT->getNumElements();
2100 // Enforce at least byte size and alignment.
2101 Width = std::max<unsigned>(8, Width);
2102 Align = std::max<unsigned>(8, Width);
2103
2104 // If the alignment is not a power of 2, round up to the next power of 2.
2105 // This happens for non-power-of-2 length vectors.
2106 if (Align & (Align-1)) {
2107 Align = llvm::bit_ceil(Align);
2108 Width = llvm::alignTo(Width, Align);
2109 }
2110 // Adjust the alignment based on the target max.
2111 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
2112 if (TargetVectorAlign && TargetVectorAlign < Align)
2113 Align = TargetVectorAlign;
2114 if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
2115 // Adjust the alignment for fixed-length SVE vectors. This is important
2116 // for non-power-of-2 vector lengths.
2117 Align = 128;
2118 else if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
2119 // Adjust the alignment for fixed-length SVE predicates.
2120 Align = 16;
2121 else if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
2122 VT->getVectorKind() == VectorKind::RVVFixedLengthMask ||
2123 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
2124 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
2125 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4)
2126 // Adjust the alignment for fixed-length RVV vectors.
2127 Align = std::min<unsigned>(64, Width);
2128 break;
2129 }
2130
2131 case Type::ConstantMatrix: {
2132 const auto *MT = cast<ConstantMatrixType>(T);
2133 TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
2134 // The internal layout of a matrix value is implementation defined.
2135 // Initially be ABI compatible with arrays with respect to alignment and
2136 // size.
2137 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
2138 Align = ElementInfo.Align;
2139 break;
2140 }
2141
2142 case Type::Builtin:
2143 switch (cast<BuiltinType>(T)->getKind()) {
2144 default: llvm_unreachable("Unknown builtin type!");
2145 case BuiltinType::Void:
2146 // GCC extension: alignof(void) = 8 bits.
2147 Width = 0;
2148 Align = 8;
2149 break;
2150 case BuiltinType::Bool:
2151 Width = Target->getBoolWidth();
2152 Align = Target->getBoolAlign();
2153 break;
2154 case BuiltinType::Char_S:
2155 case BuiltinType::Char_U:
2156 case BuiltinType::UChar:
2157 case BuiltinType::SChar:
2158 case BuiltinType::Char8:
2159 Width = Target->getCharWidth();
2160 Align = Target->getCharAlign();
2161 break;
2162 case BuiltinType::WChar_S:
2163 case BuiltinType::WChar_U:
2164 Width = Target->getWCharWidth();
2165 Align = Target->getWCharAlign();
2166 break;
2167 case BuiltinType::Char16:
2168 Width = Target->getChar16Width();
2169 Align = Target->getChar16Align();
2170 break;
2171 case BuiltinType::Char32:
2172 Width = Target->getChar32Width();
2173 Align = Target->getChar32Align();
2174 break;
2175 case BuiltinType::UShort:
2176 case BuiltinType::Short:
2177 Width = Target->getShortWidth();
2178 Align = Target->getShortAlign();
2179 break;
2180 case BuiltinType::UInt:
2181 case BuiltinType::Int:
2182 Width = Target->getIntWidth();
2183 Align = Target->getIntAlign();
2184 break;
2185 case BuiltinType::ULong:
2186 case BuiltinType::Long:
2187 Width = Target->getLongWidth();
2188 Align = Target->getLongAlign();
2189 break;
2190 case BuiltinType::ULongLong:
2191 case BuiltinType::LongLong:
2192 Width = Target->getLongLongWidth();
2193 Align = Target->getLongLongAlign();
2194 break;
2195 case BuiltinType::Int128:
2196 case BuiltinType::UInt128:
2197 Width = 128;
2198 Align = Target->getInt128Align();
2199 break;
2200 case BuiltinType::ShortAccum:
2201 case BuiltinType::UShortAccum:
2202 case BuiltinType::SatShortAccum:
2203 case BuiltinType::SatUShortAccum:
2204 Width = Target->getShortAccumWidth();
2205 Align = Target->getShortAccumAlign();
2206 break;
2207 case BuiltinType::Accum:
2208 case BuiltinType::UAccum:
2209 case BuiltinType::SatAccum:
2210 case BuiltinType::SatUAccum:
2211 Width = Target->getAccumWidth();
2212 Align = Target->getAccumAlign();
2213 break;
2214 case BuiltinType::LongAccum:
2215 case BuiltinType::ULongAccum:
2216 case BuiltinType::SatLongAccum:
2217 case BuiltinType::SatULongAccum:
2218 Width = Target->getLongAccumWidth();
2219 Align = Target->getLongAccumAlign();
2220 break;
2221 case BuiltinType::ShortFract:
2222 case BuiltinType::UShortFract:
2223 case BuiltinType::SatShortFract:
2224 case BuiltinType::SatUShortFract:
2225 Width = Target->getShortFractWidth();
2226 Align = Target->getShortFractAlign();
2227 break;
2228 case BuiltinType::Fract:
2229 case BuiltinType::UFract:
2230 case BuiltinType::SatFract:
2231 case BuiltinType::SatUFract:
2232 Width = Target->getFractWidth();
2233 Align = Target->getFractAlign();
2234 break;
2235 case BuiltinType::LongFract:
2236 case BuiltinType::ULongFract:
2237 case BuiltinType::SatLongFract:
2238 case BuiltinType::SatULongFract:
2239 Width = Target->getLongFractWidth();
2240 Align = Target->getLongFractAlign();
2241 break;
2242 case BuiltinType::BFloat16:
2243 if (Target->hasBFloat16Type()) {
2244 Width = Target->getBFloat16Width();
2245 Align = Target->getBFloat16Align();
2246 } else if ((getLangOpts().SYCLIsDevice ||
2247 (getLangOpts().OpenMP &&
2248 getLangOpts().OpenMPIsTargetDevice)) &&
2249 AuxTarget->hasBFloat16Type()) {
2250 Width = AuxTarget->getBFloat16Width();
2251 Align = AuxTarget->getBFloat16Align();
2252 }
2253 break;
2254 case BuiltinType::Float16:
2255 case BuiltinType::Half:
2256 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2257 !getLangOpts().OpenMPIsTargetDevice) {
2258 Width = Target->getHalfWidth();
2259 Align = Target->getHalfAlign();
2260 } else {
2261 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2262 "Expected OpenMP device compilation.");
2263 Width = AuxTarget->getHalfWidth();
2264 Align = AuxTarget->getHalfAlign();
2265 }
2266 break;
2267 case BuiltinType::Float:
2268 Width = Target->getFloatWidth();
2269 Align = Target->getFloatAlign();
2270 break;
2271 case BuiltinType::Double:
2272 Width = Target->getDoubleWidth();
2273 Align = Target->getDoubleAlign();
2274 break;
2275 case BuiltinType::Ibm128:
2276 Width = Target->getIbm128Width();
2277 Align = Target->getIbm128Align();
2278 break;
2279 case BuiltinType::LongDouble:
2280 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2281 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2282 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2283 Width = AuxTarget->getLongDoubleWidth();
2284 Align = AuxTarget->getLongDoubleAlign();
2285 } else {
2286 Width = Target->getLongDoubleWidth();
2287 Align = Target->getLongDoubleAlign();
2288 }
2289 break;
2290 case BuiltinType::Float128:
2291 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2292 !getLangOpts().OpenMPIsTargetDevice) {
2293 Width = Target->getFloat128Width();
2294 Align = Target->getFloat128Align();
2295 } else {
2296 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2297 "Expected OpenMP device compilation.");
2298 Width = AuxTarget->getFloat128Width();
2299 Align = AuxTarget->getFloat128Align();
2300 }
2301 break;
2302 case BuiltinType::NullPtr:
2303 // C++ 3.9.1p11: sizeof(nullptr_t) == sizeof(void*)
2304 Width = Target->getPointerWidth(LangAS::Default);
2305 Align = Target->getPointerAlign(LangAS::Default);
2306 break;
2307 case BuiltinType::ObjCId:
2308 case BuiltinType::ObjCClass:
2309 case BuiltinType::ObjCSel:
2310 Width = Target->getPointerWidth(LangAS::Default);
2311 Align = Target->getPointerAlign(LangAS::Default);
2312 break;
2313 case BuiltinType::OCLSampler:
2314 case BuiltinType::OCLEvent:
2315 case BuiltinType::OCLClkEvent:
2316 case BuiltinType::OCLQueue:
2317 case BuiltinType::OCLReserveID:
2318#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2319 case BuiltinType::Id:
2320#include "clang/Basic/OpenCLImageTypes.def"
2321#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2322 case BuiltinType::Id:
2323#include "clang/Basic/OpenCLExtensionTypes.def"
2324 AS = Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
2325 Width = Target->getPointerWidth(AS);
2326 Align = Target->getPointerAlign(AS);
2327 break;
2328 // The SVE types are effectively target-specific. The length of an
2329 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2330 // of 128 bits. There is one predicate bit for each vector byte, so the
2331 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2332 //
2333 // Because the length is only known at runtime, we use a dummy value
2334 // of 0 for the static length. The alignment values are those defined
2335 // by the Procedure Call Standard for the Arm Architecture.
2336#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
2337 case BuiltinType::Id: \
2338 Width = 0; \
2339 Align = 128; \
2340 break;
2341#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
2342 case BuiltinType::Id: \
2343 Width = 0; \
2344 Align = 16; \
2345 break;
2346#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId) \
2347 case BuiltinType::Id: \
2348 Width = 0; \
2349 Align = 16; \
2350 break;
2351#define SVE_SCALAR_TYPE(Name, MangledName, Id, SingletonId, Bits) \
2352 case BuiltinType::Id: \
2353 Width = Bits; \
2354 Align = Bits; \
2355 break;
2356#include "clang/Basic/AArch64ACLETypes.def"
2357#define PPC_VECTOR_TYPE(Name, Id, Size) \
2358 case BuiltinType::Id: \
2359 Width = Size; \
2360 Align = Size; \
2361 break;
2362#include "clang/Basic/PPCTypes.def"
2363#define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \
2364 IsFP, IsBF) \
2365 case BuiltinType::Id: \
2366 Width = 0; \
2367 Align = ElBits; \
2368 break;
2369#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2370 case BuiltinType::Id: \
2371 Width = 0; \
2372 Align = 8; \
2373 break;
2374#include "clang/Basic/RISCVVTypes.def"
2375#define WASM_TYPE(Name, Id, SingletonId) \
2376 case BuiltinType::Id: \
2377 Width = 0; \
2378 Align = 8; \
2379 break;
2380#include "clang/Basic/WebAssemblyReferenceTypes.def"
2381#define AMDGPU_TYPE(NAME, ID, SINGLETONID, WIDTH, ALIGN) \
2382 case BuiltinType::ID: \
2383 Width = WIDTH; \
2384 Align = ALIGN; \
2385 break;
2386#include "clang/Basic/AMDGPUTypes.def"
2387#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2388#include "clang/Basic/HLSLIntangibleTypes.def"
2389 Width = Target->getPointerWidth(LangAS::Default);
2390 Align = Target->getPointerAlign(LangAS::Default);
2391 break;
2392 }
2393 break;
2394 case Type::ObjCObjectPointer:
2395 Width = Target->getPointerWidth(LangAS::Default);
2396 Align = Target->getPointerAlign(LangAS::Default);
2397 break;
2398 case Type::BlockPointer:
2399 AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
2400 Width = Target->getPointerWidth(AS);
2401 Align = Target->getPointerAlign(AS);
2402 break;
2403 case Type::LValueReference:
2404 case Type::RValueReference:
2405 // alignof and sizeof should never enter this code path here, so we go
2406 // the pointer route.
2407 AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
2408 Width = Target->getPointerWidth(AS);
2409 Align = Target->getPointerAlign(AS);
2410 break;
2411 case Type::Pointer:
2412 AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
2413 Width = Target->getPointerWidth(AS);
2414 Align = Target->getPointerAlign(AS);
2415 break;
2416 case Type::MemberPointer: {
2417 const auto *MPT = cast<MemberPointerType>(T);
2418 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2419 Width = MPI.Width;
2420 Align = MPI.Align;
2421 break;
2422 }
2423 case Type::Complex: {
2424 // Complex types have the same alignment as their elements, but twice the
2425 // size.
2426 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2427 Width = EltInfo.Width * 2;
2428 Align = EltInfo.Align;
2429 break;
2430 }
2431 case Type::ObjCObject:
2432 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2433 case Type::Adjusted:
2434 case Type::Decayed:
2435 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2436 case Type::ObjCInterface: {
2437 const auto *ObjCI = cast<ObjCInterfaceType>(T);
2438 if (ObjCI->getDecl()->isInvalidDecl()) {
2439 Width = 8;
2440 Align = 8;
2441 break;
2442 }
2443 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2444 Width = toBits(Layout.getSize());
2445 Align = toBits(Layout.getAlignment());
2446 break;
2447 }
2448 case Type::BitInt: {
2449 const auto *EIT = cast<BitIntType>(T);
2450 Align = Target->getBitIntAlign(EIT->getNumBits());
2451 Width = Target->getBitIntWidth(EIT->getNumBits());
2452 break;
2453 }
2454 case Type::Record:
2455 case Type::Enum: {
2456 const auto *TT = cast<TagType>(T);
2457 const TagDecl *TD = TT->getOriginalDecl()->getDefinitionOrSelf();
2458
2459 if (TD->isInvalidDecl()) {
2460 Width = 8;
2461 Align = 8;
2462 break;
2463 }
2464
2465 if (isa<EnumType>(TT)) {
2466 const EnumDecl *ED = cast<EnumDecl>(TD);
2467 TypeInfo Info =
2469 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2470 Info.Align = AttrAlign;
2472 }
2473 return Info;
2474 }
2475
2476 const auto *RD = cast<RecordDecl>(TD);
2477 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2478 Width = toBits(Layout.getSize());
2479 Align = toBits(Layout.getAlignment());
2480 AlignRequirement = RD->hasAttr<AlignedAttr>()
2482 : AlignRequirementKind::None;
2483 break;
2484 }
2485
2486 case Type::SubstTemplateTypeParm:
2488 getReplacementType().getTypePtr());
2489
2490 case Type::Auto:
2491 case Type::DeducedTemplateSpecialization: {
2492 const auto *A = cast<DeducedType>(T);
2493 assert(!A->getDeducedType().isNull() &&
2494 "cannot request the size of an undeduced or dependent auto type");
2495 return getTypeInfo(A->getDeducedType().getTypePtr());
2496 }
2497
2498 case Type::Paren:
2499 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2500
2501 case Type::MacroQualified:
2502 return getTypeInfo(
2504
2505 case Type::ObjCTypeParam:
2506 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2507
2508 case Type::Using:
2509 return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr());
2510
2511 case Type::Typedef: {
2512 const auto *TT = cast<TypedefType>(T);
2513 TypeInfo Info = getTypeInfo(TT->desugar().getTypePtr());
2514 // If the typedef has an aligned attribute on it, it overrides any computed
2515 // alignment we have. This violates the GCC documentation (which says that
2516 // attribute(aligned) can only round up) but matches its implementation.
2517 if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) {
2518 Align = AttrAlign;
2519 AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2520 } else {
2521 Align = Info.Align;
2522 AlignRequirement = Info.AlignRequirement;
2523 }
2524 Width = Info.Width;
2525 break;
2526 }
2527
2528 case Type::Attributed:
2529 return getTypeInfo(
2530 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2531
2532 case Type::CountAttributed:
2533 return getTypeInfo(cast<CountAttributedType>(T)->desugar().getTypePtr());
2534
2535 case Type::BTFTagAttributed:
2536 return getTypeInfo(
2537 cast<BTFTagAttributedType>(T)->getWrappedType().getTypePtr());
2538
2539 case Type::HLSLAttributedResource:
2540 return getTypeInfo(
2541 cast<HLSLAttributedResourceType>(T)->getWrappedType().getTypePtr());
2542
2543 case Type::HLSLInlineSpirv: {
2544 const auto *ST = cast<HLSLInlineSpirvType>(T);
2545 // Size is specified in bytes, convert to bits
2546 Width = ST->getSize() * 8;
2547 Align = ST->getAlignment();
2548 if (Width == 0 && Align == 0) {
2549 // We are defaulting to laying out opaque SPIR-V types as 32-bit ints.
2550 Width = 32;
2551 Align = 32;
2552 }
2553 break;
2554 }
2555
2556 case Type::Atomic: {
2557 // Start with the base type information.
2558 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2559 Width = Info.Width;
2560 Align = Info.Align;
2561
2562 if (!Width) {
2563 // An otherwise zero-sized type should still generate an
2564 // atomic operation.
2565 Width = Target->getCharWidth();
2566 assert(Align);
2567 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2568 // If the size of the type doesn't exceed the platform's max
2569 // atomic promotion width, make the size and alignment more
2570 // favorable to atomic operations:
2571
2572 // Round the size up to a power of 2.
2573 Width = llvm::bit_ceil(Width);
2574
2575 // Set the alignment equal to the size.
2576 Align = static_cast<unsigned>(Width);
2577 }
2578 }
2579 break;
2580
2581 case Type::PredefinedSugar:
2582 return getTypeInfo(cast<PredefinedSugarType>(T)->desugar().getTypePtr());
2583
2584 case Type::Pipe:
2585 Width = Target->getPointerWidth(LangAS::opencl_global);
2586 Align = Target->getPointerAlign(LangAS::opencl_global);
2587 break;
2588 }
2589
2590 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2591 return TypeInfo(Width, Align, AlignRequirement);
2592}
2593
2595 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2596 if (I != MemoizedUnadjustedAlign.end())
2597 return I->second;
2598
2599 unsigned UnadjustedAlign;
2600 if (const auto *RT = T->getAsCanonical<RecordType>()) {
2601 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getOriginalDecl());
2602 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2603 } else if (const auto *ObjCI = T->getAsCanonical<ObjCInterfaceType>()) {
2604 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2605 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2606 } else {
2607 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2608 }
2609
2610 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2611 return UnadjustedAlign;
2612}
2613
2615 unsigned SimdAlign = llvm::OpenMPIRBuilder::getOpenMPDefaultSimdAlign(
2616 getTargetInfo().getTriple(), Target->getTargetOpts().FeatureMap);
2617 return SimdAlign;
2618}
2619
2620/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2622 return CharUnits::fromQuantity(BitSize / getCharWidth());
2623}
2624
2625/// toBits - Convert a size in characters to a size in characters.
2626int64_t ASTContext::toBits(CharUnits CharSize) const {
2627 return CharSize.getQuantity() * getCharWidth();
2628}
2629
2630/// getTypeSizeInChars - Return the size of the specified type, in characters.
2631/// This method does not work on incomplete types.
2638
2639/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2640/// characters. This method does not work on incomplete types.
2647
2648/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2649/// type, in characters, before alignment adjustments. This method does
2650/// not work on incomplete types.
2657
2658/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2659/// type for the current target in bits. This can be different than the ABI
2660/// alignment in cases where it is beneficial for performance or backwards
2661/// compatibility preserving to overalign a data type. (Note: despite the name,
2662/// the preferred alignment is ABI-impacting, and not an optimization.)
2664 TypeInfo TI = getTypeInfo(T);
2665 unsigned ABIAlign = TI.Align;
2666
2667 T = T->getBaseElementTypeUnsafe();
2668
2669 // The preferred alignment of member pointers is that of a pointer.
2670 if (T->isMemberPointerType())
2671 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2672
2673 if (!Target->allowsLargerPreferedTypeAlignment())
2674 return ABIAlign;
2675
2676 if (const auto *RD = T->getAsRecordDecl()) {
2677 // When used as part of a typedef, or together with a 'packed' attribute,
2678 // the 'aligned' attribute can be used to decrease alignment. Note that the
2679 // 'packed' case is already taken into consideration when computing the
2680 // alignment, we only need to handle the typedef case here.
2682 RD->isInvalidDecl())
2683 return ABIAlign;
2684
2685 unsigned PreferredAlign = static_cast<unsigned>(
2686 toBits(getASTRecordLayout(RD).PreferredAlignment));
2687 assert(PreferredAlign >= ABIAlign &&
2688 "PreferredAlign should be at least as large as ABIAlign.");
2689 return PreferredAlign;
2690 }
2691
2692 // Double (and, for targets supporting AIX `power` alignment, long double) and
2693 // long long should be naturally aligned (despite requiring less alignment) if
2694 // possible.
2695 if (const auto *CT = T->getAs<ComplexType>())
2696 T = CT->getElementType().getTypePtr();
2697 if (const auto *ED = T->getAsEnumDecl())
2698 T = ED->getIntegerType().getTypePtr();
2699 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2700 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2701 T->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2702 (T->isSpecificBuiltinType(BuiltinType::LongDouble) &&
2703 Target->defaultsToAIXPowerAlignment()))
2704 // Don't increase the alignment if an alignment attribute was specified on a
2705 // typedef declaration.
2706 if (!TI.isAlignRequired())
2707 return std::max(ABIAlign, (unsigned)getTypeSize(T));
2708
2709 return ABIAlign;
2710}
2711
2712/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2713/// for __attribute__((aligned)) on this target, to be used if no alignment
2714/// value is specified.
2718
2719/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2720/// to a global variable of the specified type.
2722 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2723 return std::max(getPreferredTypeAlign(T),
2724 getMinGlobalAlignOfVar(TypeSize, VD));
2725}
2726
2727/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2728/// should be given to a global variable of the specified type.
2733
2735 const VarDecl *VD) const {
2736 // Make the default handling as that of a non-weak definition in the
2737 // current translation unit.
2738 bool HasNonWeakDef = !VD || (VD->hasDefinition() && !VD->isWeak());
2739 return getTargetInfo().getMinGlobalAlign(Size, HasNonWeakDef);
2740}
2741
2743 CharUnits Offset = CharUnits::Zero();
2744 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2745 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2746 Offset += Layout->getBaseClassOffset(Base);
2747 Layout = &getASTRecordLayout(Base);
2748 }
2749 return Offset;
2750}
2751
2753 const ValueDecl *MPD = MP.getMemberPointerDecl();
2756 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2758 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2759 const CXXRecordDecl *Base = RD;
2760 const CXXRecordDecl *Derived = Path[I];
2761 if (DerivedMember)
2762 std::swap(Base, Derived);
2764 RD = Path[I];
2765 }
2766 if (DerivedMember)
2768 return ThisAdjustment;
2769}
2770
2771/// DeepCollectObjCIvars -
2772/// This routine first collects all declared, but not synthesized, ivars in
2773/// super class and then collects all ivars, including those synthesized for
2774/// current class. This routine is used for implementation of current class
2775/// when all ivars, declared and synthesized are known.
2777 bool leafClass,
2779 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2780 DeepCollectObjCIvars(SuperClass, false, Ivars);
2781 if (!leafClass) {
2782 llvm::append_range(Ivars, OI->ivars());
2783 } else {
2784 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2785 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2786 Iv= Iv->getNextIvar())
2787 Ivars.push_back(Iv);
2788 }
2789}
2790
2791/// CollectInheritedProtocols - Collect all protocols in current class and
2792/// those inherited by it.
2795 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2796 // We can use protocol_iterator here instead of
2797 // all_referenced_protocol_iterator since we are walking all categories.
2798 for (auto *Proto : OI->all_referenced_protocols()) {
2799 CollectInheritedProtocols(Proto, Protocols);
2800 }
2801
2802 // Categories of this Interface.
2803 for (const auto *Cat : OI->visible_categories())
2804 CollectInheritedProtocols(Cat, Protocols);
2805
2806 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2807 while (SD) {
2808 CollectInheritedProtocols(SD, Protocols);
2809 SD = SD->getSuperClass();
2810 }
2811 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2812 for (auto *Proto : OC->protocols()) {
2813 CollectInheritedProtocols(Proto, Protocols);
2814 }
2815 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2816 // Insert the protocol.
2817 if (!Protocols.insert(
2818 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2819 return;
2820
2821 for (auto *Proto : OP->protocols())
2822 CollectInheritedProtocols(Proto, Protocols);
2823 }
2824}
2825
2827 const RecordDecl *RD,
2828 bool CheckIfTriviallyCopyable) {
2829 assert(RD->isUnion() && "Must be union type");
2830 CharUnits UnionSize =
2831 Context.getTypeSizeInChars(Context.getCanonicalTagType(RD));
2832
2833 for (const auto *Field : RD->fields()) {
2834 if (!Context.hasUniqueObjectRepresentations(Field->getType(),
2835 CheckIfTriviallyCopyable))
2836 return false;
2837 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2838 if (FieldSize != UnionSize)
2839 return false;
2840 }
2841 return !RD->field_empty();
2842}
2843
2844static int64_t getSubobjectOffset(const FieldDecl *Field,
2845 const ASTContext &Context,
2846 const clang::ASTRecordLayout & /*Layout*/) {
2847 return Context.getFieldOffset(Field);
2848}
2849
2850static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
2851 const ASTContext &Context,
2852 const clang::ASTRecordLayout &Layout) {
2853 return Context.toBits(Layout.getBaseClassOffset(RD));
2854}
2855
2856static std::optional<int64_t>
2858 const RecordDecl *RD,
2859 bool CheckIfTriviallyCopyable);
2860
2861static std::optional<int64_t>
2862getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context,
2863 bool CheckIfTriviallyCopyable) {
2864 if (const auto *RD = Field->getType()->getAsRecordDecl();
2865 RD && !RD->isUnion())
2866 return structHasUniqueObjectRepresentations(Context, RD,
2867 CheckIfTriviallyCopyable);
2868
2869 // A _BitInt type may not be unique if it has padding bits
2870 // but if it is a bitfield the padding bits are not used.
2871 bool IsBitIntType = Field->getType()->isBitIntType();
2872 if (!Field->getType()->isReferenceType() && !IsBitIntType &&
2873 !Context.hasUniqueObjectRepresentations(Field->getType(),
2874 CheckIfTriviallyCopyable))
2875 return std::nullopt;
2876
2877 int64_t FieldSizeInBits =
2878 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2879 if (Field->isBitField()) {
2880 // If we have explicit padding bits, they don't contribute bits
2881 // to the actual object representation, so return 0.
2882 if (Field->isUnnamedBitField())
2883 return 0;
2884
2885 int64_t BitfieldSize = Field->getBitWidthValue();
2886 if (IsBitIntType) {
2887 if ((unsigned)BitfieldSize >
2888 cast<BitIntType>(Field->getType())->getNumBits())
2889 return std::nullopt;
2890 } else if (BitfieldSize > FieldSizeInBits) {
2891 return std::nullopt;
2892 }
2893 FieldSizeInBits = BitfieldSize;
2894 } else if (IsBitIntType && !Context.hasUniqueObjectRepresentations(
2895 Field->getType(), CheckIfTriviallyCopyable)) {
2896 return std::nullopt;
2897 }
2898 return FieldSizeInBits;
2899}
2900
2901static std::optional<int64_t>
2903 bool CheckIfTriviallyCopyable) {
2904 return structHasUniqueObjectRepresentations(Context, RD,
2905 CheckIfTriviallyCopyable);
2906}
2907
2908template <typename RangeT>
2910 const RangeT &Subobjects, int64_t CurOffsetInBits,
2911 const ASTContext &Context, const clang::ASTRecordLayout &Layout,
2912 bool CheckIfTriviallyCopyable) {
2913 for (const auto *Subobject : Subobjects) {
2914 std::optional<int64_t> SizeInBits =
2915 getSubobjectSizeInBits(Subobject, Context, CheckIfTriviallyCopyable);
2916 if (!SizeInBits)
2917 return std::nullopt;
2918 if (*SizeInBits != 0) {
2919 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
2920 if (Offset != CurOffsetInBits)
2921 return std::nullopt;
2922 CurOffsetInBits += *SizeInBits;
2923 }
2924 }
2925 return CurOffsetInBits;
2926}
2927
2928static std::optional<int64_t>
2930 const RecordDecl *RD,
2931 bool CheckIfTriviallyCopyable) {
2932 assert(!RD->isUnion() && "Must be struct/class type");
2933 const auto &Layout = Context.getASTRecordLayout(RD);
2934
2935 int64_t CurOffsetInBits = 0;
2936 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2937 if (ClassDecl->isDynamicClass())
2938 return std::nullopt;
2939
2941 for (const auto &Base : ClassDecl->bases()) {
2942 // Empty types can be inherited from, and non-empty types can potentially
2943 // have tail padding, so just make sure there isn't an error.
2944 Bases.emplace_back(Base.getType()->getAsCXXRecordDecl());
2945 }
2946
2947 llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
2948 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
2949 });
2950
2951 std::optional<int64_t> OffsetAfterBases =
2953 Bases, CurOffsetInBits, Context, Layout, CheckIfTriviallyCopyable);
2954 if (!OffsetAfterBases)
2955 return std::nullopt;
2956 CurOffsetInBits = *OffsetAfterBases;
2957 }
2958
2959 std::optional<int64_t> OffsetAfterFields =
2961 RD->fields(), CurOffsetInBits, Context, Layout,
2962 CheckIfTriviallyCopyable);
2963 if (!OffsetAfterFields)
2964 return std::nullopt;
2965 CurOffsetInBits = *OffsetAfterFields;
2966
2967 return CurOffsetInBits;
2968}
2969
2971 QualType Ty, bool CheckIfTriviallyCopyable) const {
2972 // C++17 [meta.unary.prop]:
2973 // The predicate condition for a template specialization
2974 // has_unique_object_representations<T> shall be satisfied if and only if:
2975 // (9.1) - T is trivially copyable, and
2976 // (9.2) - any two objects of type T with the same value have the same
2977 // object representation, where:
2978 // - two objects of array or non-union class type are considered to have
2979 // the same value if their respective sequences of direct subobjects
2980 // have the same values, and
2981 // - two objects of union type are considered to have the same value if
2982 // they have the same active member and the corresponding members have
2983 // the same value.
2984 // The set of scalar types for which this condition holds is
2985 // implementation-defined. [ Note: If a type has padding bits, the condition
2986 // does not hold; otherwise, the condition holds true for unsigned integral
2987 // types. -- end note ]
2988 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2989
2990 // Arrays are unique only if their element type is unique.
2991 if (Ty->isArrayType())
2993 CheckIfTriviallyCopyable);
2994
2995 assert((Ty->isVoidType() || !Ty->isIncompleteType()) &&
2996 "hasUniqueObjectRepresentations should not be called with an "
2997 "incomplete type");
2998
2999 // (9.1) - T is trivially copyable...
3000 if (CheckIfTriviallyCopyable && !Ty.isTriviallyCopyableType(*this))
3001 return false;
3002
3003 // All integrals and enums are unique.
3004 if (Ty->isIntegralOrEnumerationType()) {
3005 // Address discriminated integer types are not unique.
3007 return false;
3008 // Except _BitInt types that have padding bits.
3009 if (const auto *BIT = Ty->getAs<BitIntType>())
3010 return getTypeSize(BIT) == BIT->getNumBits();
3011
3012 return true;
3013 }
3014
3015 // All other pointers are unique.
3016 if (Ty->isPointerType())
3018
3019 if (const auto *MPT = Ty->getAs<MemberPointerType>())
3020 return !ABI->getMemberPointerInfo(MPT).HasPadding;
3021
3022 if (const auto *Record = Ty->getAsRecordDecl()) {
3023 if (Record->isInvalidDecl())
3024 return false;
3025
3026 if (Record->isUnion())
3028 CheckIfTriviallyCopyable);
3029
3030 std::optional<int64_t> StructSize = structHasUniqueObjectRepresentations(
3031 *this, Record, CheckIfTriviallyCopyable);
3032
3033 return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(Ty));
3034 }
3035
3036 // FIXME: More cases to handle here (list by rsmith):
3037 // vectors (careful about, eg, vector of 3 foo)
3038 // _Complex int and friends
3039 // _Atomic T
3040 // Obj-C block pointers
3041 // Obj-C object pointers
3042 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
3043 // clk_event_t, queue_t, reserve_id_t)
3044 // There're also Obj-C class types and the Obj-C selector type, but I think it
3045 // makes sense for those to return false here.
3046
3047 return false;
3048}
3049
3051 unsigned count = 0;
3052 // Count ivars declared in class extension.
3053 for (const auto *Ext : OI->known_extensions())
3054 count += Ext->ivar_size();
3055
3056 // Count ivar defined in this class's implementation. This
3057 // includes synthesized ivars.
3058 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
3059 count += ImplDecl->ivar_size();
3060
3061 return count;
3062}
3063
3065 if (!E)
3066 return false;
3067
3068 // nullptr_t is always treated as null.
3069 if (E->getType()->isNullPtrType()) return true;
3070
3071 if (E->getType()->isAnyPointerType() &&
3074 return true;
3075
3076 // Unfortunately, __null has type 'int'.
3077 if (isa<GNUNullExpr>(E)) return true;
3078
3079 return false;
3080}
3081
3082/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
3083/// exists.
3085 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3086 I = ObjCImpls.find(D);
3087 if (I != ObjCImpls.end())
3088 return cast<ObjCImplementationDecl>(I->second);
3089 return nullptr;
3090}
3091
3092/// Get the implementation of ObjCCategoryDecl, or nullptr if none
3093/// exists.
3095 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3096 I = ObjCImpls.find(D);
3097 if (I != ObjCImpls.end())
3098 return cast<ObjCCategoryImplDecl>(I->second);
3099 return nullptr;
3100}
3101
3102/// Set the implementation of ObjCInterfaceDecl.
3104 ObjCImplementationDecl *ImplD) {
3105 assert(IFaceD && ImplD && "Passed null params");
3106 ObjCImpls[IFaceD] = ImplD;
3107}
3108
3109/// Set the implementation of ObjCCategoryDecl.
3111 ObjCCategoryImplDecl *ImplD) {
3112 assert(CatD && ImplD && "Passed null params");
3113 ObjCImpls[CatD] = ImplD;
3114}
3115
3116const ObjCMethodDecl *
3118 return ObjCMethodRedecls.lookup(MD);
3119}
3120
3122 const ObjCMethodDecl *Redecl) {
3123 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
3124 ObjCMethodRedecls[MD] = Redecl;
3125}
3126
3128 const NamedDecl *ND) const {
3129 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
3130 return ID;
3131 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
3132 return CD->getClassInterface();
3133 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
3134 return IMD->getClassInterface();
3135
3136 return nullptr;
3137}
3138
3139/// Get the copy initialization expression of VarDecl, or nullptr if
3140/// none exists.
3142 assert(VD && "Passed null params");
3143 assert(VD->hasAttr<BlocksAttr>() &&
3144 "getBlockVarCopyInits - not __block var");
3145 auto I = BlockVarCopyInits.find(VD);
3146 if (I != BlockVarCopyInits.end())
3147 return I->second;
3148 return {nullptr, false};
3149}
3150
3151/// Set the copy initialization expression of a block var decl.
3153 bool CanThrow) {
3154 assert(VD && CopyExpr && "Passed null params");
3155 assert(VD->hasAttr<BlocksAttr>() &&
3156 "setBlockVarCopyInits - not __block var");
3157 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
3158}
3159
3161 unsigned DataSize) const {
3162 if (!DataSize)
3164 else
3165 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
3166 "incorrect data size provided to CreateTypeSourceInfo!");
3167
3168 auto *TInfo =
3169 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
3170 new (TInfo) TypeSourceInfo(T, DataSize);
3171 return TInfo;
3172}
3173
3175 SourceLocation L) const {
3177 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
3178 return DI;
3179}
3180
3181const ASTRecordLayout &
3183 return getObjCLayout(D);
3184}
3185
3188 bool &AnyNonCanonArgs) {
3189 SmallVector<TemplateArgument, 16> CanonArgs(Args);
3190 AnyNonCanonArgs |= C.canonicalizeTemplateArguments(CanonArgs);
3191 return CanonArgs;
3192}
3193
3196 bool AnyNonCanonArgs = false;
3197 for (auto &Arg : Args) {
3198 TemplateArgument OrigArg = Arg;
3200 AnyNonCanonArgs |= !Arg.structurallyEquals(OrigArg);
3201 }
3202 return AnyNonCanonArgs;
3203}
3204
3205//===----------------------------------------------------------------------===//
3206// Type creation/memoization methods
3207//===----------------------------------------------------------------------===//
3208
3210ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
3211 unsigned fastQuals = quals.getFastQualifiers();
3212 quals.removeFastQualifiers();
3213
3214 // Check if we've already instantiated this type.
3215 llvm::FoldingSetNodeID ID;
3216 ExtQuals::Profile(ID, baseType, quals);
3217 void *insertPos = nullptr;
3218 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
3219 assert(eq->getQualifiers() == quals);
3220 return QualType(eq, fastQuals);
3221 }
3222
3223 // If the base type is not canonical, make the appropriate canonical type.
3224 QualType canon;
3225 if (!baseType->isCanonicalUnqualified()) {
3226 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
3227 canonSplit.Quals.addConsistentQualifiers(quals);
3228 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
3229
3230 // Re-find the insert position.
3231 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
3232 }
3233
3234 auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
3235 ExtQualNodes.InsertNode(eq, insertPos);
3236 return QualType(eq, fastQuals);
3237}
3238
3240 LangAS AddressSpace) const {
3241 QualType CanT = getCanonicalType(T);
3242 if (CanT.getAddressSpace() == AddressSpace)
3243 return T;
3244
3245 // If we are composing extended qualifiers together, merge together
3246 // into one ExtQuals node.
3247 QualifierCollector Quals;
3248 const Type *TypeNode = Quals.strip(T);
3249
3250 // If this type already has an address space specified, it cannot get
3251 // another one.
3252 assert(!Quals.hasAddressSpace() &&
3253 "Type cannot be in multiple addr spaces!");
3254 Quals.addAddressSpace(AddressSpace);
3255
3256 return getExtQualType(TypeNode, Quals);
3257}
3258
3260 // If the type is not qualified with an address space, just return it
3261 // immediately.
3262 if (!T.hasAddressSpace())
3263 return T;
3264
3265 QualifierCollector Quals;
3266 const Type *TypeNode;
3267 // For arrays, strip the qualifier off the element type, then reconstruct the
3268 // array type
3269 if (T.getTypePtr()->isArrayType()) {
3270 T = getUnqualifiedArrayType(T, Quals);
3271 TypeNode = T.getTypePtr();
3272 } else {
3273 // If we are composing extended qualifiers together, merge together
3274 // into one ExtQuals node.
3275 while (T.hasAddressSpace()) {
3276 TypeNode = Quals.strip(T);
3277
3278 // If the type no longer has an address space after stripping qualifiers,
3279 // jump out.
3280 if (!QualType(TypeNode, 0).hasAddressSpace())
3281 break;
3282
3283 // There might be sugar in the way. Strip it and try again.
3284 T = T.getSingleStepDesugaredType(*this);
3285 }
3286 }
3287
3288 Quals.removeAddressSpace();
3289
3290 // Removal of the address space can mean there are no longer any
3291 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3292 // or required.
3293 if (Quals.hasNonFastQualifiers())
3294 return getExtQualType(TypeNode, Quals);
3295 else
3296 return QualType(TypeNode, Quals.getFastQualifiers());
3297}
3298
3299uint16_t
3301 assert(RD->isPolymorphic() &&
3302 "Attempted to get vtable pointer discriminator on a monomorphic type");
3303 std::unique_ptr<MangleContext> MC(createMangleContext());
3304 SmallString<256> Str;
3305 llvm::raw_svector_ostream Out(Str);
3306 MC->mangleCXXVTable(RD, Out);
3307 return llvm::getPointerAuthStableSipHash(Str);
3308}
3309
3310/// Encode a function type for use in the discriminator of a function pointer
3311/// type. We can't use the itanium scheme for this since C has quite permissive
3312/// rules for type compatibility that we need to be compatible with.
3313///
3314/// Formally, this function associates every function pointer type T with an
3315/// encoded string E(T). Let the equivalence relation T1 ~ T2 be defined as
3316/// E(T1) == E(T2). E(T) is part of the ABI of values of type T. C type
3317/// compatibility requires equivalent treatment under the ABI, so
3318/// CCompatible(T1, T2) must imply E(T1) == E(T2), that is, CCompatible must be
3319/// a subset of ~. Crucially, however, it must be a proper subset because
3320/// CCompatible is not an equivalence relation: for example, int[] is compatible
3321/// with both int[1] and int[2], but the latter are not compatible with each
3322/// other. Therefore this encoding function must be careful to only distinguish
3323/// types if there is no third type with which they are both required to be
3324/// compatible.
3326 raw_ostream &OS, QualType QT) {
3327 // FIXME: Consider address space qualifiers.
3328 const Type *T = QT.getCanonicalType().getTypePtr();
3329
3330 // FIXME: Consider using the C++ type mangling when we encounter a construct
3331 // that is incompatible with C.
3332
3333 switch (T->getTypeClass()) {
3334 case Type::Atomic:
3336 Ctx, OS, cast<AtomicType>(T)->getValueType());
3337
3338 case Type::LValueReference:
3339 OS << "R";
3342 return;
3343 case Type::RValueReference:
3344 OS << "O";
3347 return;
3348
3349 case Type::Pointer:
3350 // C11 6.7.6.1p2:
3351 // For two pointer types to be compatible, both shall be identically
3352 // qualified and both shall be pointers to compatible types.
3353 // FIXME: we should also consider pointee types.
3354 OS << "P";
3355 return;
3356
3357 case Type::ObjCObjectPointer:
3358 case Type::BlockPointer:
3359 OS << "P";
3360 return;
3361
3362 case Type::Complex:
3363 OS << "C";
3365 Ctx, OS, cast<ComplexType>(T)->getElementType());
3366
3367 case Type::VariableArray:
3368 case Type::ConstantArray:
3369 case Type::IncompleteArray:
3370 case Type::ArrayParameter:
3371 // C11 6.7.6.2p6:
3372 // For two array types to be compatible, both shall have compatible
3373 // element types, and if both size specifiers are present, and are integer
3374 // constant expressions, then both size specifiers shall have the same
3375 // constant value [...]
3376 //
3377 // So since ElemType[N] has to be compatible ElemType[], we can't encode the
3378 // width of the array.
3379 OS << "A";
3381 Ctx, OS, cast<ArrayType>(T)->getElementType());
3382
3383 case Type::ObjCInterface:
3384 case Type::ObjCObject:
3385 OS << "<objc_object>";
3386 return;
3387
3388 case Type::Enum: {
3389 // C11 6.7.2.2p4:
3390 // Each enumerated type shall be compatible with char, a signed integer
3391 // type, or an unsigned integer type.
3392 //
3393 // So we have to treat enum types as integers.
3394 QualType UnderlyingType = T->castAsEnumDecl()->getIntegerType();
3396 Ctx, OS, UnderlyingType.isNull() ? Ctx.IntTy : UnderlyingType);
3397 }
3398
3399 case Type::FunctionNoProto:
3400 case Type::FunctionProto: {
3401 // C11 6.7.6.3p15:
3402 // For two function types to be compatible, both shall specify compatible
3403 // return types. Moreover, the parameter type lists, if both are present,
3404 // shall agree in the number of parameters and in the use of the ellipsis
3405 // terminator; corresponding parameters shall have compatible types.
3406 //
3407 // That paragraph goes on to describe how unprototyped functions are to be
3408 // handled, which we ignore here. Unprototyped function pointers are hashed
3409 // as though they were prototyped nullary functions since thats probably
3410 // what the user meant. This behavior is non-conforming.
3411 // FIXME: If we add a "custom discriminator" function type attribute we
3412 // should encode functions as their discriminators.
3413 OS << "F";
3414 const auto *FuncType = cast<FunctionType>(T);
3415 encodeTypeForFunctionPointerAuth(Ctx, OS, FuncType->getReturnType());
3416 if (const auto *FPT = dyn_cast<FunctionProtoType>(FuncType)) {
3417 for (QualType Param : FPT->param_types()) {
3418 Param = Ctx.getSignatureParameterType(Param);
3419 encodeTypeForFunctionPointerAuth(Ctx, OS, Param);
3420 }
3421 if (FPT->isVariadic())
3422 OS << "z";
3423 }
3424 OS << "E";
3425 return;
3426 }
3427
3428 case Type::MemberPointer: {
3429 OS << "M";
3430 const auto *MPT = T->castAs<MemberPointerType>();
3432 Ctx, OS, QualType(MPT->getQualifier().getAsType(), 0));
3433 encodeTypeForFunctionPointerAuth(Ctx, OS, MPT->getPointeeType());
3434 return;
3435 }
3436 case Type::ExtVector:
3437 case Type::Vector:
3438 OS << "Dv" << Ctx.getTypeSizeInChars(T).getQuantity();
3439 break;
3440
3441 // Don't bother discriminating based on these types.
3442 case Type::Pipe:
3443 case Type::BitInt:
3444 case Type::ConstantMatrix:
3445 OS << "?";
3446 return;
3447
3448 case Type::Builtin: {
3449 const auto *BTy = T->castAs<BuiltinType>();
3450 switch (BTy->getKind()) {
3451#define SIGNED_TYPE(Id, SingletonId) \
3452 case BuiltinType::Id: \
3453 OS << "i"; \
3454 return;
3455#define UNSIGNED_TYPE(Id, SingletonId) \
3456 case BuiltinType::Id: \
3457 OS << "i"; \
3458 return;
3459#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
3460#define BUILTIN_TYPE(Id, SingletonId)
3461#include "clang/AST/BuiltinTypes.def"
3462 llvm_unreachable("placeholder types should not appear here.");
3463
3464 case BuiltinType::Half:
3465 OS << "Dh";
3466 return;
3467 case BuiltinType::Float:
3468 OS << "f";
3469 return;
3470 case BuiltinType::Double:
3471 OS << "d";
3472 return;
3473 case BuiltinType::LongDouble:
3474 OS << "e";
3475 return;
3476 case BuiltinType::Float16:
3477 OS << "DF16_";
3478 return;
3479 case BuiltinType::Float128:
3480 OS << "g";
3481 return;
3482
3483 case BuiltinType::Void:
3484 OS << "v";
3485 return;
3486
3487 case BuiltinType::ObjCId:
3488 case BuiltinType::ObjCClass:
3489 case BuiltinType::ObjCSel:
3490 case BuiltinType::NullPtr:
3491 OS << "P";
3492 return;
3493
3494 // Don't bother discriminating based on OpenCL types.
3495 case BuiltinType::OCLSampler:
3496 case BuiltinType::OCLEvent:
3497 case BuiltinType::OCLClkEvent:
3498 case BuiltinType::OCLQueue:
3499 case BuiltinType::OCLReserveID:
3500 case BuiltinType::BFloat16:
3501 case BuiltinType::VectorQuad:
3502 case BuiltinType::VectorPair:
3503 case BuiltinType::DMR1024:
3504 OS << "?";
3505 return;
3506
3507 // Don't bother discriminating based on these seldom-used types.
3508 case BuiltinType::Ibm128:
3509 return;
3510#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3511 case BuiltinType::Id: \
3512 return;
3513#include "clang/Basic/OpenCLImageTypes.def"
3514#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3515 case BuiltinType::Id: \
3516 return;
3517#include "clang/Basic/OpenCLExtensionTypes.def"
3518#define SVE_TYPE(Name, Id, SingletonId) \
3519 case BuiltinType::Id: \
3520 return;
3521#include "clang/Basic/AArch64ACLETypes.def"
3522#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3523 case BuiltinType::Id: \
3524 return;
3525#include "clang/Basic/HLSLIntangibleTypes.def"
3526 case BuiltinType::Dependent:
3527 llvm_unreachable("should never get here");
3528#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
3529#include "clang/Basic/AMDGPUTypes.def"
3530 case BuiltinType::WasmExternRef:
3531#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3532#include "clang/Basic/RISCVVTypes.def"
3533 llvm_unreachable("not yet implemented");
3534 }
3535 llvm_unreachable("should never get here");
3536 }
3537 case Type::Record: {
3538 const RecordDecl *RD = T->castAsCanonical<RecordType>()->getOriginalDecl();
3539 const IdentifierInfo *II = RD->getIdentifier();
3540
3541 // In C++, an immediate typedef of an anonymous struct or union
3542 // is considered to name it for ODR purposes, but C's specification
3543 // of type compatibility does not have a similar rule. Using the typedef
3544 // name in function type discriminators anyway, as we do here,
3545 // therefore technically violates the C standard: two function pointer
3546 // types defined in terms of two typedef'd anonymous structs with
3547 // different names are formally still compatible, but we are assigning
3548 // them different discriminators and therefore incompatible ABIs.
3549 //
3550 // This is a relatively minor violation that significantly improves
3551 // discrimination in some cases and has not caused problems in
3552 // practice. Regardless, it is now part of the ABI in places where
3553 // function type discrimination is used, and it can no longer be
3554 // changed except on new platforms.
3555
3556 if (!II)
3557 if (const TypedefNameDecl *Typedef = RD->getTypedefNameForAnonDecl())
3558 II = Typedef->getDeclName().getAsIdentifierInfo();
3559
3560 if (!II) {
3561 OS << "<anonymous_record>";
3562 return;
3563 }
3564 OS << II->getLength() << II->getName();
3565 return;
3566 }
3567 case Type::HLSLAttributedResource:
3568 case Type::HLSLInlineSpirv:
3569 llvm_unreachable("should never get here");
3570 break;
3571 case Type::DeducedTemplateSpecialization:
3572 case Type::Auto:
3573#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3574#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3575#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3576#define ABSTRACT_TYPE(Class, Base)
3577#define TYPE(Class, Base)
3578#include "clang/AST/TypeNodes.inc"
3579 llvm_unreachable("unexpected non-canonical or dependent type!");
3580 return;
3581 }
3582}
3583
3585 assert(!T->isDependentType() &&
3586 "cannot compute type discriminator of a dependent type");
3587
3588 SmallString<256> Str;
3589 llvm::raw_svector_ostream Out(Str);
3590
3591 if (T->isFunctionPointerType() || T->isFunctionReferenceType())
3592 T = T->getPointeeType();
3593
3594 if (T->isFunctionType()) {
3596 } else {
3597 T = T.getUnqualifiedType();
3598 // Calls to member function pointers don't need to worry about
3599 // language interop or the laxness of the C type compatibility rules.
3600 // We just mangle the member pointer type directly, which is
3601 // implicitly much stricter about type matching. However, we do
3602 // strip any top-level exception specification before this mangling.
3603 // C++23 requires calls to work when the function type is convertible
3604 // to the pointer type by a function pointer conversion, which can
3605 // change the exception specification. This does not technically
3606 // require the exception specification to not affect representation,
3607 // because the function pointer conversion is still always a direct
3608 // value conversion and therefore an opportunity to resign the
3609 // pointer. (This is in contrast to e.g. qualification conversions,
3610 // which can be applied in nested pointer positions, effectively
3611 // requiring qualified and unqualified representations to match.)
3612 // However, it is pragmatic to ignore exception specifications
3613 // because it allows a certain amount of `noexcept` mismatching
3614 // to not become a visible ODR problem. This also leaves some
3615 // room for the committee to add laxness to function pointer
3616 // conversions in future standards.
3617 if (auto *MPT = T->getAs<MemberPointerType>())
3618 if (MPT->isMemberFunctionPointer()) {
3619 QualType PointeeType = MPT->getPointeeType();
3620 if (PointeeType->castAs<FunctionProtoType>()->getExceptionSpecType() !=
3621 EST_None) {
3623 T = getMemberPointerType(FT, MPT->getQualifier(),
3624 MPT->getMostRecentCXXRecordDecl());
3625 }
3626 }
3627 std::unique_ptr<MangleContext> MC(createMangleContext());
3628 MC->mangleCanonicalTypeName(T, Out);
3629 }
3630
3631 return llvm::getPointerAuthStableSipHash(Str);
3632}
3633
3635 Qualifiers::GC GCAttr) const {
3636 QualType CanT = getCanonicalType(T);
3637 if (CanT.getObjCGCAttr() == GCAttr)
3638 return T;
3639
3640 if (const auto *ptr = T->getAs<PointerType>()) {
3641 QualType Pointee = ptr->getPointeeType();
3642 if (Pointee->isAnyPointerType()) {
3643 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
3644 return getPointerType(ResultType);
3645 }
3646 }
3647
3648 // If we are composing extended qualifiers together, merge together
3649 // into one ExtQuals node.
3650 QualifierCollector Quals;
3651 const Type *TypeNode = Quals.strip(T);
3652
3653 // If this type already has an ObjCGC specified, it cannot get
3654 // another one.
3655 assert(!Quals.hasObjCGCAttr() &&
3656 "Type cannot have multiple ObjCGCs!");
3657 Quals.addObjCGCAttr(GCAttr);
3658
3659 return getExtQualType(TypeNode, Quals);
3660}
3661
3663 if (const PointerType *Ptr = T->getAs<PointerType>()) {
3664 QualType Pointee = Ptr->getPointeeType();
3665 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
3666 return getPointerType(removeAddrSpaceQualType(Pointee));
3667 }
3668 }
3669 return T;
3670}
3671
3673 QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull,
3674 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3675 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3676
3677 llvm::FoldingSetNodeID ID;
3678 CountAttributedType::Profile(ID, WrappedTy, CountExpr, CountInBytes, OrNull);
3679
3680 void *InsertPos = nullptr;
3681 CountAttributedType *CATy =
3682 CountAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
3683 if (CATy)
3684 return QualType(CATy, 0);
3685
3686 QualType CanonTy = getCanonicalType(WrappedTy);
3687 size_t Size = CountAttributedType::totalSizeToAlloc<TypeCoupledDeclRefInfo>(
3688 DependentDecls.size());
3690 new (CATy) CountAttributedType(WrappedTy, CanonTy, CountExpr, CountInBytes,
3691 OrNull, DependentDecls);
3692 Types.push_back(CATy);
3693 CountAttributedTypes.InsertNode(CATy, InsertPos);
3694
3695 return QualType(CATy, 0);
3696}
3697
3700 llvm::function_ref<QualType(QualType)> Adjust) const {
3701 switch (Orig->getTypeClass()) {
3702 case Type::Attributed: {
3703 const auto *AT = cast<AttributedType>(Orig);
3704 return getAttributedType(AT->getAttrKind(),
3705 adjustType(AT->getModifiedType(), Adjust),
3706 adjustType(AT->getEquivalentType(), Adjust),
3707 AT->getAttr());
3708 }
3709
3710 case Type::BTFTagAttributed: {
3711 const auto *BTFT = dyn_cast<BTFTagAttributedType>(Orig);
3712 return getBTFTagAttributedType(BTFT->getAttr(),
3713 adjustType(BTFT->getWrappedType(), Adjust));
3714 }
3715
3716 case Type::Paren:
3717 return getParenType(
3718 adjustType(cast<ParenType>(Orig)->getInnerType(), Adjust));
3719
3720 case Type::Adjusted: {
3721 const auto *AT = cast<AdjustedType>(Orig);
3722 return getAdjustedType(AT->getOriginalType(),
3723 adjustType(AT->getAdjustedType(), Adjust));
3724 }
3725
3726 case Type::MacroQualified: {
3727 const auto *MQT = cast<MacroQualifiedType>(Orig);
3728 return getMacroQualifiedType(adjustType(MQT->getUnderlyingType(), Adjust),
3729 MQT->getMacroIdentifier());
3730 }
3731
3732 default:
3733 return Adjust(Orig);
3734 }
3735}
3736
3738 FunctionType::ExtInfo Info) {
3739 if (T->getExtInfo() == Info)
3740 return T;
3741
3743 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
3744 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
3745 } else {
3746 const auto *FPT = cast<FunctionProtoType>(T);
3747 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3748 EPI.ExtInfo = Info;
3749 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
3750 }
3751
3752 return cast<FunctionType>(Result.getTypePtr());
3753}
3754
3756 QualType ResultType) {
3757 return adjustType(FunctionType, [&](QualType Orig) {
3758 if (const auto *FNPT = Orig->getAs<FunctionNoProtoType>())
3759 return getFunctionNoProtoType(ResultType, FNPT->getExtInfo());
3760
3761 const auto *FPT = Orig->castAs<FunctionProtoType>();
3762 return getFunctionType(ResultType, FPT->getParamTypes(),
3763 FPT->getExtProtoInfo());
3764 });
3765}
3766
3768 QualType ResultType) {
3769 FD = FD->getMostRecentDecl();
3770 while (true) {
3771 FD->setType(adjustFunctionResultType(FD->getType(), ResultType));
3772 if (FunctionDecl *Next = FD->getPreviousDecl())
3773 FD = Next;
3774 else
3775 break;
3776 }
3778 L->DeducedReturnType(FD, ResultType);
3779}
3780
3781/// Get a function type and produce the equivalent function type with the
3782/// specified exception specification. Type sugar that can be present on a
3783/// declaration of a function with an exception specification is permitted
3784/// and preserved. Other type sugar (for instance, typedefs) is not.
3786 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
3787 return adjustType(Orig, [&](QualType Ty) {
3788 const auto *Proto = Ty->castAs<FunctionProtoType>();
3789 return getFunctionType(Proto->getReturnType(), Proto->getParamTypes(),
3790 Proto->getExtProtoInfo().withExceptionSpec(ESI));
3791 });
3792}
3793
3801
3803 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3804 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3805 SmallVector<QualType, 16> Args(Proto->param_types().size());
3806 for (unsigned i = 0, n = Args.size(); i != n; ++i)
3807 Args[i] = removePtrSizeAddrSpace(Proto->param_types()[i]);
3808 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3809 }
3810
3811 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3812 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3813 return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3814 }
3815
3816 return T;
3817}
3818
3824
3826 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3827 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3828 EPI.ExtParameterInfos = nullptr;
3829 return getFunctionType(Proto->getReturnType(), Proto->param_types(), EPI);
3830 }
3831 return T;
3832}
3833
3839
3842 bool AsWritten) {
3843 // Update the type.
3844 QualType Updated =
3846 FD->setType(Updated);
3847
3848 if (!AsWritten)
3849 return;
3850
3851 // Update the type in the type source information too.
3852 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3853 // If the type and the type-as-written differ, we may need to update
3854 // the type-as-written too.
3855 if (TSInfo->getType() != FD->getType())
3856 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
3857
3858 // FIXME: When we get proper type location information for exceptions,
3859 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3860 // up the TypeSourceInfo;
3861 assert(TypeLoc::getFullDataSizeForType(Updated) ==
3862 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3863 "TypeLoc size mismatch from updating exception specification");
3864 TSInfo->overrideType(Updated);
3865 }
3866}
3867
3868/// getComplexType - Return the uniqued reference to the type for a complex
3869/// number with the specified element type.
3871 // Unique pointers, to guarantee there is only one pointer of a particular
3872 // structure.
3873 llvm::FoldingSetNodeID ID;
3875
3876 void *InsertPos = nullptr;
3877 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3878 return QualType(CT, 0);
3879
3880 // If the pointee type isn't canonical, this won't be a canonical type either,
3881 // so fill in the canonical type field.
3882 QualType Canonical;
3883 if (!T.isCanonical()) {
3884 Canonical = getComplexType(getCanonicalType(T));
3885
3886 // Get the new insert position for the node we care about.
3887 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3888 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3889 }
3890 auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
3891 Types.push_back(New);
3892 ComplexTypes.InsertNode(New, InsertPos);
3893 return QualType(New, 0);
3894}
3895
3896/// getPointerType - Return the uniqued reference to the type for a pointer to
3897/// the specified type.
3899 // Unique pointers, to guarantee there is only one pointer of a particular
3900 // structure.
3901 llvm::FoldingSetNodeID ID;
3903
3904 void *InsertPos = nullptr;
3905 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3906 return QualType(PT, 0);
3907
3908 // If the pointee type isn't canonical, this won't be a canonical type either,
3909 // so fill in the canonical type field.
3910 QualType Canonical;
3911 if (!T.isCanonical()) {
3912 Canonical = getPointerType(getCanonicalType(T));
3913
3914 // Get the new insert position for the node we care about.
3915 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3916 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3917 }
3918 auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
3919 Types.push_back(New);
3920 PointerTypes.InsertNode(New, InsertPos);
3921 return QualType(New, 0);
3922}
3923
3925 llvm::FoldingSetNodeID ID;
3926 AdjustedType::Profile(ID, Orig, New);
3927 void *InsertPos = nullptr;
3928 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3929 if (AT)
3930 return QualType(AT, 0);
3931
3932 QualType Canonical = getCanonicalType(New);
3933
3934 // Get the new insert position for the node we care about.
3935 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3936 assert(!AT && "Shouldn't be in the map!");
3937
3938 AT = new (*this, alignof(AdjustedType))
3939 AdjustedType(Type::Adjusted, Orig, New, Canonical);
3940 Types.push_back(AT);
3941 AdjustedTypes.InsertNode(AT, InsertPos);
3942 return QualType(AT, 0);
3943}
3944
3946 llvm::FoldingSetNodeID ID;
3947 AdjustedType::Profile(ID, Orig, Decayed);
3948 void *InsertPos = nullptr;
3949 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3950 if (AT)
3951 return QualType(AT, 0);
3952
3953 QualType Canonical = getCanonicalType(Decayed);
3954
3955 // Get the new insert position for the node we care about.
3956 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3957 assert(!AT && "Shouldn't be in the map!");
3958
3959 AT = new (*this, alignof(DecayedType)) DecayedType(Orig, Decayed, Canonical);
3960 Types.push_back(AT);
3961 AdjustedTypes.InsertNode(AT, InsertPos);
3962 return QualType(AT, 0);
3963}
3964
3966 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
3967
3968 QualType Decayed;
3969
3970 // C99 6.7.5.3p7:
3971 // A declaration of a parameter as "array of type" shall be
3972 // adjusted to "qualified pointer to type", where the type
3973 // qualifiers (if any) are those specified within the [ and ] of
3974 // the array type derivation.
3975 if (T->isArrayType())
3976 Decayed = getArrayDecayedType(T);
3977
3978 // C99 6.7.5.3p8:
3979 // A declaration of a parameter as "function returning type"
3980 // shall be adjusted to "pointer to function returning type", as
3981 // in 6.3.2.1.
3982 if (T->isFunctionType())
3983 Decayed = getPointerType(T);
3984
3985 return getDecayedType(T, Decayed);
3986}
3987
3989 if (Ty->isArrayParameterType())
3990 return Ty;
3991 assert(Ty->isConstantArrayType() && "Ty must be an array type.");
3992 QualType DTy = Ty.getDesugaredType(*this);
3993 const auto *ATy = cast<ConstantArrayType>(DTy);
3994 llvm::FoldingSetNodeID ID;
3995 ATy->Profile(ID, *this, ATy->getElementType(), ATy->getZExtSize(),
3996 ATy->getSizeExpr(), ATy->getSizeModifier(),
3997 ATy->getIndexTypeQualifiers().getAsOpaqueValue());
3998 void *InsertPos = nullptr;
3999 ArrayParameterType *AT =
4000 ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
4001 if (AT)
4002 return QualType(AT, 0);
4003
4004 QualType Canonical;
4005 if (!DTy.isCanonical()) {
4006 Canonical = getArrayParameterType(getCanonicalType(Ty));
4007
4008 // Get the new insert position for the node we care about.
4009 AT = ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
4010 assert(!AT && "Shouldn't be in the map!");
4011 }
4012
4013 AT = new (*this, alignof(ArrayParameterType))
4014 ArrayParameterType(ATy, Canonical);
4015 Types.push_back(AT);
4016 ArrayParameterTypes.InsertNode(AT, InsertPos);
4017 return QualType(AT, 0);
4018}
4019
4020/// getBlockPointerType - Return the uniqued reference to the type for
4021/// a pointer to the specified block.
4023 assert(T->isFunctionType() && "block of function types only");
4024 // Unique pointers, to guarantee there is only one block of a particular
4025 // structure.
4026 llvm::FoldingSetNodeID ID;
4028
4029 void *InsertPos = nullptr;
4030 if (BlockPointerType *PT =
4031 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4032 return QualType(PT, 0);
4033
4034 // If the block pointee type isn't canonical, this won't be a canonical
4035 // type either so fill in the canonical type field.
4036 QualType Canonical;
4037 if (!T.isCanonical()) {
4039
4040 // Get the new insert position for the node we care about.
4041 BlockPointerType *NewIP =
4042 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4043 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4044 }
4045 auto *New =
4046 new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
4047 Types.push_back(New);
4048 BlockPointerTypes.InsertNode(New, InsertPos);
4049 return QualType(New, 0);
4050}
4051
4052/// getLValueReferenceType - Return the uniqued reference to the type for an
4053/// lvalue reference to the specified type.
4055ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
4056 assert((!T->isPlaceholderType() ||
4057 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4058 "Unresolved placeholder type");
4059
4060 // Unique pointers, to guarantee there is only one pointer of a particular
4061 // structure.
4062 llvm::FoldingSetNodeID ID;
4063 ReferenceType::Profile(ID, T, SpelledAsLValue);
4064
4065 void *InsertPos = nullptr;
4066 if (LValueReferenceType *RT =
4067 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
4068 return QualType(RT, 0);
4069
4070 const auto *InnerRef = T->getAs<ReferenceType>();
4071
4072 // If the referencee type isn't canonical, this won't be a canonical type
4073 // either, so fill in the canonical type field.
4074 QualType Canonical;
4075 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
4076 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4077 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
4078
4079 // Get the new insert position for the node we care about.
4080 LValueReferenceType *NewIP =
4081 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4082 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4083 }
4084
4085 auto *New = new (*this, alignof(LValueReferenceType))
4086 LValueReferenceType(T, Canonical, SpelledAsLValue);
4087 Types.push_back(New);
4088 LValueReferenceTypes.InsertNode(New, InsertPos);
4089
4090 return QualType(New, 0);
4091}
4092
4093/// getRValueReferenceType - Return the uniqued reference to the type for an
4094/// rvalue reference to the specified type.
4096 assert((!T->isPlaceholderType() ||
4097 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4098 "Unresolved placeholder type");
4099
4100 // Unique pointers, to guarantee there is only one pointer of a particular
4101 // structure.
4102 llvm::FoldingSetNodeID ID;
4103 ReferenceType::Profile(ID, T, false);
4104
4105 void *InsertPos = nullptr;
4106 if (RValueReferenceType *RT =
4107 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
4108 return QualType(RT, 0);
4109
4110 const auto *InnerRef = T->getAs<ReferenceType>();
4111
4112 // If the referencee type isn't canonical, this won't be a canonical type
4113 // either, so fill in the canonical type field.
4114 QualType Canonical;
4115 if (InnerRef || !T.isCanonical()) {
4116 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4117 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
4118
4119 // Get the new insert position for the node we care about.
4120 RValueReferenceType *NewIP =
4121 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4122 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4123 }
4124
4125 auto *New = new (*this, alignof(RValueReferenceType))
4126 RValueReferenceType(T, Canonical);
4127 Types.push_back(New);
4128 RValueReferenceTypes.InsertNode(New, InsertPos);
4129 return QualType(New, 0);
4130}
4131
4133 NestedNameSpecifier Qualifier,
4134 const CXXRecordDecl *Cls) const {
4135 if (!Qualifier) {
4136 assert(Cls && "At least one of Qualifier or Cls must be provided");
4137 Qualifier = NestedNameSpecifier(getCanonicalTagType(Cls).getTypePtr());
4138 } else if (!Cls) {
4139 Cls = Qualifier.getAsRecordDecl();
4140 }
4141 // Unique pointers, to guarantee there is only one pointer of a particular
4142 // structure.
4143 llvm::FoldingSetNodeID ID;
4144 MemberPointerType::Profile(ID, T, Qualifier, Cls);
4145
4146 void *InsertPos = nullptr;
4147 if (MemberPointerType *PT =
4148 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4149 return QualType(PT, 0);
4150
4151 NestedNameSpecifier CanonicalQualifier = [&] {
4152 if (!Cls)
4153 return Qualifier.getCanonical();
4154 NestedNameSpecifier R(getCanonicalTagType(Cls).getTypePtr());
4155 assert(R.isCanonical());
4156 return R;
4157 }();
4158 // If the pointee or class type isn't canonical, this won't be a canonical
4159 // type either, so fill in the canonical type field.
4160 QualType Canonical;
4161 if (!T.isCanonical() || Qualifier != CanonicalQualifier) {
4162 Canonical =
4163 getMemberPointerType(getCanonicalType(T), CanonicalQualifier, Cls);
4164 assert(!cast<MemberPointerType>(Canonical)->isSugared());
4165 // Get the new insert position for the node we care about.
4166 [[maybe_unused]] MemberPointerType *NewIP =
4167 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4168 assert(!NewIP && "Shouldn't be in the map!");
4169 }
4170 auto *New = new (*this, alignof(MemberPointerType))
4171 MemberPointerType(T, Qualifier, Canonical);
4172 Types.push_back(New);
4173 MemberPointerTypes.InsertNode(New, InsertPos);
4174 return QualType(New, 0);
4175}
4176
4177/// getConstantArrayType - Return the unique reference to the type for an
4178/// array of the specified element type.
4180 const llvm::APInt &ArySizeIn,
4181 const Expr *SizeExpr,
4183 unsigned IndexTypeQuals) const {
4184 assert((EltTy->isDependentType() ||
4185 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
4186 "Constant array of VLAs is illegal!");
4187
4188 // We only need the size as part of the type if it's instantiation-dependent.
4189 if (SizeExpr && !SizeExpr->isInstantiationDependent())
4190 SizeExpr = nullptr;
4191
4192 // Convert the array size into a canonical width matching the pointer size for
4193 // the target.
4194 llvm::APInt ArySize(ArySizeIn);
4195 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
4196
4197 llvm::FoldingSetNodeID ID;
4198 ConstantArrayType::Profile(ID, *this, EltTy, ArySize.getZExtValue(), SizeExpr,
4199 ASM, IndexTypeQuals);
4200
4201 void *InsertPos = nullptr;
4202 if (ConstantArrayType *ATP =
4203 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
4204 return QualType(ATP, 0);
4205
4206 // If the element type isn't canonical or has qualifiers, or the array bound
4207 // is instantiation-dependent, this won't be a canonical type either, so fill
4208 // in the canonical type field.
4209 QualType Canon;
4210 // FIXME: Check below should look for qualifiers behind sugar.
4211 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
4212 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4213 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
4214 ASM, IndexTypeQuals);
4215 Canon = getQualifiedType(Canon, canonSplit.Quals);
4216
4217 // Get the new insert position for the node we care about.
4218 ConstantArrayType *NewIP =
4219 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
4220 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4221 }
4222
4223 auto *New = ConstantArrayType::Create(*this, EltTy, Canon, ArySize, SizeExpr,
4224 ASM, IndexTypeQuals);
4225 ConstantArrayTypes.InsertNode(New, InsertPos);
4226 Types.push_back(New);
4227 return QualType(New, 0);
4228}
4229
4230/// getVariableArrayDecayedType - Turns the given type, which may be
4231/// variably-modified, into the corresponding type with all the known
4232/// sizes replaced with [*].
4234 // Vastly most common case.
4235 if (!type->isVariablyModifiedType()) return type;
4236
4237 QualType result;
4238
4239 SplitQualType split = type.getSplitDesugaredType();
4240 const Type *ty = split.Ty;
4241 switch (ty->getTypeClass()) {
4242#define TYPE(Class, Base)
4243#define ABSTRACT_TYPE(Class, Base)
4244#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4245#include "clang/AST/TypeNodes.inc"
4246 llvm_unreachable("didn't desugar past all non-canonical types?");
4247
4248 // These types should never be variably-modified.
4249 case Type::Builtin:
4250 case Type::Complex:
4251 case Type::Vector:
4252 case Type::DependentVector:
4253 case Type::ExtVector:
4254 case Type::DependentSizedExtVector:
4255 case Type::ConstantMatrix:
4256 case Type::DependentSizedMatrix:
4257 case Type::DependentAddressSpace:
4258 case Type::ObjCObject:
4259 case Type::ObjCInterface:
4260 case Type::ObjCObjectPointer:
4261 case Type::Record:
4262 case Type::Enum:
4263 case Type::UnresolvedUsing:
4264 case Type::TypeOfExpr:
4265 case Type::TypeOf:
4266 case Type::Decltype:
4267 case Type::UnaryTransform:
4268 case Type::DependentName:
4269 case Type::InjectedClassName:
4270 case Type::TemplateSpecialization:
4271 case Type::TemplateTypeParm:
4272 case Type::SubstTemplateTypeParmPack:
4273 case Type::SubstBuiltinTemplatePack:
4274 case Type::Auto:
4275 case Type::DeducedTemplateSpecialization:
4276 case Type::PackExpansion:
4277 case Type::PackIndexing:
4278 case Type::BitInt:
4279 case Type::DependentBitInt:
4280 case Type::ArrayParameter:
4281 case Type::HLSLAttributedResource:
4282 case Type::HLSLInlineSpirv:
4283 llvm_unreachable("type should never be variably-modified");
4284
4285 // These types can be variably-modified but should never need to
4286 // further decay.
4287 case Type::FunctionNoProto:
4288 case Type::FunctionProto:
4289 case Type::BlockPointer:
4290 case Type::MemberPointer:
4291 case Type::Pipe:
4292 return type;
4293
4294 // These types can be variably-modified. All these modifications
4295 // preserve structure except as noted by comments.
4296 // TODO: if we ever care about optimizing VLAs, there are no-op
4297 // optimizations available here.
4298 case Type::Pointer:
4301 break;
4302
4303 case Type::LValueReference: {
4304 const auto *lv = cast<LValueReferenceType>(ty);
4305 result = getLValueReferenceType(
4306 getVariableArrayDecayedType(lv->getPointeeType()),
4307 lv->isSpelledAsLValue());
4308 break;
4309 }
4310
4311 case Type::RValueReference: {
4312 const auto *lv = cast<RValueReferenceType>(ty);
4313 result = getRValueReferenceType(
4314 getVariableArrayDecayedType(lv->getPointeeType()));
4315 break;
4316 }
4317
4318 case Type::Atomic: {
4319 const auto *at = cast<AtomicType>(ty);
4320 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
4321 break;
4322 }
4323
4324 case Type::ConstantArray: {
4325 const auto *cat = cast<ConstantArrayType>(ty);
4326 result = getConstantArrayType(
4327 getVariableArrayDecayedType(cat->getElementType()),
4328 cat->getSize(),
4329 cat->getSizeExpr(),
4330 cat->getSizeModifier(),
4331 cat->getIndexTypeCVRQualifiers());
4332 break;
4333 }
4334
4335 case Type::DependentSizedArray: {
4336 const auto *dat = cast<DependentSizedArrayType>(ty);
4338 getVariableArrayDecayedType(dat->getElementType()), dat->getSizeExpr(),
4339 dat->getSizeModifier(), dat->getIndexTypeCVRQualifiers());
4340 break;
4341 }
4342
4343 // Turn incomplete types into [*] types.
4344 case Type::IncompleteArray: {
4345 const auto *iat = cast<IncompleteArrayType>(ty);
4346 result =
4348 /*size*/ nullptr, ArraySizeModifier::Normal,
4349 iat->getIndexTypeCVRQualifiers());
4350 break;
4351 }
4352
4353 // Turn VLA types into [*] types.
4354 case Type::VariableArray: {
4355 const auto *vat = cast<VariableArrayType>(ty);
4356 result =
4358 /*size*/ nullptr, ArraySizeModifier::Star,
4359 vat->getIndexTypeCVRQualifiers());
4360 break;
4361 }
4362 }
4363
4364 // Apply the top-level qualifiers from the original.
4365 return getQualifiedType(result, split.Quals);
4366}
4367
4368/// getVariableArrayType - Returns a non-unique reference to the type for a
4369/// variable array of the specified element type.
4372 unsigned IndexTypeQuals) const {
4373 // Since we don't unique expressions, it isn't possible to unique VLA's
4374 // that have an expression provided for their size.
4375 QualType Canon;
4376
4377 // Be sure to pull qualifiers off the element type.
4378 // FIXME: Check below should look for qualifiers behind sugar.
4379 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
4380 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4381 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
4382 IndexTypeQuals);
4383 Canon = getQualifiedType(Canon, canonSplit.Quals);
4384 }
4385
4386 auto *New = new (*this, alignof(VariableArrayType))
4387 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals);
4388
4389 VariableArrayTypes.push_back(New);
4390 Types.push_back(New);
4391 return QualType(New, 0);
4392}
4393
4394/// getDependentSizedArrayType - Returns a non-unique reference to
4395/// the type for a dependently-sized array of the specified element
4396/// type.
4400 unsigned elementTypeQuals) const {
4401 assert((!numElements || numElements->isTypeDependent() ||
4402 numElements->isValueDependent()) &&
4403 "Size must be type- or value-dependent!");
4404
4405 SplitQualType canonElementType = getCanonicalType(elementType).split();
4406
4407 void *insertPos = nullptr;
4408 llvm::FoldingSetNodeID ID;
4410 ID, *this, numElements ? QualType(canonElementType.Ty, 0) : elementType,
4411 ASM, elementTypeQuals, numElements);
4412
4413 // Look for an existing type with these properties.
4414 DependentSizedArrayType *canonTy =
4415 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4416
4417 // Dependently-sized array types that do not have a specified number
4418 // of elements will have their sizes deduced from a dependent
4419 // initializer.
4420 if (!numElements) {
4421 if (canonTy)
4422 return QualType(canonTy, 0);
4423
4424 auto *newType = new (*this, alignof(DependentSizedArrayType))
4425 DependentSizedArrayType(elementType, QualType(), numElements, ASM,
4426 elementTypeQuals);
4427 DependentSizedArrayTypes.InsertNode(newType, insertPos);
4428 Types.push_back(newType);
4429 return QualType(newType, 0);
4430 }
4431
4432 // If we don't have one, build one.
4433 if (!canonTy) {
4434 canonTy = new (*this, alignof(DependentSizedArrayType))
4435 DependentSizedArrayType(QualType(canonElementType.Ty, 0), QualType(),
4436 numElements, ASM, elementTypeQuals);
4437 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
4438 Types.push_back(canonTy);
4439 }
4440
4441 // Apply qualifiers from the element type to the array.
4442 QualType canon = getQualifiedType(QualType(canonTy,0),
4443 canonElementType.Quals);
4444
4445 // If we didn't need extra canonicalization for the element type or the size
4446 // expression, then just use that as our result.
4447 if (QualType(canonElementType.Ty, 0) == elementType &&
4448 canonTy->getSizeExpr() == numElements)
4449 return canon;
4450
4451 // Otherwise, we need to build a type which follows the spelling
4452 // of the element type.
4453 auto *sugaredType = new (*this, alignof(DependentSizedArrayType))
4454 DependentSizedArrayType(elementType, canon, numElements, ASM,
4455 elementTypeQuals);
4456 Types.push_back(sugaredType);
4457 return QualType(sugaredType, 0);
4458}
4459
4462 unsigned elementTypeQuals) const {
4463 llvm::FoldingSetNodeID ID;
4464 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
4465
4466 void *insertPos = nullptr;
4467 if (IncompleteArrayType *iat =
4468 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
4469 return QualType(iat, 0);
4470
4471 // If the element type isn't canonical, this won't be a canonical type
4472 // either, so fill in the canonical type field. We also have to pull
4473 // qualifiers off the element type.
4474 QualType canon;
4475
4476 // FIXME: Check below should look for qualifiers behind sugar.
4477 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
4478 SplitQualType canonSplit = getCanonicalType(elementType).split();
4479 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
4480 ASM, elementTypeQuals);
4481 canon = getQualifiedType(canon, canonSplit.Quals);
4482
4483 // Get the new insert position for the node we care about.
4484 IncompleteArrayType *existing =
4485 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4486 assert(!existing && "Shouldn't be in the map!"); (void) existing;
4487 }
4488
4489 auto *newType = new (*this, alignof(IncompleteArrayType))
4490 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
4491
4492 IncompleteArrayTypes.InsertNode(newType, insertPos);
4493 Types.push_back(newType);
4494 return QualType(newType, 0);
4495}
4496
4499#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
4500 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
4501 NUMVECTORS};
4502
4503#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
4504 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
4505
4506 switch (Ty->getKind()) {
4507 default:
4508 llvm_unreachable("Unsupported builtin vector type");
4509
4510#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4511 ElBits, NF, IsSigned) \
4512 case BuiltinType::Id: \
4513 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4514 llvm::ElementCount::getScalable(NumEls), NF};
4515#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4516 ElBits, NF) \
4517 case BuiltinType::Id: \
4518 return {ElBits == 16 ? HalfTy : (ElBits == 32 ? FloatTy : DoubleTy), \
4519 llvm::ElementCount::getScalable(NumEls), NF};
4520#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4521 ElBits, NF) \
4522 case BuiltinType::Id: \
4523 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4524#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4525 ElBits, NF) \
4526 case BuiltinType::Id: \
4527 return {MFloat8Ty, llvm::ElementCount::getScalable(NumEls), NF};
4528#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4529 case BuiltinType::Id: \
4530 return {BoolTy, llvm::ElementCount::getScalable(NumEls), NF};
4531#include "clang/Basic/AArch64ACLETypes.def"
4532
4533#define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
4534 IsSigned) \
4535 case BuiltinType::Id: \
4536 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4537 llvm::ElementCount::getScalable(NumEls), NF};
4538#define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4539 case BuiltinType::Id: \
4540 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
4541 llvm::ElementCount::getScalable(NumEls), NF};
4542#define RVV_VECTOR_TYPE_BFLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4543 case BuiltinType::Id: \
4544 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4545#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4546 case BuiltinType::Id: \
4547 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
4548#include "clang/Basic/RISCVVTypes.def"
4549 }
4550}
4551
4552/// getExternrefType - Return a WebAssembly externref type, which represents an
4553/// opaque reference to a host value.
4555 if (Target->getTriple().isWasm() && Target->hasFeature("reference-types")) {
4556#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
4557 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
4558 return SingletonId;
4559#include "clang/Basic/WebAssemblyReferenceTypes.def"
4560 }
4561 llvm_unreachable(
4562 "shouldn't try to generate type externref outside WebAssembly target");
4563}
4564
4565/// getScalableVectorType - Return the unique reference to a scalable vector
4566/// type of the specified element type and size. VectorType must be a built-in
4567/// type.
4569 unsigned NumFields) const {
4570 auto K = llvm::ScalableVecTyKey{EltTy, NumElts, NumFields};
4571 if (auto It = ScalableVecTyMap.find(K); It != ScalableVecTyMap.end())
4572 return It->second;
4573
4574 if (Target->hasAArch64ACLETypes()) {
4575 uint64_t EltTySize = getTypeSize(EltTy);
4576
4577#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4578 ElBits, NF, IsSigned) \
4579 if (EltTy->hasIntegerRepresentation() && !EltTy->isBooleanType() && \
4580 EltTy->hasSignedIntegerRepresentation() == IsSigned && \
4581 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4582 return ScalableVecTyMap[K] = SingletonId; \
4583 }
4584#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4585 ElBits, NF) \
4586 if (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4587 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4588 return ScalableVecTyMap[K] = SingletonId; \
4589 }
4590#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4591 ElBits, NF) \
4592 if (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4593 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4594 return ScalableVecTyMap[K] = SingletonId; \
4595 }
4596#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4597 ElBits, NF) \
4598 if (EltTy->isMFloat8Type() && EltTySize == ElBits && \
4599 NumElts == (NumEls * NF) && NumFields == 1) { \
4600 return ScalableVecTyMap[K] = SingletonId; \
4601 }
4602#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4603 if (EltTy->isBooleanType() && NumElts == (NumEls * NF) && NumFields == 1) \
4604 return ScalableVecTyMap[K] = SingletonId;
4605#include "clang/Basic/AArch64ACLETypes.def"
4606 } else if (Target->hasRISCVVTypes()) {
4607 uint64_t EltTySize = getTypeSize(EltTy);
4608#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
4609 IsFP, IsBF) \
4610 if (!EltTy->isBooleanType() && \
4611 ((EltTy->hasIntegerRepresentation() && \
4612 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4613 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4614 IsFP && !IsBF) || \
4615 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4616 IsBF && !IsFP)) && \
4617 EltTySize == ElBits && NumElts == NumEls && NumFields == NF) \
4618 return ScalableVecTyMap[K] = SingletonId;
4619#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4620 if (EltTy->isBooleanType() && NumElts == NumEls) \
4621 return ScalableVecTyMap[K] = SingletonId;
4622#include "clang/Basic/RISCVVTypes.def"
4623 }
4624 return QualType();
4625}
4626
4627/// getVectorType - Return the unique reference to a vector type of
4628/// the specified element type and size. VectorType must be a built-in type.
4630 VectorKind VecKind) const {
4631 assert(vecType->isBuiltinType() ||
4632 (vecType->isBitIntType() &&
4633 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4634 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4635
4636 // Check if we've already instantiated a vector of this type.
4637 llvm::FoldingSetNodeID ID;
4638 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
4639
4640 void *InsertPos = nullptr;
4641 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4642 return QualType(VTP, 0);
4643
4644 // If the element type isn't canonical, this won't be a canonical type either,
4645 // so fill in the canonical type field.
4646 QualType Canonical;
4647 if (!vecType.isCanonical()) {
4648 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
4649
4650 // Get the new insert position for the node we care about.
4651 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4652 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4653 }
4654 auto *New = new (*this, alignof(VectorType))
4655 VectorType(vecType, NumElts, Canonical, VecKind);
4656 VectorTypes.InsertNode(New, InsertPos);
4657 Types.push_back(New);
4658 return QualType(New, 0);
4659}
4660
4662 SourceLocation AttrLoc,
4663 VectorKind VecKind) const {
4664 llvm::FoldingSetNodeID ID;
4665 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
4666 VecKind);
4667 void *InsertPos = nullptr;
4668 DependentVectorType *Canon =
4669 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4671
4672 if (Canon) {
4673 New = new (*this, alignof(DependentVectorType)) DependentVectorType(
4674 VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4675 } else {
4676 QualType CanonVecTy = getCanonicalType(VecType);
4677 if (CanonVecTy == VecType) {
4678 New = new (*this, alignof(DependentVectorType))
4679 DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4680
4681 DependentVectorType *CanonCheck =
4682 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4683 assert(!CanonCheck &&
4684 "Dependent-sized vector_size canonical type broken");
4685 (void)CanonCheck;
4686 DependentVectorTypes.InsertNode(New, InsertPos);
4687 } else {
4688 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
4689 SourceLocation(), VecKind);
4690 New = new (*this, alignof(DependentVectorType))
4691 DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4692 }
4693 }
4694
4695 Types.push_back(New);
4696 return QualType(New, 0);
4697}
4698
4699/// getExtVectorType - Return the unique reference to an extended vector type of
4700/// the specified element type and size. VectorType must be a built-in type.
4702 unsigned NumElts) const {
4703 assert(vecType->isBuiltinType() || vecType->isDependentType() ||
4704 (vecType->isBitIntType() &&
4705 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4706 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4707
4708 // Check if we've already instantiated a vector of this type.
4709 llvm::FoldingSetNodeID ID;
4710 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
4712 void *InsertPos = nullptr;
4713 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4714 return QualType(VTP, 0);
4715
4716 // If the element type isn't canonical, this won't be a canonical type either,
4717 // so fill in the canonical type field.
4718 QualType Canonical;
4719 if (!vecType.isCanonical()) {
4720 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
4721
4722 // Get the new insert position for the node we care about.
4723 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4724 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4725 }
4726 auto *New = new (*this, alignof(ExtVectorType))
4727 ExtVectorType(vecType, NumElts, Canonical);
4728 VectorTypes.InsertNode(New, InsertPos);
4729 Types.push_back(New);
4730 return QualType(New, 0);
4731}
4732
4735 Expr *SizeExpr,
4736 SourceLocation AttrLoc) const {
4737 llvm::FoldingSetNodeID ID;
4739 SizeExpr);
4740
4741 void *InsertPos = nullptr;
4743 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4745 if (Canon) {
4746 // We already have a canonical version of this array type; use it as
4747 // the canonical type for a newly-built type.
4748 New = new (*this, alignof(DependentSizedExtVectorType))
4749 DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr,
4750 AttrLoc);
4751 } else {
4752 QualType CanonVecTy = getCanonicalType(vecType);
4753 if (CanonVecTy == vecType) {
4754 New = new (*this, alignof(DependentSizedExtVectorType))
4755 DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
4756
4757 DependentSizedExtVectorType *CanonCheck
4758 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4759 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4760 (void)CanonCheck;
4761 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
4762 } else {
4763 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4764 SourceLocation());
4765 New = new (*this, alignof(DependentSizedExtVectorType))
4766 DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc);
4767 }
4768 }
4769
4770 Types.push_back(New);
4771 return QualType(New, 0);
4772}
4773
4775 unsigned NumColumns) const {
4776 llvm::FoldingSetNodeID ID;
4777 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
4778 Type::ConstantMatrix);
4779
4780 assert(MatrixType::isValidElementType(ElementTy) &&
4781 "need a valid element type");
4782 assert(ConstantMatrixType::isDimensionValid(NumRows) &&
4784 "need valid matrix dimensions");
4785 void *InsertPos = nullptr;
4786 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
4787 return QualType(MTP, 0);
4788
4789 QualType Canonical;
4790 if (!ElementTy.isCanonical()) {
4791 Canonical =
4792 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
4793
4794 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4795 assert(!NewIP && "Matrix type shouldn't already exist in the map");
4796 (void)NewIP;
4797 }
4798
4799 auto *New = new (*this, alignof(ConstantMatrixType))
4800 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4801 MatrixTypes.InsertNode(New, InsertPos);
4802 Types.push_back(New);
4803 return QualType(New, 0);
4804}
4805
4807 Expr *RowExpr,
4808 Expr *ColumnExpr,
4809 SourceLocation AttrLoc) const {
4810 QualType CanonElementTy = getCanonicalType(ElementTy);
4811 llvm::FoldingSetNodeID ID;
4812 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4813 ColumnExpr);
4814
4815 void *InsertPos = nullptr;
4817 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4818
4819 if (!Canon) {
4820 Canon = new (*this, alignof(DependentSizedMatrixType))
4821 DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr,
4822 ColumnExpr, AttrLoc);
4823#ifndef NDEBUG
4824 DependentSizedMatrixType *CanonCheck =
4825 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4826 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4827#endif
4828 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
4829 Types.push_back(Canon);
4830 }
4831
4832 // Already have a canonical version of the matrix type
4833 //
4834 // If it exactly matches the requested type, use it directly.
4835 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4836 Canon->getRowExpr() == ColumnExpr)
4837 return QualType(Canon, 0);
4838
4839 // Use Canon as the canonical type for newly-built type.
4841 DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr,
4842 ColumnExpr, AttrLoc);
4843 Types.push_back(New);
4844 return QualType(New, 0);
4845}
4846
4848 Expr *AddrSpaceExpr,
4849 SourceLocation AttrLoc) const {
4850 assert(AddrSpaceExpr->isInstantiationDependent());
4851
4852 QualType canonPointeeType = getCanonicalType(PointeeType);
4853
4854 void *insertPos = nullptr;
4855 llvm::FoldingSetNodeID ID;
4856 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4857 AddrSpaceExpr);
4858
4859 DependentAddressSpaceType *canonTy =
4860 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
4861
4862 if (!canonTy) {
4863 canonTy = new (*this, alignof(DependentAddressSpaceType))
4864 DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr,
4865 AttrLoc);
4866 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
4867 Types.push_back(canonTy);
4868 }
4869
4870 if (canonPointeeType == PointeeType &&
4871 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4872 return QualType(canonTy, 0);
4873
4874 auto *sugaredType = new (*this, alignof(DependentAddressSpaceType))
4875 DependentAddressSpaceType(PointeeType, QualType(canonTy, 0),
4876 AddrSpaceExpr, AttrLoc);
4877 Types.push_back(sugaredType);
4878 return QualType(sugaredType, 0);
4879}
4880
4881/// Determine whether \p T is canonical as the result type of a function.
4883 return T.isCanonical() &&
4884 (T.getObjCLifetime() == Qualifiers::OCL_None ||
4885 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4886}
4887
4888/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4889QualType
4891 const FunctionType::ExtInfo &Info) const {
4892 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
4893 // functionality creates a function without a prototype regardless of
4894 // language mode (so it makes them even in C++). Once the rewriter has been
4895 // fixed, this assertion can be enabled again.
4896 //assert(!LangOpts.requiresStrictPrototypes() &&
4897 // "strict prototypes are disabled");
4898
4899 // Unique functions, to guarantee there is only one function of a particular
4900 // structure.
4901 llvm::FoldingSetNodeID ID;
4902 FunctionNoProtoType::Profile(ID, ResultTy, Info);
4903
4904 void *InsertPos = nullptr;
4905 if (FunctionNoProtoType *FT =
4906 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
4907 return QualType(FT, 0);
4908
4909 QualType Canonical;
4910 if (!isCanonicalResultType(ResultTy)) {
4911 Canonical =
4913
4914 // Get the new insert position for the node we care about.
4915 FunctionNoProtoType *NewIP =
4916 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4917 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4918 }
4919
4920 auto *New = new (*this, alignof(FunctionNoProtoType))
4921 FunctionNoProtoType(ResultTy, Canonical, Info);
4922 Types.push_back(New);
4923 FunctionNoProtoTypes.InsertNode(New, InsertPos);
4924 return QualType(New, 0);
4925}
4926
4929 CanQualType CanResultType = getCanonicalType(ResultType);
4930
4931 // Canonical result types do not have ARC lifetime qualifiers.
4932 if (CanResultType.getQualifiers().hasObjCLifetime()) {
4933 Qualifiers Qs = CanResultType.getQualifiers();
4934 Qs.removeObjCLifetime();
4936 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
4937 }
4938
4939 return CanResultType;
4940}
4941
4943 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
4944 if (ESI.Type == EST_None)
4945 return true;
4946 if (!NoexceptInType)
4947 return false;
4948
4949 // C++17 onwards: exception specification is part of the type, as a simple
4950 // boolean "can this function type throw".
4951 if (ESI.Type == EST_BasicNoexcept)
4952 return true;
4953
4954 // A noexcept(expr) specification is (possibly) canonical if expr is
4955 // value-dependent.
4956 if (ESI.Type == EST_DependentNoexcept)
4957 return true;
4958
4959 // A dynamic exception specification is canonical if it only contains pack
4960 // expansions (so we can't tell whether it's non-throwing) and all its
4961 // contained types are canonical.
4962 if (ESI.Type == EST_Dynamic) {
4963 bool AnyPackExpansions = false;
4964 for (QualType ET : ESI.Exceptions) {
4965 if (!ET.isCanonical())
4966 return false;
4967 if (ET->getAs<PackExpansionType>())
4968 AnyPackExpansions = true;
4969 }
4970 return AnyPackExpansions;
4971 }
4972
4973 return false;
4974}
4975
4976QualType ASTContext::getFunctionTypeInternal(
4977 QualType ResultTy, ArrayRef<QualType> ArgArray,
4978 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
4979 size_t NumArgs = ArgArray.size();
4980
4981 // Unique functions, to guarantee there is only one function of a particular
4982 // structure.
4983 llvm::FoldingSetNodeID ID;
4984 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
4985 *this, true);
4986
4987 QualType Canonical;
4988 bool Unique = false;
4989
4990 void *InsertPos = nullptr;
4991 if (FunctionProtoType *FPT =
4992 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
4993 QualType Existing = QualType(FPT, 0);
4994
4995 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
4996 // it so long as our exception specification doesn't contain a dependent
4997 // noexcept expression, or we're just looking for a canonical type.
4998 // Otherwise, we're going to need to create a type
4999 // sugar node to hold the concrete expression.
5000 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
5001 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
5002 return Existing;
5003
5004 // We need a new type sugar node for this one, to hold the new noexcept
5005 // expression. We do no canonicalization here, but that's OK since we don't
5006 // expect to see the same noexcept expression much more than once.
5007 Canonical = getCanonicalType(Existing);
5008 Unique = true;
5009 }
5010
5011 bool NoexceptInType = getLangOpts().CPlusPlus17;
5012 bool IsCanonicalExceptionSpec =
5014
5015 // Determine whether the type being created is already canonical or not.
5016 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
5017 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
5018 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
5019 if (!ArgArray[i].isCanonicalAsParam())
5020 isCanonical = false;
5021
5022 if (OnlyWantCanonical)
5023 assert(isCanonical &&
5024 "given non-canonical parameters constructing canonical type");
5025
5026 // If this type isn't canonical, get the canonical version of it if we don't
5027 // already have it. The exception spec is only partially part of the
5028 // canonical type, and only in C++17 onwards.
5029 if (!isCanonical && Canonical.isNull()) {
5030 SmallVector<QualType, 16> CanonicalArgs;
5031 CanonicalArgs.reserve(NumArgs);
5032 for (unsigned i = 0; i != NumArgs; ++i)
5033 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
5034
5035 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
5036 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
5037 CanonicalEPI.HasTrailingReturn = false;
5038
5039 if (IsCanonicalExceptionSpec) {
5040 // Exception spec is already OK.
5041 } else if (NoexceptInType) {
5042 switch (EPI.ExceptionSpec.Type) {
5044 // We don't know yet. It shouldn't matter what we pick here; no-one
5045 // should ever look at this.
5046 [[fallthrough]];
5047 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
5048 CanonicalEPI.ExceptionSpec.Type = EST_None;
5049 break;
5050
5051 // A dynamic exception specification is almost always "not noexcept",
5052 // with the exception that a pack expansion might expand to no types.
5053 case EST_Dynamic: {
5054 bool AnyPacks = false;
5055 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
5056 if (ET->getAs<PackExpansionType>())
5057 AnyPacks = true;
5058 ExceptionTypeStorage.push_back(getCanonicalType(ET));
5059 }
5060 if (!AnyPacks)
5061 CanonicalEPI.ExceptionSpec.Type = EST_None;
5062 else {
5063 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
5064 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
5065 }
5066 break;
5067 }
5068
5069 case EST_DynamicNone:
5070 case EST_BasicNoexcept:
5071 case EST_NoexceptTrue:
5072 case EST_NoThrow:
5073 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
5074 break;
5075
5077 llvm_unreachable("dependent noexcept is already canonical");
5078 }
5079 } else {
5080 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
5081 }
5082
5083 // Adjust the canonical function result type.
5084 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
5085 Canonical =
5086 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
5087
5088 // Get the new insert position for the node we care about.
5089 FunctionProtoType *NewIP =
5090 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
5091 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5092 }
5093
5094 // Compute the needed size to hold this FunctionProtoType and the
5095 // various trailing objects.
5096 auto ESH = FunctionProtoType::getExceptionSpecSize(
5097 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
5098 size_t Size = FunctionProtoType::totalSizeToAlloc<
5099 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
5100 FunctionType::FunctionTypeExtraAttributeInfo,
5101 FunctionType::FunctionTypeArmAttributes, FunctionType::ExceptionType,
5102 Expr *, FunctionDecl *, FunctionProtoType::ExtParameterInfo, Qualifiers,
5103 FunctionEffect, EffectConditionExpr>(
5106 EPI.requiresFunctionProtoTypeArmAttributes(), ESH.NumExceptionType,
5107 ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
5108 EPI.ExtParameterInfos ? NumArgs : 0,
5110 EPI.FunctionEffects.conditions().size());
5111
5112 auto *FTP = (FunctionProtoType *)Allocate(Size, alignof(FunctionProtoType));
5113 FunctionProtoType::ExtProtoInfo newEPI = EPI;
5114 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
5115 Types.push_back(FTP);
5116 if (!Unique)
5117 FunctionProtoTypes.InsertNode(FTP, InsertPos);
5118 if (!EPI.FunctionEffects.empty())
5119 AnyFunctionEffects = true;
5120 return QualType(FTP, 0);
5121}
5122
5123QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
5124 llvm::FoldingSetNodeID ID;
5125 PipeType::Profile(ID, T, ReadOnly);
5126
5127 void *InsertPos = nullptr;
5128 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
5129 return QualType(PT, 0);
5130
5131 // If the pipe element type isn't canonical, this won't be a canonical type
5132 // either, so fill in the canonical type field.
5133 QualType Canonical;
5134 if (!T.isCanonical()) {
5135 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
5136
5137 // Get the new insert position for the node we care about.
5138 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
5139 assert(!NewIP && "Shouldn't be in the map!");
5140 (void)NewIP;
5141 }
5142 auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly);
5143 Types.push_back(New);
5144 PipeTypes.InsertNode(New, InsertPos);
5145 return QualType(New, 0);
5146}
5147
5149 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
5150 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
5151 : Ty;
5152}
5153
5155 return getPipeType(T, true);
5156}
5157
5159 return getPipeType(T, false);
5160}
5161
5162QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
5163 llvm::FoldingSetNodeID ID;
5164 BitIntType::Profile(ID, IsUnsigned, NumBits);
5165
5166 void *InsertPos = nullptr;
5167 if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5168 return QualType(EIT, 0);
5169
5170 auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits);
5171 BitIntTypes.InsertNode(New, InsertPos);
5172 Types.push_back(New);
5173 return QualType(New, 0);
5174}
5175
5177 Expr *NumBitsExpr) const {
5178 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
5179 llvm::FoldingSetNodeID ID;
5180 DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
5181
5182 void *InsertPos = nullptr;
5183 if (DependentBitIntType *Existing =
5184 DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5185 return QualType(Existing, 0);
5186
5187 auto *New = new (*this, alignof(DependentBitIntType))
5188 DependentBitIntType(IsUnsigned, NumBitsExpr);
5189 DependentBitIntTypes.InsertNode(New, InsertPos);
5190
5191 Types.push_back(New);
5192 return QualType(New, 0);
5193}
5194
5197 using Kind = PredefinedSugarType::Kind;
5198
5199 if (auto *Target = PredefinedSugarTypes[llvm::to_underlying(KD)];
5200 Target != nullptr)
5201 return QualType(Target, 0);
5202
5203 auto getCanonicalType = [](const ASTContext &Ctx, Kind KDI) -> QualType {
5204 switch (KDI) {
5205 // size_t (C99TC3 6.5.3.4), signed size_t (C++23 5.13.2) and
5206 // ptrdiff_t (C99TC3 6.5.6) Although these types are not built-in, they
5207 // are part of the core language and are widely used. Using
5208 // PredefinedSugarType makes these types as named sugar types rather than
5209 // standard integer types, enabling better hints and diagnostics.
5210 case Kind::SizeT:
5211 return Ctx.getFromTargetType(Ctx.Target->getSizeType());
5212 case Kind::SignedSizeT:
5213 return Ctx.getFromTargetType(Ctx.Target->getSignedSizeType());
5214 case Kind::PtrdiffT:
5215 return Ctx.getFromTargetType(Ctx.Target->getPtrDiffType(LangAS::Default));
5216 }
5217 llvm_unreachable("unexpected kind");
5218 };
5219 auto *New = new (*this, alignof(PredefinedSugarType))
5220 PredefinedSugarType(KD, &Idents.get(PredefinedSugarType::getName(KD)),
5221 getCanonicalType(*this, static_cast<Kind>(KD)));
5222 Types.push_back(New);
5223 PredefinedSugarTypes[llvm::to_underlying(KD)] = New;
5224 return QualType(New, 0);
5225}
5226
5228 NestedNameSpecifier Qualifier,
5229 const TypeDecl *Decl) const {
5230 if (auto *Tag = dyn_cast<TagDecl>(Decl))
5231 return getTagType(Keyword, Qualifier, Tag,
5232 /*OwnsTag=*/false);
5233 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
5234 return getTypedefType(Keyword, Qualifier, Typedef);
5235 if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5236 return getUnresolvedUsingType(Keyword, Qualifier, UD);
5237
5239 assert(!Qualifier);
5240 return QualType(Decl->TypeForDecl, 0);
5241}
5242
5244 if (auto *Tag = dyn_cast<TagDecl>(TD))
5245 return getCanonicalTagType(Tag);
5246 if (auto *TN = dyn_cast<TypedefNameDecl>(TD))
5247 return getCanonicalType(TN->getUnderlyingType());
5248 if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TD))
5250 assert(TD->TypeForDecl);
5251 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5252}
5253
5255 if (const auto *TD = dyn_cast<TagDecl>(Decl))
5256 return getCanonicalTagType(TD);
5257 if (const auto *TD = dyn_cast<TypedefNameDecl>(Decl);
5258 isa_and_nonnull<TypedefDecl, TypeAliasDecl>(TD))
5260 /*Qualifier=*/std::nullopt, TD);
5261 if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5262 return getCanonicalUnresolvedUsingType(Using);
5263
5264 assert(Decl->TypeForDecl);
5265 return QualType(Decl->TypeForDecl, 0);
5266}
5267
5268/// getTypedefType - Return the unique reference to the type for the
5269/// specified typedef name decl.
5272 NestedNameSpecifier Qualifier,
5273 const TypedefNameDecl *Decl, QualType UnderlyingType,
5274 std::optional<bool> TypeMatchesDeclOrNone) const {
5275 if (!TypeMatchesDeclOrNone) {
5276 QualType DeclUnderlyingType = Decl->getUnderlyingType();
5277 assert(!DeclUnderlyingType.isNull());
5278 if (UnderlyingType.isNull())
5279 UnderlyingType = DeclUnderlyingType;
5280 else
5281 assert(hasSameType(UnderlyingType, DeclUnderlyingType));
5282 TypeMatchesDeclOrNone = UnderlyingType == DeclUnderlyingType;
5283 } else {
5284 // FIXME: This is a workaround for a serialization cycle: assume the decl
5285 // underlying type is not available; don't touch it.
5286 assert(!UnderlyingType.isNull());
5287 }
5288
5289 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier &&
5290 *TypeMatchesDeclOrNone) {
5291 if (Decl->TypeForDecl)
5292 return QualType(Decl->TypeForDecl, 0);
5293
5294 auto *NewType = new (*this, alignof(TypedefType))
5295 TypedefType(Type::Typedef, Keyword, Qualifier, Decl, UnderlyingType,
5296 !*TypeMatchesDeclOrNone);
5297
5298 Types.push_back(NewType);
5299 Decl->TypeForDecl = NewType;
5300 return QualType(NewType, 0);
5301 }
5302
5303 llvm::FoldingSetNodeID ID;
5304 TypedefType::Profile(ID, Keyword, Qualifier, Decl,
5305 *TypeMatchesDeclOrNone ? QualType() : UnderlyingType);
5306
5307 void *InsertPos = nullptr;
5308 if (FoldingSetPlaceholder<TypedefType> *Placeholder =
5309 TypedefTypes.FindNodeOrInsertPos(ID, InsertPos))
5310 return QualType(Placeholder->getType(), 0);
5311
5312 void *Mem =
5313 Allocate(TypedefType::totalSizeToAlloc<FoldingSetPlaceholder<TypedefType>,
5315 1, !!Qualifier, !*TypeMatchesDeclOrNone),
5316 alignof(TypedefType));
5317 auto *NewType =
5318 new (Mem) TypedefType(Type::Typedef, Keyword, Qualifier, Decl,
5319 UnderlyingType, !*TypeMatchesDeclOrNone);
5320 auto *Placeholder = new (NewType->getFoldingSetPlaceholder())
5322 TypedefTypes.InsertNode(Placeholder, InsertPos);
5323 Types.push_back(NewType);
5324 return QualType(NewType, 0);
5325}
5326
5328 NestedNameSpecifier Qualifier,
5329 const UsingShadowDecl *D,
5330 QualType UnderlyingType) const {
5331 // FIXME: This is expensive to compute every time!
5332 if (UnderlyingType.isNull()) {
5333 const auto *UD = cast<UsingDecl>(D->getIntroducer());
5334 UnderlyingType =
5337 UD->getQualifier(), cast<TypeDecl>(D->getTargetDecl()));
5338 }
5339
5340 llvm::FoldingSetNodeID ID;
5341 UsingType::Profile(ID, Keyword, Qualifier, D, UnderlyingType);
5342
5343 void *InsertPos = nullptr;
5344 if (const UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5345 return QualType(T, 0);
5346
5347 assert(!UnderlyingType.hasLocalQualifiers());
5348
5349 assert(
5351 UnderlyingType));
5352
5353 void *Mem =
5354 Allocate(UsingType::totalSizeToAlloc<NestedNameSpecifier>(!!Qualifier),
5355 alignof(UsingType));
5356 UsingType *T = new (Mem) UsingType(Keyword, Qualifier, D, UnderlyingType);
5357 Types.push_back(T);
5358 UsingTypes.InsertNode(T, InsertPos);
5359 return QualType(T, 0);
5360}
5361
5362TagType *ASTContext::getTagTypeInternal(ElaboratedTypeKeyword Keyword,
5363 NestedNameSpecifier Qualifier,
5364 const TagDecl *TD, bool OwnsTag,
5365 bool IsInjected,
5366 const Type *CanonicalType,
5367 bool WithFoldingSetNode) const {
5368 auto [TC, Size] = [&] {
5369 switch (TD->getDeclKind()) {
5370 case Decl::Enum:
5371 static_assert(alignof(EnumType) == alignof(TagType));
5372 return std::make_tuple(Type::Enum, sizeof(EnumType));
5373 case Decl::ClassTemplatePartialSpecialization:
5374 case Decl::ClassTemplateSpecialization:
5375 case Decl::CXXRecord:
5376 static_assert(alignof(RecordType) == alignof(TagType));
5377 static_assert(alignof(InjectedClassNameType) == alignof(TagType));
5378 if (cast<CXXRecordDecl>(TD)->hasInjectedClassType())
5379 return std::make_tuple(Type::InjectedClassName,
5380 sizeof(InjectedClassNameType));
5381 [[fallthrough]];
5382 case Decl::Record:
5383 return std::make_tuple(Type::Record, sizeof(RecordType));
5384 default:
5385 llvm_unreachable("unexpected decl kind");
5386 }
5387 }();
5388
5389 if (Qualifier) {
5390 static_assert(alignof(NestedNameSpecifier) <= alignof(TagType));
5391 Size = llvm::alignTo(Size, alignof(NestedNameSpecifier)) +
5392 sizeof(NestedNameSpecifier);
5393 }
5394 void *Mem;
5395 if (WithFoldingSetNode) {
5396 // FIXME: It would be more profitable to tail allocate the folding set node
5397 // from the type, instead of the other way around, due to the greater
5398 // alignment requirements of the type. But this makes it harder to deal with
5399 // the different type node sizes. This would require either uniquing from
5400 // different folding sets, or having the folding setaccept a
5401 // contextual parameter which is not fixed at construction.
5402 Mem = Allocate(
5403 sizeof(TagTypeFoldingSetPlaceholder) +
5404 TagTypeFoldingSetPlaceholder::getOffset() + Size,
5405 std::max(alignof(TagTypeFoldingSetPlaceholder), alignof(TagType)));
5406 auto *T = new (Mem) TagTypeFoldingSetPlaceholder();
5407 Mem = T->getTagType();
5408 } else {
5409 Mem = Allocate(Size, alignof(TagType));
5410 }
5411
5412 auto *T = [&, TC = TC]() -> TagType * {
5413 switch (TC) {
5414 case Type::Enum: {
5415 assert(isa<EnumDecl>(TD));
5416 auto *T = new (Mem) EnumType(TC, Keyword, Qualifier, TD, OwnsTag,
5417 IsInjected, CanonicalType);
5418 assert(reinterpret_cast<void *>(T) ==
5419 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5420 "TagType must be the first base of EnumType");
5421 return T;
5422 }
5423 case Type::Record: {
5424 assert(isa<RecordDecl>(TD));
5425 auto *T = new (Mem) RecordType(TC, Keyword, Qualifier, TD, OwnsTag,
5426 IsInjected, CanonicalType);
5427 assert(reinterpret_cast<void *>(T) ==
5428 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5429 "TagType must be the first base of RecordType");
5430 return T;
5431 }
5432 case Type::InjectedClassName: {
5433 auto *T = new (Mem) InjectedClassNameType(Keyword, Qualifier, TD,
5434 IsInjected, CanonicalType);
5435 assert(reinterpret_cast<void *>(T) ==
5436 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5437 "TagType must be the first base of InjectedClassNameType");
5438 return T;
5439 }
5440 default:
5441 llvm_unreachable("unexpected type class");
5442 }
5443 }();
5444 assert(T->getKeyword() == Keyword);
5445 assert(T->getQualifier() == Qualifier);
5446 assert(T->getOriginalDecl() == TD);
5447 assert(T->isInjected() == IsInjected);
5448 assert(T->isTagOwned() == OwnsTag);
5449 assert((T->isCanonicalUnqualified()
5450 ? QualType()
5451 : T->getCanonicalTypeInternal()) == QualType(CanonicalType, 0));
5452 Types.push_back(T);
5453 return T;
5454}
5455
5456static const TagDecl *getNonInjectedClassName(const TagDecl *TD) {
5457 if (const auto *RD = dyn_cast<CXXRecordDecl>(TD);
5458 RD && RD->isInjectedClassName())
5459 return cast<TagDecl>(RD->getDeclContext());
5460 return TD;
5461}
5462
5465 if (TD->TypeForDecl)
5466 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5467
5468 const Type *CanonicalType = getTagTypeInternal(
5470 /*Qualifier=*/std::nullopt, TD,
5471 /*OwnsTag=*/false, /*IsInjected=*/false, /*CanonicalType=*/nullptr,
5472 /*WithFoldingSetNode=*/false);
5473 TD->TypeForDecl = CanonicalType;
5474 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5475}
5476
5478 NestedNameSpecifier Qualifier,
5479 const TagDecl *TD, bool OwnsTag) const {
5480
5481 const TagDecl *NonInjectedTD = ::getNonInjectedClassName(TD);
5482 bool IsInjected = TD != NonInjectedTD;
5483
5484 ElaboratedTypeKeyword PreferredKeyword =
5487 NonInjectedTD->getTagKind());
5488
5489 if (Keyword == PreferredKeyword && !Qualifier && !OwnsTag) {
5490 if (const Type *T = TD->TypeForDecl; T && !T->isCanonicalUnqualified())
5491 return QualType(T, 0);
5492
5493 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5494 const Type *T =
5495 getTagTypeInternal(Keyword,
5496 /*Qualifier=*/std::nullopt, NonInjectedTD,
5497 /*OwnsTag=*/false, IsInjected, CanonicalType,
5498 /*WithFoldingSetNode=*/false);
5499 TD->TypeForDecl = T;
5500 return QualType(T, 0);
5501 }
5502
5503 llvm::FoldingSetNodeID ID;
5504 TagTypeFoldingSetPlaceholder::Profile(ID, Keyword, Qualifier, NonInjectedTD,
5505 OwnsTag, IsInjected);
5506
5507 void *InsertPos = nullptr;
5508 if (TagTypeFoldingSetPlaceholder *T =
5509 TagTypes.FindNodeOrInsertPos(ID, InsertPos))
5510 return QualType(T->getTagType(), 0);
5511
5512 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5513 TagType *T =
5514 getTagTypeInternal(Keyword, Qualifier, NonInjectedTD, OwnsTag, IsInjected,
5515 CanonicalType, /*WithFoldingSetNode=*/true);
5516 TagTypes.InsertNode(TagTypeFoldingSetPlaceholder::fromTagType(T), InsertPos);
5517 return QualType(T, 0);
5518}
5519
5520bool ASTContext::computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits,
5521 unsigned NumPositiveBits,
5522 QualType &BestType,
5523 QualType &BestPromotionType) {
5524 unsigned IntWidth = Target->getIntWidth();
5525 unsigned CharWidth = Target->getCharWidth();
5526 unsigned ShortWidth = Target->getShortWidth();
5527 bool EnumTooLarge = false;
5528 unsigned BestWidth;
5529 if (NumNegativeBits) {
5530 // If there is a negative value, figure out the smallest integer type (of
5531 // int/long/longlong) that fits.
5532 // If it's packed, check also if it fits a char or a short.
5533 if (IsPacked && NumNegativeBits <= CharWidth &&
5534 NumPositiveBits < CharWidth) {
5535 BestType = SignedCharTy;
5536 BestWidth = CharWidth;
5537 } else if (IsPacked && NumNegativeBits <= ShortWidth &&
5538 NumPositiveBits < ShortWidth) {
5539 BestType = ShortTy;
5540 BestWidth = ShortWidth;
5541 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
5542 BestType = IntTy;
5543 BestWidth = IntWidth;
5544 } else {
5545 BestWidth = Target->getLongWidth();
5546
5547 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
5548 BestType = LongTy;
5549 } else {
5550 BestWidth = Target->getLongLongWidth();
5551
5552 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
5553 EnumTooLarge = true;
5554 BestType = LongLongTy;
5555 }
5556 }
5557 BestPromotionType = (BestWidth <= IntWidth ? IntTy : BestType);
5558 } else {
5559 // If there is no negative value, figure out the smallest type that fits
5560 // all of the enumerator values.
5561 // If it's packed, check also if it fits a char or a short.
5562 if (IsPacked && NumPositiveBits <= CharWidth) {
5563 BestType = UnsignedCharTy;
5564 BestPromotionType = IntTy;
5565 BestWidth = CharWidth;
5566 } else if (IsPacked && NumPositiveBits <= ShortWidth) {
5567 BestType = UnsignedShortTy;
5568 BestPromotionType = IntTy;
5569 BestWidth = ShortWidth;
5570 } else if (NumPositiveBits <= IntWidth) {
5571 BestType = UnsignedIntTy;
5572 BestWidth = IntWidth;
5573 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5575 : IntTy;
5576 } else if (NumPositiveBits <= (BestWidth = Target->getLongWidth())) {
5577 BestType = UnsignedLongTy;
5578 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5580 : LongTy;
5581 } else {
5582 BestWidth = Target->getLongLongWidth();
5583 if (NumPositiveBits > BestWidth) {
5584 // This can happen with bit-precise integer types, but those are not
5585 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
5586 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
5587 // a 128-bit integer, we should consider doing the same.
5588 EnumTooLarge = true;
5589 }
5590 BestType = UnsignedLongLongTy;
5591 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5593 : LongLongTy;
5594 }
5595 }
5596 return EnumTooLarge;
5597}
5598
5600 assert((T->isIntegralType(*this) || T->isEnumeralType()) &&
5601 "Integral type required!");
5602 unsigned BitWidth = getIntWidth(T);
5603
5604 if (Value.isUnsigned() || Value.isNonNegative()) {
5605 if (T->isSignedIntegerOrEnumerationType())
5606 --BitWidth;
5607 return Value.getActiveBits() <= BitWidth;
5608 }
5609 return Value.getSignificantBits() <= BitWidth;
5610}
5611
5612UnresolvedUsingType *ASTContext::getUnresolvedUsingTypeInternal(
5614 const UnresolvedUsingTypenameDecl *D, void *InsertPos,
5615 const Type *CanonicalType) const {
5616 void *Mem = Allocate(
5617 UnresolvedUsingType::totalSizeToAlloc<
5619 !!InsertPos, !!Qualifier),
5620 alignof(UnresolvedUsingType));
5621 auto *T = new (Mem) UnresolvedUsingType(Keyword, Qualifier, D, CanonicalType);
5622 if (InsertPos) {
5623 auto *Placeholder = new (T->getFoldingSetPlaceholder())
5625 TypedefTypes.InsertNode(Placeholder, InsertPos);
5626 }
5627 Types.push_back(T);
5628 return T;
5629}
5630
5632 const UnresolvedUsingTypenameDecl *D) const {
5633 D = D->getCanonicalDecl();
5634 if (D->TypeForDecl)
5635 return D->TypeForDecl->getCanonicalTypeUnqualified();
5636
5637 const Type *CanonicalType = getUnresolvedUsingTypeInternal(
5639 /*Qualifier=*/std::nullopt, D,
5640 /*InsertPos=*/nullptr, /*CanonicalType=*/nullptr);
5641 D->TypeForDecl = CanonicalType;
5642 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5643}
5644
5647 NestedNameSpecifier Qualifier,
5648 const UnresolvedUsingTypenameDecl *D) const {
5649 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier) {
5650 if (const Type *T = D->TypeForDecl; T && !T->isCanonicalUnqualified())
5651 return QualType(T, 0);
5652
5653 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5654 const Type *T =
5655 getUnresolvedUsingTypeInternal(ElaboratedTypeKeyword::None,
5656 /*Qualifier=*/std::nullopt, D,
5657 /*InsertPos=*/nullptr, CanonicalType);
5658 D->TypeForDecl = T;
5659 return QualType(T, 0);
5660 }
5661
5662 llvm::FoldingSetNodeID ID;
5663 UnresolvedUsingType::Profile(ID, Keyword, Qualifier, D);
5664
5665 void *InsertPos = nullptr;
5667 UnresolvedUsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5668 return QualType(Placeholder->getType(), 0);
5669 assert(InsertPos);
5670
5671 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5672 const Type *T = getUnresolvedUsingTypeInternal(Keyword, Qualifier, D,
5673 InsertPos, CanonicalType);
5674 return QualType(T, 0);
5675}
5676
5678 QualType modifiedType,
5679 QualType equivalentType,
5680 const Attr *attr) const {
5681 llvm::FoldingSetNodeID id;
5682 AttributedType::Profile(id, attrKind, modifiedType, equivalentType, attr);
5683
5684 void *insertPos = nullptr;
5685 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
5686 if (type) return QualType(type, 0);
5687
5688 assert(!attr || attr->getKind() == attrKind);
5689
5690 QualType canon = getCanonicalType(equivalentType);
5691 type = new (*this, alignof(AttributedType))
5692 AttributedType(canon, attrKind, attr, modifiedType, equivalentType);
5693
5694 Types.push_back(type);
5695 AttributedTypes.InsertNode(type, insertPos);
5696
5697 return QualType(type, 0);
5698}
5699
5701 QualType equivalentType) const {
5702 return getAttributedType(attr->getKind(), modifiedType, equivalentType, attr);
5703}
5704
5706 QualType modifiedType,
5707 QualType equivalentType) {
5708 switch (nullability) {
5710 return getAttributedType(attr::TypeNonNull, modifiedType, equivalentType);
5711
5713 return getAttributedType(attr::TypeNullable, modifiedType, equivalentType);
5714
5716 return getAttributedType(attr::TypeNullableResult, modifiedType,
5717 equivalentType);
5718
5720 return getAttributedType(attr::TypeNullUnspecified, modifiedType,
5721 equivalentType);
5722 }
5723
5724 llvm_unreachable("Unknown nullability kind");
5725}
5726
5727QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
5728 QualType Wrapped) const {
5729 llvm::FoldingSetNodeID ID;
5730 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
5731
5732 void *InsertPos = nullptr;
5733 BTFTagAttributedType *Ty =
5734 BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
5735 if (Ty)
5736 return QualType(Ty, 0);
5737
5738 QualType Canon = getCanonicalType(Wrapped);
5739 Ty = new (*this, alignof(BTFTagAttributedType))
5740 BTFTagAttributedType(Canon, Wrapped, BTFAttr);
5741
5742 Types.push_back(Ty);
5743 BTFTagAttributedTypes.InsertNode(Ty, InsertPos);
5744
5745 return QualType(Ty, 0);
5746}
5747
5749 QualType Wrapped, QualType Contained,
5750 const HLSLAttributedResourceType::Attributes &Attrs) {
5751
5752 llvm::FoldingSetNodeID ID;
5753 HLSLAttributedResourceType::Profile(ID, Wrapped, Contained, Attrs);
5754
5755 void *InsertPos = nullptr;
5756 HLSLAttributedResourceType *Ty =
5757 HLSLAttributedResourceTypes.FindNodeOrInsertPos(ID, InsertPos);
5758 if (Ty)
5759 return QualType(Ty, 0);
5760
5761 Ty = new (*this, alignof(HLSLAttributedResourceType))
5762 HLSLAttributedResourceType(Wrapped, Contained, Attrs);
5763
5764 Types.push_back(Ty);
5765 HLSLAttributedResourceTypes.InsertNode(Ty, InsertPos);
5766
5767 return QualType(Ty, 0);
5768}
5769
5770QualType ASTContext::getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size,
5771 uint32_t Alignment,
5772 ArrayRef<SpirvOperand> Operands) {
5773 llvm::FoldingSetNodeID ID;
5774 HLSLInlineSpirvType::Profile(ID, Opcode, Size, Alignment, Operands);
5775
5776 void *InsertPos = nullptr;
5777 HLSLInlineSpirvType *Ty =
5778 HLSLInlineSpirvTypes.FindNodeOrInsertPos(ID, InsertPos);
5779 if (Ty)
5780 return QualType(Ty, 0);
5781
5782 void *Mem = Allocate(
5783 HLSLInlineSpirvType::totalSizeToAlloc<SpirvOperand>(Operands.size()),
5784 alignof(HLSLInlineSpirvType));
5785
5786 Ty = new (Mem) HLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
5787
5788 Types.push_back(Ty);
5789 HLSLInlineSpirvTypes.InsertNode(Ty, InsertPos);
5790
5791 return QualType(Ty, 0);
5792}
5793
5794/// Retrieve a substitution-result type.
5796 Decl *AssociatedDecl,
5797 unsigned Index,
5798 UnsignedOrNone PackIndex,
5799 bool Final) const {
5800 llvm::FoldingSetNodeID ID;
5801 SubstTemplateTypeParmType::Profile(ID, Replacement, AssociatedDecl, Index,
5802 PackIndex, Final);
5803 void *InsertPos = nullptr;
5804 SubstTemplateTypeParmType *SubstParm =
5805 SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5806
5807 if (!SubstParm) {
5808 void *Mem = Allocate(SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
5809 !Replacement.isCanonical()),
5810 alignof(SubstTemplateTypeParmType));
5811 SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
5812 Index, PackIndex, Final);
5813 Types.push_back(SubstParm);
5814 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
5815 }
5816
5817 return QualType(SubstParm, 0);
5818}
5819
5822 unsigned Index, bool Final,
5823 const TemplateArgument &ArgPack) {
5824#ifndef NDEBUG
5825 for (const auto &P : ArgPack.pack_elements())
5826 assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type");
5827#endif
5828
5829 llvm::FoldingSetNodeID ID;
5830 SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
5831 ArgPack);
5832 void *InsertPos = nullptr;
5833 if (SubstTemplateTypeParmPackType *SubstParm =
5834 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
5835 return QualType(SubstParm, 0);
5836
5837 QualType Canon;
5838 {
5839 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
5840 if (!AssociatedDecl->isCanonicalDecl() ||
5841 !CanonArgPack.structurallyEquals(ArgPack)) {
5843 AssociatedDecl->getCanonicalDecl(), Index, Final, CanonArgPack);
5844 [[maybe_unused]] const auto *Nothing =
5845 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
5846 assert(!Nothing);
5847 }
5848 }
5849
5850 auto *SubstParm = new (*this, alignof(SubstTemplateTypeParmPackType))
5851 SubstTemplateTypeParmPackType(Canon, AssociatedDecl, Index, Final,
5852 ArgPack);
5853 Types.push_back(SubstParm);
5854 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
5855 return QualType(SubstParm, 0);
5856}
5857
5860 assert(llvm::all_of(ArgPack.pack_elements(),
5861 [](const auto &P) {
5862 return P.getKind() == TemplateArgument::Type;
5863 }) &&
5864 "Pack contains a non-type");
5865
5866 llvm::FoldingSetNodeID ID;
5867 SubstBuiltinTemplatePackType::Profile(ID, ArgPack);
5868
5869 void *InsertPos = nullptr;
5870 if (auto *T =
5871 SubstBuiltinTemplatePackTypes.FindNodeOrInsertPos(ID, InsertPos))
5872 return QualType(T, 0);
5873
5874 QualType Canon;
5875 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
5876 if (!CanonArgPack.structurallyEquals(ArgPack))
5877 Canon = getSubstBuiltinTemplatePack(CanonArgPack);
5878
5879 auto *PackType = new (*this, alignof(SubstBuiltinTemplatePackType))
5880 SubstBuiltinTemplatePackType(Canon, ArgPack);
5881 Types.push_back(PackType);
5882 SubstBuiltinTemplatePackTypes.InsertNode(PackType, InsertPos);
5883 return QualType(PackType, 0);
5884}
5885
5886/// Retrieve the template type parameter type for a template
5887/// parameter or parameter pack with the given depth, index, and (optionally)
5888/// name.
5889QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
5890 bool ParameterPack,
5891 TemplateTypeParmDecl *TTPDecl) const {
5892 llvm::FoldingSetNodeID ID;
5893 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
5894 void *InsertPos = nullptr;
5895 TemplateTypeParmType *TypeParm
5896 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5897
5898 if (TypeParm)
5899 return QualType(TypeParm, 0);
5900
5901 if (TTPDecl) {
5902 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
5903 TypeParm = new (*this, alignof(TemplateTypeParmType))
5904 TemplateTypeParmType(Depth, Index, ParameterPack, TTPDecl, Canon);
5905
5906 TemplateTypeParmType *TypeCheck
5907 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5908 assert(!TypeCheck && "Template type parameter canonical type broken");
5909 (void)TypeCheck;
5910 } else
5911 TypeParm = new (*this, alignof(TemplateTypeParmType)) TemplateTypeParmType(
5912 Depth, Index, ParameterPack, /*TTPDecl=*/nullptr, /*Canon=*/QualType());
5913
5914 Types.push_back(TypeParm);
5915 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
5916
5917 return QualType(TypeParm, 0);
5918}
5919
5922 switch (Keyword) {
5923 // These are just themselves.
5929 return Keyword;
5930
5931 // These are equivalent.
5934
5935 // These are functionally equivalent, so relying on their equivalence is
5936 // IFNDR. By making them equivalent, we disallow overloading, which at least
5937 // can produce a diagnostic.
5940 }
5941 llvm_unreachable("unexpected keyword kind");
5942}
5943
5945 ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc,
5946 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc,
5947 TemplateName Name, SourceLocation NameLoc,
5948 const TemplateArgumentListInfo &SpecifiedArgs,
5949 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
5951 Keyword, Name, SpecifiedArgs.arguments(), CanonicalArgs, Underlying);
5952
5955 ElaboratedKeywordLoc, QualifierLoc, TemplateKeywordLoc, NameLoc,
5956 SpecifiedArgs);
5957 return DI;
5958}
5959
5962 ArrayRef<TemplateArgumentLoc> SpecifiedArgs,
5963 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
5964 SmallVector<TemplateArgument, 4> SpecifiedArgVec;
5965 SpecifiedArgVec.reserve(SpecifiedArgs.size());
5966 for (const TemplateArgumentLoc &Arg : SpecifiedArgs)
5967 SpecifiedArgVec.push_back(Arg.getArgument());
5968
5969 return getTemplateSpecializationType(Keyword, Template, SpecifiedArgVec,
5970 CanonicalArgs, Underlying);
5971}
5972
5973[[maybe_unused]] static bool
5975 for (const TemplateArgument &Arg : Args)
5976 if (Arg.isPackExpansion())
5977 return true;
5978 return false;
5979}
5980
5983 ArrayRef<TemplateArgument> Args) const {
5984 assert(Template ==
5985 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true));
5987 Template.getAsDependentTemplateName()));
5988#ifndef NDEBUG
5989 for (const auto &Arg : Args)
5990 assert(Arg.structurallyEquals(getCanonicalTemplateArgument(Arg)));
5991#endif
5992
5993 llvm::FoldingSetNodeID ID;
5994 TemplateSpecializationType::Profile(ID, Keyword, Template, Args, QualType(),
5995 *this);
5996 void *InsertPos = nullptr;
5997 if (auto *T = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
5998 return QualType(T, 0);
5999
6000 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
6001 sizeof(TemplateArgument) * Args.size(),
6002 alignof(TemplateSpecializationType));
6003 auto *Spec =
6004 new (Mem) TemplateSpecializationType(Keyword, Template,
6005 /*IsAlias=*/false, Args, QualType());
6006 assert(Spec->isDependentType() &&
6007 "canonical template specialization must be dependent");
6008 Types.push_back(Spec);
6009 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
6010 return QualType(Spec, 0);
6011}
6012
6015 ArrayRef<TemplateArgument> SpecifiedArgs,
6016 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6017 const auto *TD = Template.getAsTemplateDecl(/*IgnoreDeduced=*/true);
6018 bool IsTypeAlias = TD && TD->isTypeAlias();
6019 if (Underlying.isNull()) {
6020 TemplateName CanonTemplate =
6021 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true);
6022 ElaboratedTypeKeyword CanonKeyword =
6023 CanonTemplate.getAsDependentTemplateName()
6026 bool NonCanonical = Template != CanonTemplate || Keyword != CanonKeyword;
6028 if (CanonicalArgs.empty()) {
6029 CanonArgsVec = SmallVector<TemplateArgument, 4>(SpecifiedArgs);
6030 NonCanonical |= canonicalizeTemplateArguments(CanonArgsVec);
6031 CanonicalArgs = CanonArgsVec;
6032 } else {
6033 NonCanonical |= !llvm::equal(
6034 SpecifiedArgs, CanonicalArgs,
6035 [](const TemplateArgument &A, const TemplateArgument &B) {
6036 return A.structurallyEquals(B);
6037 });
6038 }
6039
6040 // We can get here with an alias template when the specialization
6041 // contains a pack expansion that does not match up with a parameter
6042 // pack, or a builtin template which cannot be resolved due to dependency.
6043 assert((!isa_and_nonnull<TypeAliasTemplateDecl>(TD) ||
6044 hasAnyPackExpansions(CanonicalArgs)) &&
6045 "Caller must compute aliased type");
6046 IsTypeAlias = false;
6047
6049 CanonKeyword, CanonTemplate, CanonicalArgs);
6050 if (!NonCanonical)
6051 return Underlying;
6052 }
6053 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
6054 sizeof(TemplateArgument) * SpecifiedArgs.size() +
6055 (IsTypeAlias ? sizeof(QualType) : 0),
6056 alignof(TemplateSpecializationType));
6057 auto *Spec = new (Mem) TemplateSpecializationType(
6058 Keyword, Template, IsTypeAlias, SpecifiedArgs, Underlying);
6059 Types.push_back(Spec);
6060 return QualType(Spec, 0);
6061}
6062
6065 llvm::FoldingSetNodeID ID;
6066 ParenType::Profile(ID, InnerType);
6067
6068 void *InsertPos = nullptr;
6069 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6070 if (T)
6071 return QualType(T, 0);
6072
6073 QualType Canon = InnerType;
6074 if (!Canon.isCanonical()) {
6075 Canon = getCanonicalType(InnerType);
6076 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6077 assert(!CheckT && "Paren canonical type broken");
6078 (void)CheckT;
6079 }
6080
6081 T = new (*this, alignof(ParenType)) ParenType(InnerType, Canon);
6082 Types.push_back(T);
6083 ParenTypes.InsertNode(T, InsertPos);
6084 return QualType(T, 0);
6085}
6086
6089 const IdentifierInfo *MacroII) const {
6090 QualType Canon = UnderlyingTy;
6091 if (!Canon.isCanonical())
6092 Canon = getCanonicalType(UnderlyingTy);
6093
6094 auto *newType = new (*this, alignof(MacroQualifiedType))
6095 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
6096 Types.push_back(newType);
6097 return QualType(newType, 0);
6098}
6099
6102 const IdentifierInfo *Name) const {
6103 llvm::FoldingSetNodeID ID;
6104 DependentNameType::Profile(ID, Keyword, NNS, Name);
6105
6106 void *InsertPos = nullptr;
6107 if (DependentNameType *T =
6108 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos))
6109 return QualType(T, 0);
6110
6111 ElaboratedTypeKeyword CanonKeyword =
6113 NestedNameSpecifier CanonNNS = NNS.getCanonical();
6114
6115 QualType Canon;
6116 if (CanonKeyword != Keyword || CanonNNS != NNS) {
6117 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
6118 [[maybe_unused]] DependentNameType *T =
6119 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
6120 assert(!T && "broken canonicalization");
6121 assert(Canon.isCanonical());
6122 }
6123
6124 DependentNameType *T = new (*this, alignof(DependentNameType))
6125 DependentNameType(Keyword, NNS, Name, Canon);
6126 Types.push_back(T);
6127 DependentNameTypes.InsertNode(T, InsertPos);
6128 return QualType(T, 0);
6129}
6130
6132 TemplateArgument Arg;
6133 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6135 if (TTP->isParameterPack())
6136 ArgType = getPackExpansionType(ArgType, std::nullopt);
6137
6139 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6140 QualType T =
6141 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
6142 // For class NTTPs, ensure we include the 'const' so the type matches that
6143 // of a real template argument.
6144 // FIXME: It would be more faithful to model this as something like an
6145 // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
6147 if (T->isRecordType()) {
6148 // C++ [temp.param]p8: An id-expression naming a non-type
6149 // template-parameter of class type T denotes a static storage duration
6150 // object of type const T.
6151 T.addConst();
6152 VK = VK_LValue;
6153 } else {
6154 VK = Expr::getValueKindForType(NTTP->getType());
6155 }
6156 Expr *E = new (*this)
6157 DeclRefExpr(*this, NTTP, /*RefersToEnclosingVariableOrCapture=*/false,
6158 T, VK, NTTP->getLocation());
6159
6160 if (NTTP->isParameterPack())
6161 E = new (*this) PackExpansionExpr(E, NTTP->getLocation(), std::nullopt);
6162 Arg = TemplateArgument(E, /*IsCanonical=*/false);
6163 } else {
6164 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
6166 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
6167 TemplateName(TTP));
6168 if (TTP->isParameterPack())
6169 Arg = TemplateArgument(Name, /*NumExpansions=*/std::nullopt);
6170 else
6171 Arg = TemplateArgument(Name);
6172 }
6173
6174 if (Param->isTemplateParameterPack())
6175 Arg =
6176 TemplateArgument::CreatePackCopy(const_cast<ASTContext &>(*this), Arg);
6177
6178 return Arg;
6179}
6180
6182 UnsignedOrNone NumExpansions,
6183 bool ExpectPackInType) const {
6184 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
6185 "Pack expansions must expand one or more parameter packs");
6186
6187 llvm::FoldingSetNodeID ID;
6188 PackExpansionType::Profile(ID, Pattern, NumExpansions);
6189
6190 void *InsertPos = nullptr;
6191 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6192 if (T)
6193 return QualType(T, 0);
6194
6195 QualType Canon;
6196 if (!Pattern.isCanonical()) {
6197 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
6198 /*ExpectPackInType=*/false);
6199
6200 // Find the insert position again, in case we inserted an element into
6201 // PackExpansionTypes and invalidated our insert position.
6202 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6203 }
6204
6205 T = new (*this, alignof(PackExpansionType))
6206 PackExpansionType(Pattern, Canon, NumExpansions);
6207 Types.push_back(T);
6208 PackExpansionTypes.InsertNode(T, InsertPos);
6209 return QualType(T, 0);
6210}
6211
6212/// CmpProtocolNames - Comparison predicate for sorting protocols
6213/// alphabetically.
6214static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
6215 ObjCProtocolDecl *const *RHS) {
6216 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
6217}
6218
6220 if (Protocols.empty()) return true;
6221
6222 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
6223 return false;
6224
6225 for (unsigned i = 1; i != Protocols.size(); ++i)
6226 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
6227 Protocols[i]->getCanonicalDecl() != Protocols[i])
6228 return false;
6229 return true;
6230}
6231
6232static void
6234 // Sort protocols, keyed by name.
6235 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
6236
6237 // Canonicalize.
6238 for (ObjCProtocolDecl *&P : Protocols)
6239 P = P->getCanonicalDecl();
6240
6241 // Remove duplicates.
6242 auto ProtocolsEnd = llvm::unique(Protocols);
6243 Protocols.erase(ProtocolsEnd, Protocols.end());
6244}
6245
6247 ObjCProtocolDecl * const *Protocols,
6248 unsigned NumProtocols) const {
6249 return getObjCObjectType(BaseType, {}, ArrayRef(Protocols, NumProtocols),
6250 /*isKindOf=*/false);
6251}
6252
6254 QualType baseType,
6255 ArrayRef<QualType> typeArgs,
6257 bool isKindOf) const {
6258 // If the base type is an interface and there aren't any protocols or
6259 // type arguments to add, then the interface type will do just fine.
6260 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
6261 isa<ObjCInterfaceType>(baseType))
6262 return baseType;
6263
6264 // Look in the folding set for an existing type.
6265 llvm::FoldingSetNodeID ID;
6266 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
6267 void *InsertPos = nullptr;
6268 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
6269 return QualType(QT, 0);
6270
6271 // Determine the type arguments to be used for canonicalization,
6272 // which may be explicitly specified here or written on the base
6273 // type.
6274 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
6275 if (effectiveTypeArgs.empty()) {
6276 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
6277 effectiveTypeArgs = baseObject->getTypeArgs();
6278 }
6279
6280 // Build the canonical type, which has the canonical base type and a
6281 // sorted-and-uniqued list of protocols and the type arguments
6282 // canonicalized.
6283 QualType canonical;
6284 bool typeArgsAreCanonical = llvm::all_of(
6285 effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); });
6286 bool protocolsSorted = areSortedAndUniqued(protocols);
6287 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
6288 // Determine the canonical type arguments.
6289 ArrayRef<QualType> canonTypeArgs;
6290 SmallVector<QualType, 4> canonTypeArgsVec;
6291 if (!typeArgsAreCanonical) {
6292 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
6293 for (auto typeArg : effectiveTypeArgs)
6294 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
6295 canonTypeArgs = canonTypeArgsVec;
6296 } else {
6297 canonTypeArgs = effectiveTypeArgs;
6298 }
6299
6300 ArrayRef<ObjCProtocolDecl *> canonProtocols;
6301 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
6302 if (!protocolsSorted) {
6303 canonProtocolsVec.append(protocols.begin(), protocols.end());
6304 SortAndUniqueProtocols(canonProtocolsVec);
6305 canonProtocols = canonProtocolsVec;
6306 } else {
6307 canonProtocols = protocols;
6308 }
6309
6310 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
6311 canonProtocols, isKindOf);
6312
6313 // Regenerate InsertPos.
6314 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
6315 }
6316
6317 unsigned size = sizeof(ObjCObjectTypeImpl);
6318 size += typeArgs.size() * sizeof(QualType);
6319 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6320 void *mem = Allocate(size, alignof(ObjCObjectTypeImpl));
6321 auto *T =
6322 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
6323 isKindOf);
6324
6325 Types.push_back(T);
6326 ObjCObjectTypes.InsertNode(T, InsertPos);
6327 return QualType(T, 0);
6328}
6329
6330/// Apply Objective-C protocol qualifiers to the given type.
6331/// If this is for the canonical type of a type parameter, we can apply
6332/// protocol qualifiers on the ObjCObjectPointerType.
6335 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
6336 bool allowOnPointerType) const {
6337 hasError = false;
6338
6339 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
6340 return getObjCTypeParamType(objT->getDecl(), protocols);
6341 }
6342
6343 // Apply protocol qualifiers to ObjCObjectPointerType.
6344 if (allowOnPointerType) {
6345 if (const auto *objPtr =
6346 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
6347 const ObjCObjectType *objT = objPtr->getObjectType();
6348 // Merge protocol lists and construct ObjCObjectType.
6350 protocolsVec.append(objT->qual_begin(),
6351 objT->qual_end());
6352 protocolsVec.append(protocols.begin(), protocols.end());
6353 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
6355 objT->getBaseType(),
6356 objT->getTypeArgsAsWritten(),
6357 protocols,
6358 objT->isKindOfTypeAsWritten());
6360 }
6361 }
6362
6363 // Apply protocol qualifiers to ObjCObjectType.
6364 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
6365 // FIXME: Check for protocols to which the class type is already
6366 // known to conform.
6367
6368 return getObjCObjectType(objT->getBaseType(),
6369 objT->getTypeArgsAsWritten(),
6370 protocols,
6371 objT->isKindOfTypeAsWritten());
6372 }
6373
6374 // If the canonical type is ObjCObjectType, ...
6375 if (type->isObjCObjectType()) {
6376 // Silently overwrite any existing protocol qualifiers.
6377 // TODO: determine whether that's the right thing to do.
6378
6379 // FIXME: Check for protocols to which the class type is already
6380 // known to conform.
6381 return getObjCObjectType(type, {}, protocols, false);
6382 }
6383
6384 // id<protocol-list>
6385 if (type->isObjCIdType()) {
6386 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6387 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
6388 objPtr->isKindOfType());
6390 }
6391
6392 // Class<protocol-list>
6393 if (type->isObjCClassType()) {
6394 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6395 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
6396 objPtr->isKindOfType());
6398 }
6399
6400 hasError = true;
6401 return type;
6402}
6403
6406 ArrayRef<ObjCProtocolDecl *> protocols) const {
6407 // Look in the folding set for an existing type.
6408 llvm::FoldingSetNodeID ID;
6409 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
6410 void *InsertPos = nullptr;
6411 if (ObjCTypeParamType *TypeParam =
6412 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
6413 return QualType(TypeParam, 0);
6414
6415 // We canonicalize to the underlying type.
6416 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
6417 if (!protocols.empty()) {
6418 // Apply the protocol qualifers.
6419 bool hasError;
6421 Canonical, protocols, hasError, true /*allowOnPointerType*/));
6422 assert(!hasError && "Error when apply protocol qualifier to bound type");
6423 }
6424
6425 unsigned size = sizeof(ObjCTypeParamType);
6426 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6427 void *mem = Allocate(size, alignof(ObjCTypeParamType));
6428 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
6429
6430 Types.push_back(newType);
6431 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
6432 return QualType(newType, 0);
6433}
6434
6436 ObjCTypeParamDecl *New) const {
6437 New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType()));
6438 // Update TypeForDecl after updating TypeSourceInfo.
6439 auto *NewTypeParamTy = cast<ObjCTypeParamType>(New->TypeForDecl);
6441 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
6442 QualType UpdatedTy = getObjCTypeParamType(New, protocols);
6443 New->TypeForDecl = UpdatedTy.getTypePtr();
6444}
6445
6446/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
6447/// protocol list adopt all protocols in QT's qualified-id protocol
6448/// list.
6450 ObjCInterfaceDecl *IC) {
6451 if (!QT->isObjCQualifiedIdType())
6452 return false;
6453
6454 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
6455 // If both the right and left sides have qualifiers.
6456 for (auto *Proto : OPT->quals()) {
6457 if (!IC->ClassImplementsProtocol(Proto, false))
6458 return false;
6459 }
6460 return true;
6461 }
6462 return false;
6463}
6464
6465/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
6466/// QT's qualified-id protocol list adopt all protocols in IDecl's list
6467/// of protocols.
6469 ObjCInterfaceDecl *IDecl) {
6470 if (!QT->isObjCQualifiedIdType())
6471 return false;
6472 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
6473 if (!OPT)
6474 return false;
6475 if (!IDecl->hasDefinition())
6476 return false;
6478 CollectInheritedProtocols(IDecl, InheritedProtocols);
6479 if (InheritedProtocols.empty())
6480 return false;
6481 // Check that if every protocol in list of id<plist> conforms to a protocol
6482 // of IDecl's, then bridge casting is ok.
6483 bool Conforms = false;
6484 for (auto *Proto : OPT->quals()) {
6485 Conforms = false;
6486 for (auto *PI : InheritedProtocols) {
6487 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
6488 Conforms = true;
6489 break;
6490 }
6491 }
6492 if (!Conforms)
6493 break;
6494 }
6495 if (Conforms)
6496 return true;
6497
6498 for (auto *PI : InheritedProtocols) {
6499 // If both the right and left sides have qualifiers.
6500 bool Adopts = false;
6501 for (auto *Proto : OPT->quals()) {
6502 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
6503 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
6504 break;
6505 }
6506 if (!Adopts)
6507 return false;
6508 }
6509 return true;
6510}
6511
6512/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
6513/// the given object type.
6515 llvm::FoldingSetNodeID ID;
6516 ObjCObjectPointerType::Profile(ID, ObjectT);
6517
6518 void *InsertPos = nullptr;
6519 if (ObjCObjectPointerType *QT =
6520 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
6521 return QualType(QT, 0);
6522
6523 // Find the canonical object type.
6524 QualType Canonical;
6525 if (!ObjectT.isCanonical()) {
6526 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
6527
6528 // Regenerate InsertPos.
6529 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
6530 }
6531
6532 // No match.
6533 void *Mem =
6535 auto *QType =
6536 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
6537
6538 Types.push_back(QType);
6539 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
6540 return QualType(QType, 0);
6541}
6542
6543/// getObjCInterfaceType - Return the unique reference to the type for the
6544/// specified ObjC interface decl. The list of protocols is optional.
6546 ObjCInterfaceDecl *PrevDecl) const {
6547 if (Decl->TypeForDecl)
6548 return QualType(Decl->TypeForDecl, 0);
6549
6550 if (PrevDecl) {
6551 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
6552 Decl->TypeForDecl = PrevDecl->TypeForDecl;
6553 return QualType(PrevDecl->TypeForDecl, 0);
6554 }
6555
6556 // Prefer the definition, if there is one.
6557 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
6558 Decl = Def;
6559
6560 void *Mem = Allocate(sizeof(ObjCInterfaceType), alignof(ObjCInterfaceType));
6561 auto *T = new (Mem) ObjCInterfaceType(Decl);
6562 Decl->TypeForDecl = T;
6563 Types.push_back(T);
6564 return QualType(T, 0);
6565}
6566
6567/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
6568/// TypeOfExprType AST's (since expression's are never shared). For example,
6569/// multiple declarations that refer to "typeof(x)" all contain different
6570/// DeclRefExpr's. This doesn't effect the type checker, since it operates
6571/// on canonical type's (which are always unique).
6573 TypeOfExprType *toe;
6574 if (tofExpr->isTypeDependent()) {
6575 llvm::FoldingSetNodeID ID;
6576 DependentTypeOfExprType::Profile(ID, *this, tofExpr,
6577 Kind == TypeOfKind::Unqualified);
6578
6579 void *InsertPos = nullptr;
6581 DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
6582 if (Canon) {
6583 // We already have a "canonical" version of an identical, dependent
6584 // typeof(expr) type. Use that as our canonical type.
6585 toe = new (*this, alignof(TypeOfExprType)) TypeOfExprType(
6586 *this, tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
6587 } else {
6588 // Build a new, canonical typeof(expr) type.
6589 Canon = new (*this, alignof(DependentTypeOfExprType))
6590 DependentTypeOfExprType(*this, tofExpr, Kind);
6591 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
6592 toe = Canon;
6593 }
6594 } else {
6595 QualType Canonical = getCanonicalType(tofExpr->getType());
6596 toe = new (*this, alignof(TypeOfExprType))
6597 TypeOfExprType(*this, tofExpr, Kind, Canonical);
6598 }
6599 Types.push_back(toe);
6600 return QualType(toe, 0);
6601}
6602
6603/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
6604/// TypeOfType nodes. The only motivation to unique these nodes would be
6605/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
6606/// an issue. This doesn't affect the type checker, since it operates
6607/// on canonical types (which are always unique).
6609 QualType Canonical = getCanonicalType(tofType);
6610 auto *tot = new (*this, alignof(TypeOfType))
6611 TypeOfType(*this, tofType, Canonical, Kind);
6612 Types.push_back(tot);
6613 return QualType(tot, 0);
6614}
6615
6616/// getReferenceQualifiedType - Given an expr, will return the type for
6617/// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
6618/// and class member access into account.
6620 // C++11 [dcl.type.simple]p4:
6621 // [...]
6622 QualType T = E->getType();
6623 switch (E->getValueKind()) {
6624 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6625 // type of e;
6626 case VK_XValue:
6627 return getRValueReferenceType(T);
6628 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6629 // type of e;
6630 case VK_LValue:
6631 return getLValueReferenceType(T);
6632 // - otherwise, decltype(e) is the type of e.
6633 case VK_PRValue:
6634 return T;
6635 }
6636 llvm_unreachable("Unknown value kind");
6637}
6638
6639/// Unlike many "get<Type>" functions, we don't unique DecltypeType
6640/// nodes. This would never be helpful, since each such type has its own
6641/// expression, and would not give a significant memory saving, since there
6642/// is an Expr tree under each such type.
6644 // C++11 [temp.type]p2:
6645 // If an expression e involves a template parameter, decltype(e) denotes a
6646 // unique dependent type. Two such decltype-specifiers refer to the same
6647 // type only if their expressions are equivalent (14.5.6.1).
6648 QualType CanonType;
6649 if (!E->isInstantiationDependent()) {
6650 CanonType = getCanonicalType(UnderlyingType);
6651 } else if (!UnderlyingType.isNull()) {
6652 CanonType = getDecltypeType(E, QualType());
6653 } else {
6654 llvm::FoldingSetNodeID ID;
6655 DependentDecltypeType::Profile(ID, *this, E);
6656
6657 void *InsertPos = nullptr;
6658 if (DependentDecltypeType *Canon =
6659 DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos))
6660 return QualType(Canon, 0);
6661
6662 // Build a new, canonical decltype(expr) type.
6663 auto *DT =
6664 new (*this, alignof(DependentDecltypeType)) DependentDecltypeType(E);
6665 DependentDecltypeTypes.InsertNode(DT, InsertPos);
6666 Types.push_back(DT);
6667 return QualType(DT, 0);
6668 }
6669 auto *DT = new (*this, alignof(DecltypeType))
6670 DecltypeType(E, UnderlyingType, CanonType);
6671 Types.push_back(DT);
6672 return QualType(DT, 0);
6673}
6674
6676 bool FullySubstituted,
6677 ArrayRef<QualType> Expansions,
6678 UnsignedOrNone Index) const {
6679 QualType Canonical;
6680 if (FullySubstituted && Index) {
6681 Canonical = getCanonicalType(Expansions[*Index]);
6682 } else {
6683 llvm::FoldingSetNodeID ID;
6684 PackIndexingType::Profile(ID, *this, Pattern.getCanonicalType(), IndexExpr,
6685 FullySubstituted, Expansions);
6686 void *InsertPos = nullptr;
6687 PackIndexingType *Canon =
6688 DependentPackIndexingTypes.FindNodeOrInsertPos(ID, InsertPos);
6689 if (!Canon) {
6690 void *Mem = Allocate(
6691 PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6693 Canon =
6694 new (Mem) PackIndexingType(QualType(), Pattern.getCanonicalType(),
6695 IndexExpr, FullySubstituted, Expansions);
6696 DependentPackIndexingTypes.InsertNode(Canon, InsertPos);
6697 }
6698 Canonical = QualType(Canon, 0);
6699 }
6700
6701 void *Mem =
6702 Allocate(PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6704 auto *T = new (Mem) PackIndexingType(Canonical, Pattern, IndexExpr,
6705 FullySubstituted, Expansions);
6706 Types.push_back(T);
6707 return QualType(T, 0);
6708}
6709
6710/// getUnaryTransformationType - We don't unique these, since the memory
6711/// savings are minimal and these are rare.
6714 UnaryTransformType::UTTKind Kind) const {
6715
6716 llvm::FoldingSetNodeID ID;
6717 UnaryTransformType::Profile(ID, BaseType, UnderlyingType, Kind);
6718
6719 void *InsertPos = nullptr;
6720 if (UnaryTransformType *UT =
6721 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos))
6722 return QualType(UT, 0);
6723
6724 QualType CanonType;
6725 if (!BaseType->isDependentType()) {
6726 CanonType = UnderlyingType.getCanonicalType();
6727 } else {
6728 assert(UnderlyingType.isNull() || BaseType == UnderlyingType);
6729 UnderlyingType = QualType();
6730 if (QualType CanonBase = BaseType.getCanonicalType();
6731 BaseType != CanonBase) {
6732 CanonType = getUnaryTransformType(CanonBase, QualType(), Kind);
6733 assert(CanonType.isCanonical());
6734
6735 // Find the insertion position again.
6736 [[maybe_unused]] UnaryTransformType *UT =
6737 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
6738 assert(!UT && "broken canonicalization");
6739 }
6740 }
6741
6742 auto *UT = new (*this, alignof(UnaryTransformType))
6743 UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType);
6744 UnaryTransformTypes.InsertNode(UT, InsertPos);
6745 Types.push_back(UT);
6746 return QualType(UT, 0);
6747}
6748
6749QualType ASTContext::getAutoTypeInternal(
6750 QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent,
6751 bool IsPack, TemplateDecl *TypeConstraintConcept,
6752 ArrayRef<TemplateArgument> TypeConstraintArgs, bool IsCanon) const {
6753 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto &&
6754 !TypeConstraintConcept && !IsDependent)
6755 return getAutoDeductType();
6756
6757 // Look in the folding set for an existing type.
6758 llvm::FoldingSetNodeID ID;
6759 bool IsDeducedDependent =
6760 isa_and_nonnull<TemplateTemplateParmDecl>(TypeConstraintConcept) ||
6761 (!DeducedType.isNull() && DeducedType->isDependentType());
6762 AutoType::Profile(ID, *this, DeducedType, Keyword,
6763 IsDependent || IsDeducedDependent, TypeConstraintConcept,
6764 TypeConstraintArgs);
6765 if (auto const AT_iter = AutoTypes.find(ID); AT_iter != AutoTypes.end())
6766 return QualType(AT_iter->getSecond(), 0);
6767
6768 QualType Canon;
6769 if (!IsCanon) {
6770 if (!DeducedType.isNull()) {
6771 Canon = DeducedType.getCanonicalType();
6772 } else if (TypeConstraintConcept) {
6773 bool AnyNonCanonArgs = false;
6774 auto *CanonicalConcept =
6775 cast<TemplateDecl>(TypeConstraintConcept->getCanonicalDecl());
6776 auto CanonicalConceptArgs = ::getCanonicalTemplateArguments(
6777 *this, TypeConstraintArgs, AnyNonCanonArgs);
6778 if (CanonicalConcept != TypeConstraintConcept || AnyNonCanonArgs) {
6779 Canon = getAutoTypeInternal(QualType(), Keyword, IsDependent, IsPack,
6780 CanonicalConcept, CanonicalConceptArgs,
6781 /*IsCanon=*/true);
6782 }
6783 }
6784 }
6785
6786 void *Mem = Allocate(sizeof(AutoType) +
6787 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
6788 alignof(AutoType));
6789 auto *AT = new (Mem) AutoType(
6790 DeducedType, Keyword,
6791 (IsDependent ? TypeDependence::DependentInstantiation
6792 : TypeDependence::None) |
6793 (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None),
6794 Canon, TypeConstraintConcept, TypeConstraintArgs);
6795#ifndef NDEBUG
6796 llvm::FoldingSetNodeID InsertedID;
6797 AT->Profile(InsertedID, *this);
6798 assert(InsertedID == ID && "ID does not match");
6799#endif
6800 Types.push_back(AT);
6801 AutoTypes.try_emplace(ID, AT);
6802 return QualType(AT, 0);
6803}
6804
6805/// getAutoType - Return the uniqued reference to the 'auto' type which has been
6806/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
6807/// canonical deduced-but-dependent 'auto' type.
6808QualType
6810 bool IsDependent, bool IsPack,
6811 TemplateDecl *TypeConstraintConcept,
6812 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
6813 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
6814 assert((!IsDependent || DeducedType.isNull()) &&
6815 "A dependent auto should be undeduced");
6816 return getAutoTypeInternal(DeducedType, Keyword, IsDependent, IsPack,
6817 TypeConstraintConcept, TypeConstraintArgs);
6818}
6819
6821 QualType CanonT = T.getNonPackExpansionType().getCanonicalType();
6822
6823 // Remove a type-constraint from a top-level auto or decltype(auto).
6824 if (auto *AT = CanonT->getAs<AutoType>()) {
6825 if (!AT->isConstrained())
6826 return T;
6827 return getQualifiedType(getAutoType(QualType(), AT->getKeyword(),
6828 AT->isDependentType(),
6829 AT->containsUnexpandedParameterPack()),
6830 T.getQualifiers());
6831 }
6832
6833 // FIXME: We only support constrained auto at the top level in the type of a
6834 // non-type template parameter at the moment. Once we lift that restriction,
6835 // we'll need to recursively build types containing auto here.
6836 assert(!CanonT->getContainedAutoType() ||
6837 !CanonT->getContainedAutoType()->isConstrained());
6838 return T;
6839}
6840
6841QualType ASTContext::getDeducedTemplateSpecializationTypeInternal(
6843 bool IsDependent, QualType Canon) const {
6844 // Look in the folding set for an existing type.
6845 void *InsertPos = nullptr;
6846 llvm::FoldingSetNodeID ID;
6847 DeducedTemplateSpecializationType::Profile(ID, Keyword, Template, DeducedType,
6848 IsDependent);
6849 if (DeducedTemplateSpecializationType *DTST =
6850 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6851 return QualType(DTST, 0);
6852
6853 auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType))
6854 DeducedTemplateSpecializationType(Keyword, Template, DeducedType,
6855 IsDependent, Canon);
6856
6857#ifndef NDEBUG
6858 llvm::FoldingSetNodeID TempID;
6859 DTST->Profile(TempID);
6860 assert(ID == TempID && "ID does not match");
6861#endif
6862 Types.push_back(DTST);
6863 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
6864 return QualType(DTST, 0);
6865}
6866
6867/// Return the uniqued reference to the deduced template specialization type
6868/// which has been deduced to the given type, or to the canonical undeduced
6869/// such type, or the canonical deduced-but-dependent such type.
6872 bool IsDependent) const {
6873 // FIXME: This could save an extra hash table lookup if it handled all the
6874 // parameters already being canonical.
6875 // FIXME: Can this be formed from a DependentTemplateName, such that the
6876 // keyword should be part of the canonical type?
6877 QualType Canon =
6878 DeducedType.isNull()
6879 ? getDeducedTemplateSpecializationTypeInternal(
6881 QualType(), IsDependent, QualType())
6882 : DeducedType.getCanonicalType();
6883 return getDeducedTemplateSpecializationTypeInternal(
6884 Keyword, Template, DeducedType, IsDependent, Canon);
6885}
6886
6887/// getAtomicType - Return the uniqued reference to the atomic type for
6888/// the given value type.
6890 // Unique pointers, to guarantee there is only one pointer of a particular
6891 // structure.
6892 llvm::FoldingSetNodeID ID;
6894
6895 void *InsertPos = nullptr;
6896 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
6897 return QualType(AT, 0);
6898
6899 // If the atomic value type isn't canonical, this won't be a canonical type
6900 // either, so fill in the canonical type field.
6901 QualType Canonical;
6902 if (!T.isCanonical()) {
6903 Canonical = getAtomicType(getCanonicalType(T));
6904
6905 // Get the new insert position for the node we care about.
6906 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
6907 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
6908 }
6909 auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
6910 Types.push_back(New);
6911 AtomicTypes.InsertNode(New, InsertPos);
6912 return QualType(New, 0);
6913}
6914
6915/// getAutoDeductType - Get type pattern for deducing against 'auto'.
6917 if (AutoDeductTy.isNull())
6918 AutoDeductTy = QualType(new (*this, alignof(AutoType))
6919 AutoType(QualType(), AutoTypeKeyword::Auto,
6920 TypeDependence::None, QualType(),
6921 /*concept*/ nullptr, /*args*/ {}),
6922 0);
6923 return AutoDeductTy;
6924}
6925
6926/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
6928 if (AutoRRefDeductTy.isNull())
6930 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
6931 return AutoRRefDeductTy;
6932}
6933
6934/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
6935/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
6936/// needs to agree with the definition in <stddef.h>.
6940
6942 return getFromTargetType(Target->getSizeType());
6943}
6944
6945/// Return the unique signed counterpart of the integer type
6946/// corresponding to size_t.
6950
6951/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
6952/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
6956
6957/// Return the unique unsigned counterpart of "ptrdiff_t"
6958/// integer type. The standard (C11 7.21.6.1p7) refers to this type
6959/// in the definition of %tu format specifier.
6961 return getFromTargetType(Target->getUnsignedPtrDiffType(LangAS::Default));
6962}
6963
6964/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
6966 return getFromTargetType(Target->getIntMaxType());
6967}
6968
6969/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
6971 return getFromTargetType(Target->getUIntMaxType());
6972}
6973
6974/// getSignedWCharType - Return the type of "signed wchar_t".
6975/// Used when in C++, as a GCC extension.
6977 // FIXME: derive from "Target" ?
6978 return WCharTy;
6979}
6980
6981/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
6982/// Used when in C++, as a GCC extension.
6984 // FIXME: derive from "Target" ?
6985 return UnsignedIntTy;
6986}
6987
6989 return getFromTargetType(Target->getIntPtrType());
6990}
6991
6995
6996/// Return the unique type for "pid_t" defined in
6997/// <sys/types.h>. We need this to compute the correct type for vfork().
6999 return getFromTargetType(Target->getProcessIDType());
7000}
7001
7002//===----------------------------------------------------------------------===//
7003// Type Operators
7004//===----------------------------------------------------------------------===//
7005
7007 // Push qualifiers into arrays, and then discard any remaining
7008 // qualifiers.
7009 T = getCanonicalType(T);
7011 const Type *Ty = T.getTypePtr();
7015 } else if (isa<ArrayType>(Ty)) {
7017 } else if (isa<FunctionType>(Ty)) {
7018 Result = getPointerType(QualType(Ty, 0));
7019 } else {
7020 Result = QualType(Ty, 0);
7021 }
7022
7024}
7025
7027 Qualifiers &quals) const {
7028 SplitQualType splitType = type.getSplitUnqualifiedType();
7029
7030 // FIXME: getSplitUnqualifiedType() actually walks all the way to
7031 // the unqualified desugared type and then drops it on the floor.
7032 // We then have to strip that sugar back off with
7033 // getUnqualifiedDesugaredType(), which is silly.
7034 const auto *AT =
7035 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
7036
7037 // If we don't have an array, just use the results in splitType.
7038 if (!AT) {
7039 quals = splitType.Quals;
7040 return QualType(splitType.Ty, 0);
7041 }
7042
7043 // Otherwise, recurse on the array's element type.
7044 QualType elementType = AT->getElementType();
7045 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
7046
7047 // If that didn't change the element type, AT has no qualifiers, so we
7048 // can just use the results in splitType.
7049 if (elementType == unqualElementType) {
7050 assert(quals.empty()); // from the recursive call
7051 quals = splitType.Quals;
7052 return QualType(splitType.Ty, 0);
7053 }
7054
7055 // Otherwise, add in the qualifiers from the outermost type, then
7056 // build the type back up.
7057 quals.addConsistentQualifiers(splitType.Quals);
7058
7059 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
7060 return getConstantArrayType(unqualElementType, CAT->getSize(),
7061 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
7062 }
7063
7064 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
7065 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
7066 }
7067
7068 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
7069 return getVariableArrayType(unqualElementType, VAT->getSizeExpr(),
7070 VAT->getSizeModifier(),
7071 VAT->getIndexTypeCVRQualifiers());
7072 }
7073
7074 const auto *DSAT = cast<DependentSizedArrayType>(AT);
7075 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
7076 DSAT->getSizeModifier(), 0);
7077}
7078
7079/// Attempt to unwrap two types that may both be array types with the same bound
7080/// (or both be array types of unknown bound) for the purpose of comparing the
7081/// cv-decomposition of two types per C++ [conv.qual].
7082///
7083/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7084/// C++20 [conv.qual], if permitted by the current language mode.
7086 bool AllowPiMismatch) const {
7087 while (true) {
7088 auto *AT1 = getAsArrayType(T1);
7089 if (!AT1)
7090 return;
7091
7092 auto *AT2 = getAsArrayType(T2);
7093 if (!AT2)
7094 return;
7095
7096 // If we don't have two array types with the same constant bound nor two
7097 // incomplete array types, we've unwrapped everything we can.
7098 // C++20 also permits one type to be a constant array type and the other
7099 // to be an incomplete array type.
7100 // FIXME: Consider also unwrapping array of unknown bound and VLA.
7101 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
7102 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
7103 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
7104 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7106 return;
7107 } else if (isa<IncompleteArrayType>(AT1)) {
7108 if (!(isa<IncompleteArrayType>(AT2) ||
7109 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7111 return;
7112 } else {
7113 return;
7114 }
7115
7116 T1 = AT1->getElementType();
7117 T2 = AT2->getElementType();
7118 }
7119}
7120
7121/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
7122///
7123/// If T1 and T2 are both pointer types of the same kind, or both array types
7124/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
7125/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
7126///
7127/// This function will typically be called in a loop that successively
7128/// "unwraps" pointer and pointer-to-member types to compare them at each
7129/// level.
7130///
7131/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7132/// C++20 [conv.qual], if permitted by the current language mode.
7133///
7134/// \return \c true if a pointer type was unwrapped, \c false if we reached a
7135/// pair of types that can't be unwrapped further.
7137 bool AllowPiMismatch) const {
7138 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
7139
7140 const auto *T1PtrType = T1->getAs<PointerType>();
7141 const auto *T2PtrType = T2->getAs<PointerType>();
7142 if (T1PtrType && T2PtrType) {
7143 T1 = T1PtrType->getPointeeType();
7144 T2 = T2PtrType->getPointeeType();
7145 return true;
7146 }
7147
7148 if (const auto *T1MPType = T1->getAs<MemberPointerType>(),
7149 *T2MPType = T2->getAs<MemberPointerType>();
7150 T1MPType && T2MPType) {
7151 if (auto *RD1 = T1MPType->getMostRecentCXXRecordDecl(),
7152 *RD2 = T2MPType->getMostRecentCXXRecordDecl();
7153 RD1 != RD2 && RD1->getCanonicalDecl() != RD2->getCanonicalDecl())
7154 return false;
7155 if (T1MPType->getQualifier().getCanonical() !=
7156 T2MPType->getQualifier().getCanonical())
7157 return false;
7158 T1 = T1MPType->getPointeeType();
7159 T2 = T2MPType->getPointeeType();
7160 return true;
7161 }
7162
7163 if (getLangOpts().ObjC) {
7164 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
7165 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
7166 if (T1OPType && T2OPType) {
7167 T1 = T1OPType->getPointeeType();
7168 T2 = T2OPType->getPointeeType();
7169 return true;
7170 }
7171 }
7172
7173 // FIXME: Block pointers, too?
7174
7175 return false;
7176}
7177
7179 while (true) {
7180 Qualifiers Quals;
7181 T1 = getUnqualifiedArrayType(T1, Quals);
7182 T2 = getUnqualifiedArrayType(T2, Quals);
7183 if (hasSameType(T1, T2))
7184 return true;
7185 if (!UnwrapSimilarTypes(T1, T2))
7186 return false;
7187 }
7188}
7189
7191 while (true) {
7192 Qualifiers Quals1, Quals2;
7193 T1 = getUnqualifiedArrayType(T1, Quals1);
7194 T2 = getUnqualifiedArrayType(T2, Quals2);
7195
7196 Quals1.removeCVRQualifiers();
7197 Quals2.removeCVRQualifiers();
7198 if (Quals1 != Quals2)
7199 return false;
7200
7201 if (hasSameType(T1, T2))
7202 return true;
7203
7204 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
7205 return false;
7206 }
7207}
7208
7211 SourceLocation NameLoc) const {
7212 switch (Name.getKind()) {
7215 // DNInfo work in progress: CHECKME: what about DNLoc?
7217 NameLoc);
7218
7221 // DNInfo work in progress: CHECKME: what about DNLoc?
7222 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
7223 }
7224
7227 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
7228 }
7229
7233 DeclarationName DName;
7234 if (const IdentifierInfo *II = TN.getIdentifier()) {
7235 DName = DeclarationNames.getIdentifier(II);
7236 return DeclarationNameInfo(DName, NameLoc);
7237 } else {
7238 DName = DeclarationNames.getCXXOperatorName(TN.getOperator());
7239 // DNInfo work in progress: FIXME: source locations?
7240 DeclarationNameLoc DNLoc =
7242 return DeclarationNameInfo(DName, NameLoc, DNLoc);
7243 }
7244 }
7245
7249 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
7250 NameLoc);
7251 }
7252
7257 NameLoc);
7258 }
7261 NameLoc);
7264 return getNameForTemplate(DTS->getUnderlying(), NameLoc);
7265 }
7266 }
7267
7268 llvm_unreachable("bad template name kind!");
7269}
7270
7271static const TemplateArgument *
7273 auto handleParam = [](auto *TP) -> const TemplateArgument * {
7274 if (!TP->hasDefaultArgument())
7275 return nullptr;
7276 return &TP->getDefaultArgument().getArgument();
7277 };
7278 switch (P->getKind()) {
7279 case NamedDecl::TemplateTypeParm:
7280 return handleParam(cast<TemplateTypeParmDecl>(P));
7281 case NamedDecl::NonTypeTemplateParm:
7282 return handleParam(cast<NonTypeTemplateParmDecl>(P));
7283 case NamedDecl::TemplateTemplateParm:
7284 return handleParam(cast<TemplateTemplateParmDecl>(P));
7285 default:
7286 llvm_unreachable("Unexpected template parameter kind");
7287 }
7288}
7289
7291 bool IgnoreDeduced) const {
7292 while (std::optional<TemplateName> UnderlyingOrNone =
7293 Name.desugar(IgnoreDeduced))
7294 Name = *UnderlyingOrNone;
7295
7296 switch (Name.getKind()) {
7299 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
7301
7302 // The canonical template name is the canonical template declaration.
7303 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
7304 }
7305
7308 llvm_unreachable("cannot canonicalize unresolved template");
7309
7312 assert(DTN && "Non-dependent template names must refer to template decls.");
7313 NestedNameSpecifier Qualifier = DTN->getQualifier();
7314 NestedNameSpecifier CanonQualifier = Qualifier.getCanonical();
7315 if (Qualifier != CanonQualifier || !DTN->hasTemplateKeyword())
7316 return getDependentTemplateName({CanonQualifier, DTN->getName(),
7317 /*HasTemplateKeyword=*/true});
7318 return Name;
7319 }
7320
7324 TemplateArgument canonArgPack =
7327 canonArgPack, subst->getAssociatedDecl()->getCanonicalDecl(),
7328 subst->getIndex(), subst->getFinal());
7329 }
7331 assert(IgnoreDeduced == false);
7333 DefaultArguments DefArgs = DTS->getDefaultArguments();
7334 TemplateName Underlying = DTS->getUnderlying();
7335
7336 TemplateName CanonUnderlying =
7337 getCanonicalTemplateName(Underlying, /*IgnoreDeduced=*/true);
7338 bool NonCanonical = CanonUnderlying != Underlying;
7339 auto CanonArgs =
7340 getCanonicalTemplateArguments(*this, DefArgs.Args, NonCanonical);
7341
7342 ArrayRef<NamedDecl *> Params =
7343 CanonUnderlying.getAsTemplateDecl()->getTemplateParameters()->asArray();
7344 assert(CanonArgs.size() <= Params.size());
7345 // A deduced template name which deduces the same default arguments already
7346 // declared in the underlying template is the same template as the
7347 // underlying template. We need need to note any arguments which differ from
7348 // the corresponding declaration. If any argument differs, we must build a
7349 // deduced template name.
7350 for (int I = CanonArgs.size() - 1; I >= 0; --I) {
7352 if (!A)
7353 break;
7354 auto CanonParamDefArg = getCanonicalTemplateArgument(*A);
7355 TemplateArgument &CanonDefArg = CanonArgs[I];
7356 if (CanonDefArg.structurallyEquals(CanonParamDefArg))
7357 continue;
7358 // Keep popping from the back any deault arguments which are the same.
7359 if (I == int(CanonArgs.size() - 1))
7360 CanonArgs.pop_back();
7361 NonCanonical = true;
7362 }
7363 return NonCanonical ? getDeducedTemplateName(
7364 CanonUnderlying,
7365 /*DefaultArgs=*/{DefArgs.StartPos, CanonArgs})
7366 : Name;
7367 }
7371 llvm_unreachable("always sugar node");
7372 }
7373
7374 llvm_unreachable("bad template name!");
7375}
7376
7378 const TemplateName &Y,
7379 bool IgnoreDeduced) const {
7380 return getCanonicalTemplateName(X, IgnoreDeduced) ==
7381 getCanonicalTemplateName(Y, IgnoreDeduced);
7382}
7383
7385 const AssociatedConstraint &ACX, const AssociatedConstraint &ACY) const {
7386 if (ACX.ArgPackSubstIndex != ACY.ArgPackSubstIndex)
7387 return false;
7389 return false;
7390 return true;
7391}
7392
7393bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
7394 if (!XCE != !YCE)
7395 return false;
7396
7397 if (!XCE)
7398 return true;
7399
7400 llvm::FoldingSetNodeID XCEID, YCEID;
7401 XCE->Profile(XCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7402 YCE->Profile(YCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7403 return XCEID == YCEID;
7404}
7405
7407 const TypeConstraint *YTC) const {
7408 if (!XTC != !YTC)
7409 return false;
7410
7411 if (!XTC)
7412 return true;
7413
7414 auto *NCX = XTC->getNamedConcept();
7415 auto *NCY = YTC->getNamedConcept();
7416 if (!NCX || !NCY || !isSameEntity(NCX, NCY))
7417 return false;
7420 return false;
7422 if (XTC->getConceptReference()
7424 ->NumTemplateArgs !=
7426 return false;
7427
7428 // Compare slowly by profiling.
7429 //
7430 // We couldn't compare the profiling result for the template
7431 // args here. Consider the following example in different modules:
7432 //
7433 // template <__integer_like _Tp, C<_Tp> Sentinel>
7434 // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
7435 // return __t;
7436 // }
7437 //
7438 // When we compare the profiling result for `C<_Tp>` in different
7439 // modules, it will compare the type of `_Tp` in different modules.
7440 // However, the type of `_Tp` in different modules refer to different
7441 // types here naturally. So we couldn't compare the profiling result
7442 // for the template args directly.
7445}
7446
7448 const NamedDecl *Y) const {
7449 if (X->getKind() != Y->getKind())
7450 return false;
7451
7452 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
7453 auto *TY = cast<TemplateTypeParmDecl>(Y);
7454 if (TX->isParameterPack() != TY->isParameterPack())
7455 return false;
7456 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
7457 return false;
7458 return isSameTypeConstraint(TX->getTypeConstraint(),
7459 TY->getTypeConstraint());
7460 }
7461
7462 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7463 auto *TY = cast<NonTypeTemplateParmDecl>(Y);
7464 return TX->isParameterPack() == TY->isParameterPack() &&
7465 TX->getASTContext().hasSameType(TX->getType(), TY->getType()) &&
7466 isSameConstraintExpr(TX->getPlaceholderTypeConstraint(),
7467 TY->getPlaceholderTypeConstraint());
7468 }
7469
7471 auto *TY = cast<TemplateTemplateParmDecl>(Y);
7472 return TX->isParameterPack() == TY->isParameterPack() &&
7473 isSameTemplateParameterList(TX->getTemplateParameters(),
7474 TY->getTemplateParameters());
7475}
7476
7478 const TemplateParameterList *X, const TemplateParameterList *Y) const {
7479 if (X->size() != Y->size())
7480 return false;
7481
7482 for (unsigned I = 0, N = X->size(); I != N; ++I)
7483 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
7484 return false;
7485
7486 return isSameConstraintExpr(X->getRequiresClause(), Y->getRequiresClause());
7487}
7488
7490 const NamedDecl *Y) const {
7491 // If the type parameter isn't the same already, we don't need to check the
7492 // default argument further.
7493 if (!isSameTemplateParameter(X, Y))
7494 return false;
7495
7496 if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(X)) {
7497 auto *TTPY = cast<TemplateTypeParmDecl>(Y);
7498 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7499 return false;
7500
7501 return hasSameType(TTPX->getDefaultArgument().getArgument().getAsType(),
7502 TTPY->getDefaultArgument().getArgument().getAsType());
7503 }
7504
7505 if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7506 auto *NTTPY = cast<NonTypeTemplateParmDecl>(Y);
7507 if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
7508 return false;
7509
7510 Expr *DefaultArgumentX =
7511 NTTPX->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7512 Expr *DefaultArgumentY =
7513 NTTPY->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7514 llvm::FoldingSetNodeID XID, YID;
7515 DefaultArgumentX->Profile(XID, *this, /*Canonical=*/true);
7516 DefaultArgumentY->Profile(YID, *this, /*Canonical=*/true);
7517 return XID == YID;
7518 }
7519
7520 auto *TTPX = cast<TemplateTemplateParmDecl>(X);
7521 auto *TTPY = cast<TemplateTemplateParmDecl>(Y);
7522
7523 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7524 return false;
7525
7526 const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
7527 const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
7528 return hasSameTemplateName(TAX.getAsTemplate(), TAY.getAsTemplate());
7529}
7530
7532 const NestedNameSpecifier Y) {
7533 if (X == Y)
7534 return true;
7535 if (!X || !Y)
7536 return false;
7537
7538 auto Kind = X.getKind();
7539 if (Kind != Y.getKind())
7540 return false;
7541
7542 // FIXME: For namespaces and types, we're permitted to check that the entity
7543 // is named via the same tokens. We should probably do so.
7544 switch (Kind) {
7546 auto [NamespaceX, PrefixX] = X.getAsNamespaceAndPrefix();
7547 auto [NamespaceY, PrefixY] = Y.getAsNamespaceAndPrefix();
7548 if (!declaresSameEntity(NamespaceX->getNamespace(),
7549 NamespaceY->getNamespace()))
7550 return false;
7551 return isSameQualifier(PrefixX, PrefixY);
7552 }
7554 const auto *TX = X.getAsType(), *TY = Y.getAsType();
7555 if (TX->getCanonicalTypeInternal() != TY->getCanonicalTypeInternal())
7556 return false;
7557 return isSameQualifier(TX->getPrefix(), TY->getPrefix());
7558 }
7562 return true;
7563 }
7564 llvm_unreachable("unhandled qualifier kind");
7565}
7566
7567static bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B) {
7568 if (!A->getASTContext().getLangOpts().CUDA)
7569 return true; // Target attributes are overloadable in CUDA compilation only.
7570 if (A->hasAttr<CUDADeviceAttr>() != B->hasAttr<CUDADeviceAttr>())
7571 return false;
7572 if (A->hasAttr<CUDADeviceAttr>() && B->hasAttr<CUDADeviceAttr>())
7573 return A->hasAttr<CUDAHostAttr>() == B->hasAttr<CUDAHostAttr>();
7574 return true; // unattributed and __host__ functions are the same.
7575}
7576
7577/// Determine whether the attributes we can overload on are identical for A and
7578/// B. Will ignore any overloadable attrs represented in the type of A and B.
7580 const FunctionDecl *B) {
7581 // Note that pass_object_size attributes are represented in the function's
7582 // ExtParameterInfo, so we don't need to check them here.
7583
7584 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
7585 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
7586 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
7587
7588 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
7589 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
7590 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
7591
7592 // Return false if the number of enable_if attributes is different.
7593 if (!Cand1A || !Cand2A)
7594 return false;
7595
7596 Cand1ID.clear();
7597 Cand2ID.clear();
7598
7599 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
7600 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
7601
7602 // Return false if any of the enable_if expressions of A and B are
7603 // different.
7604 if (Cand1ID != Cand2ID)
7605 return false;
7606 }
7607 return hasSameCudaAttrs(A, B);
7608}
7609
7610bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
7611 // Caution: this function is called by the AST reader during deserialization,
7612 // so it cannot rely on AST invariants being met. Non-trivial accessors
7613 // should be avoided, along with any traversal of redeclaration chains.
7614
7615 if (X == Y)
7616 return true;
7617
7618 if (X->getDeclName() != Y->getDeclName())
7619 return false;
7620
7621 // Must be in the same context.
7622 //
7623 // Note that we can't use DeclContext::Equals here, because the DeclContexts
7624 // could be two different declarations of the same function. (We will fix the
7625 // semantic DC to refer to the primary definition after merging.)
7626 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
7628 return false;
7629
7630 // If either X or Y are local to the owning module, they are only possible to
7631 // be the same entity if they are in the same module.
7632 if (X->isModuleLocal() || Y->isModuleLocal())
7633 if (!isInSameModule(X->getOwningModule(), Y->getOwningModule()))
7634 return false;
7635
7636 // Two typedefs refer to the same entity if they have the same underlying
7637 // type.
7638 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
7639 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
7640 return hasSameType(TypedefX->getUnderlyingType(),
7641 TypedefY->getUnderlyingType());
7642
7643 // Must have the same kind.
7644 if (X->getKind() != Y->getKind())
7645 return false;
7646
7647 // Objective-C classes and protocols with the same name always match.
7649 return true;
7650
7652 // No need to handle these here: we merge them when adding them to the
7653 // template.
7654 return false;
7655 }
7656
7657 // Compatible tags match.
7658 if (const auto *TagX = dyn_cast<TagDecl>(X)) {
7659 const auto *TagY = cast<TagDecl>(Y);
7660 return (TagX->getTagKind() == TagY->getTagKind()) ||
7661 ((TagX->getTagKind() == TagTypeKind::Struct ||
7662 TagX->getTagKind() == TagTypeKind::Class ||
7663 TagX->getTagKind() == TagTypeKind::Interface) &&
7664 (TagY->getTagKind() == TagTypeKind::Struct ||
7665 TagY->getTagKind() == TagTypeKind::Class ||
7666 TagY->getTagKind() == TagTypeKind::Interface));
7667 }
7668
7669 // Functions with the same type and linkage match.
7670 // FIXME: This needs to cope with merging of prototyped/non-prototyped
7671 // functions, etc.
7672 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
7673 const auto *FuncY = cast<FunctionDecl>(Y);
7674 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
7675 const auto *CtorY = cast<CXXConstructorDecl>(Y);
7676 if (CtorX->getInheritedConstructor() &&
7677 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
7678 CtorY->getInheritedConstructor().getConstructor()))
7679 return false;
7680 }
7681
7682 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
7683 return false;
7684
7685 // Multiversioned functions with different feature strings are represented
7686 // as separate declarations.
7687 if (FuncX->isMultiVersion()) {
7688 const auto *TAX = FuncX->getAttr<TargetAttr>();
7689 const auto *TAY = FuncY->getAttr<TargetAttr>();
7690 assert(TAX && TAY && "Multiversion Function without target attribute");
7691
7692 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
7693 return false;
7694 }
7695
7696 // Per C++20 [temp.over.link]/4, friends in different classes are sometimes
7697 // not the same entity if they are constrained.
7698 if ((FuncX->isMemberLikeConstrainedFriend() ||
7699 FuncY->isMemberLikeConstrainedFriend()) &&
7700 !FuncX->getLexicalDeclContext()->Equals(
7701 FuncY->getLexicalDeclContext())) {
7702 return false;
7703 }
7704
7705 if (!isSameAssociatedConstraint(FuncX->getTrailingRequiresClause(),
7706 FuncY->getTrailingRequiresClause()))
7707 return false;
7708
7709 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
7710 // Map to the first declaration that we've already merged into this one.
7711 // The TSI of redeclarations might not match (due to calling conventions
7712 // being inherited onto the type but not the TSI), but the TSI type of
7713 // the first declaration of the function should match across modules.
7714 FD = FD->getCanonicalDecl();
7715 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
7716 : FD->getType();
7717 };
7718 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
7719 if (!hasSameType(XT, YT)) {
7720 // We can get functions with different types on the redecl chain in C++17
7721 // if they have differing exception specifications and at least one of
7722 // the excpetion specs is unresolved.
7723 auto *XFPT = XT->getAs<FunctionProtoType>();
7724 auto *YFPT = YT->getAs<FunctionProtoType>();
7725 if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
7726 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
7729 return true;
7730 return false;
7731 }
7732
7733 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
7734 hasSameOverloadableAttrs(FuncX, FuncY);
7735 }
7736
7737 // Variables with the same type and linkage match.
7738 if (const auto *VarX = dyn_cast<VarDecl>(X)) {
7739 const auto *VarY = cast<VarDecl>(Y);
7740 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
7741 // During deserialization, we might compare variables before we load
7742 // their types. Assume the types will end up being the same.
7743 if (VarX->getType().isNull() || VarY->getType().isNull())
7744 return true;
7745
7746 if (hasSameType(VarX->getType(), VarY->getType()))
7747 return true;
7748
7749 // We can get decls with different types on the redecl chain. Eg.
7750 // template <typename T> struct S { static T Var[]; }; // #1
7751 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
7752 // Only? happens when completing an incomplete array type. In this case
7753 // when comparing #1 and #2 we should go through their element type.
7754 const ArrayType *VarXTy = getAsArrayType(VarX->getType());
7755 const ArrayType *VarYTy = getAsArrayType(VarY->getType());
7756 if (!VarXTy || !VarYTy)
7757 return false;
7758 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
7759 return hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
7760 }
7761 return false;
7762 }
7763
7764 // Namespaces with the same name and inlinedness match.
7765 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
7766 const auto *NamespaceY = cast<NamespaceDecl>(Y);
7767 return NamespaceX->isInline() == NamespaceY->isInline();
7768 }
7769
7770 // Identical template names and kinds match if their template parameter lists
7771 // and patterns match.
7772 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
7773 const auto *TemplateY = cast<TemplateDecl>(Y);
7774
7775 // ConceptDecl wouldn't be the same if their constraint expression differs.
7776 if (const auto *ConceptX = dyn_cast<ConceptDecl>(X)) {
7777 const auto *ConceptY = cast<ConceptDecl>(Y);
7778 if (!isSameConstraintExpr(ConceptX->getConstraintExpr(),
7779 ConceptY->getConstraintExpr()))
7780 return false;
7781 }
7782
7783 return isSameEntity(TemplateX->getTemplatedDecl(),
7784 TemplateY->getTemplatedDecl()) &&
7785 isSameTemplateParameterList(TemplateX->getTemplateParameters(),
7786 TemplateY->getTemplateParameters());
7787 }
7788
7789 // Fields with the same name and the same type match.
7790 if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
7791 const auto *FDY = cast<FieldDecl>(Y);
7792 // FIXME: Also check the bitwidth is odr-equivalent, if any.
7793 return hasSameType(FDX->getType(), FDY->getType());
7794 }
7795
7796 // Indirect fields with the same target field match.
7797 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
7798 const auto *IFDY = cast<IndirectFieldDecl>(Y);
7799 return IFDX->getAnonField()->getCanonicalDecl() ==
7800 IFDY->getAnonField()->getCanonicalDecl();
7801 }
7802
7803 // Enumerators with the same name match.
7805 // FIXME: Also check the value is odr-equivalent.
7806 return true;
7807
7808 // Using shadow declarations with the same target match.
7809 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
7810 const auto *USY = cast<UsingShadowDecl>(Y);
7811 return declaresSameEntity(USX->getTargetDecl(), USY->getTargetDecl());
7812 }
7813
7814 // Using declarations with the same qualifier match. (We already know that
7815 // the name matches.)
7816 if (const auto *UX = dyn_cast<UsingDecl>(X)) {
7817 const auto *UY = cast<UsingDecl>(Y);
7818 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7819 UX->hasTypename() == UY->hasTypename() &&
7820 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7821 }
7822 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
7823 const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
7824 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7825 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7826 }
7827 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
7828 return isSameQualifier(
7829 UX->getQualifier(),
7830 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
7831 }
7832
7833 // Using-pack declarations are only created by instantiation, and match if
7834 // they're instantiated from matching UnresolvedUsing...Decls.
7835 if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
7836 return declaresSameEntity(
7837 UX->getInstantiatedFromUsingDecl(),
7838 cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
7839 }
7840
7841 // Namespace alias definitions with the same target match.
7842 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
7843 const auto *NAY = cast<NamespaceAliasDecl>(Y);
7844 return NAX->getNamespace()->Equals(NAY->getNamespace());
7845 }
7846
7847 return false;
7848}
7849
7852 switch (Arg.getKind()) {
7854 return Arg;
7855
7857 return TemplateArgument(Arg.getAsExpr(), /*IsCanonical=*/true,
7858 Arg.getIsDefaulted());
7859
7861 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
7863 Arg.getIsDefaulted());
7864 }
7865
7868 /*isNullPtr*/ true, Arg.getIsDefaulted());
7869
7872 Arg.getIsDefaulted());
7873
7875 return TemplateArgument(
7878
7881
7883 return TemplateArgument(*this,
7886
7889 /*isNullPtr*/ false, Arg.getIsDefaulted());
7890
7892 bool AnyNonCanonArgs = false;
7893 auto CanonArgs = ::getCanonicalTemplateArguments(
7894 *this, Arg.pack_elements(), AnyNonCanonArgs);
7895 if (!AnyNonCanonArgs)
7896 return Arg;
7898 const_cast<ASTContext &>(*this), CanonArgs);
7899 NewArg.setIsDefaulted(Arg.getIsDefaulted());
7900 return NewArg;
7901 }
7902 }
7903
7904 // Silence GCC warning
7905 llvm_unreachable("Unhandled template argument kind");
7906}
7907
7909 const TemplateArgument &Arg2) const {
7910 if (Arg1.getKind() != Arg2.getKind())
7911 return false;
7912
7913 switch (Arg1.getKind()) {
7915 llvm_unreachable("Comparing NULL template argument");
7916
7918 return hasSameType(Arg1.getAsType(), Arg2.getAsType());
7919
7921 return Arg1.getAsDecl()->getUnderlyingDecl()->getCanonicalDecl() ==
7923
7925 return hasSameType(Arg1.getNullPtrType(), Arg2.getNullPtrType());
7926
7931
7933 return llvm::APSInt::isSameValue(Arg1.getAsIntegral(),
7934 Arg2.getAsIntegral());
7935
7937 return Arg1.structurallyEquals(Arg2);
7938
7940 llvm::FoldingSetNodeID ID1, ID2;
7941 Arg1.getAsExpr()->Profile(ID1, *this, /*Canonical=*/true);
7942 Arg2.getAsExpr()->Profile(ID2, *this, /*Canonical=*/true);
7943 return ID1 == ID2;
7944 }
7945
7947 return llvm::equal(
7948 Arg1.getPackAsArray(), Arg2.getPackAsArray(),
7949 [&](const TemplateArgument &Arg1, const TemplateArgument &Arg2) {
7950 return isSameTemplateArgument(Arg1, Arg2);
7951 });
7952 }
7953
7954 llvm_unreachable("Unhandled template argument kind");
7955}
7956
7958 // Handle the non-qualified case efficiently.
7959 if (!T.hasLocalQualifiers()) {
7960 // Handle the common positive case fast.
7961 if (const auto *AT = dyn_cast<ArrayType>(T))
7962 return AT;
7963 }
7964
7965 // Handle the common negative case fast.
7966 if (!isa<ArrayType>(T.getCanonicalType()))
7967 return nullptr;
7968
7969 // Apply any qualifiers from the array type to the element type. This
7970 // implements C99 6.7.3p8: "If the specification of an array type includes
7971 // any type qualifiers, the element type is so qualified, not the array type."
7972
7973 // If we get here, we either have type qualifiers on the type, or we have
7974 // sugar such as a typedef in the way. If we have type qualifiers on the type
7975 // we must propagate them down into the element type.
7976
7977 SplitQualType split = T.getSplitDesugaredType();
7978 Qualifiers qs = split.Quals;
7979
7980 // If we have a simple case, just return now.
7981 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
7982 if (!ATy || qs.empty())
7983 return ATy;
7984
7985 // Otherwise, we have an array and we have qualifiers on it. Push the
7986 // qualifiers into the array element type and return a new array type.
7987 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
7988
7989 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
7990 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
7991 CAT->getSizeExpr(),
7992 CAT->getSizeModifier(),
7993 CAT->getIndexTypeCVRQualifiers()));
7994 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
7996 IAT->getSizeModifier(),
7997 IAT->getIndexTypeCVRQualifiers()));
7998
7999 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
8001 NewEltTy, DSAT->getSizeExpr(), DSAT->getSizeModifier(),
8002 DSAT->getIndexTypeCVRQualifiers()));
8003
8004 const auto *VAT = cast<VariableArrayType>(ATy);
8005 return cast<ArrayType>(
8006 getVariableArrayType(NewEltTy, VAT->getSizeExpr(), VAT->getSizeModifier(),
8007 VAT->getIndexTypeCVRQualifiers()));
8008}
8009
8011 if (getLangOpts().HLSL && T->isConstantArrayType())
8012 return getArrayParameterType(T);
8013 if (T->isArrayType() || T->isFunctionType())
8014 return getDecayedType(T);
8015 return T;
8016}
8017
8021 return T.getUnqualifiedType();
8022}
8023
8025 // C++ [except.throw]p3:
8026 // A throw-expression initializes a temporary object, called the exception
8027 // object, the type of which is determined by removing any top-level
8028 // cv-qualifiers from the static type of the operand of throw and adjusting
8029 // the type from "array of T" or "function returning T" to "pointer to T"
8030 // or "pointer to function returning T", [...]
8032 if (T->isArrayType() || T->isFunctionType())
8033 T = getDecayedType(T);
8034 return T.getUnqualifiedType();
8035}
8036
8037/// getArrayDecayedType - Return the properly qualified result of decaying the
8038/// specified array type to a pointer. This operation is non-trivial when
8039/// handling typedefs etc. The canonical type of "T" must be an array type,
8040/// this returns a pointer to a properly qualified element of the array.
8041///
8042/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
8044 // Get the element type with 'getAsArrayType' so that we don't lose any
8045 // typedefs in the element type of the array. This also handles propagation
8046 // of type qualifiers from the array type into the element type if present
8047 // (C99 6.7.3p8).
8048 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
8049 assert(PrettyArrayType && "Not an array type!");
8050
8051 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
8052
8053 // int x[restrict 4] -> int *restrict
8055 PrettyArrayType->getIndexTypeQualifiers());
8056
8057 // int x[_Nullable] -> int * _Nullable
8058 if (auto Nullability = Ty->getNullability()) {
8059 Result = const_cast<ASTContext *>(this)->getAttributedType(*Nullability,
8060 Result, Result);
8061 }
8062 return Result;
8063}
8064
8066 return getBaseElementType(array->getElementType());
8067}
8068
8070 Qualifiers qs;
8071 while (true) {
8072 SplitQualType split = type.getSplitDesugaredType();
8073 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
8074 if (!array) break;
8075
8076 type = array->getElementType();
8078 }
8079
8080 return getQualifiedType(type, qs);
8081}
8082
8083/// getConstantArrayElementCount - Returns number of constant array elements.
8084uint64_t
8086 uint64_t ElementCount = 1;
8087 do {
8088 ElementCount *= CA->getZExtSize();
8089 CA = dyn_cast_or_null<ConstantArrayType>(
8091 } while (CA);
8092 return ElementCount;
8093}
8094
8096 const ArrayInitLoopExpr *AILE) const {
8097 if (!AILE)
8098 return 0;
8099
8100 uint64_t ElementCount = 1;
8101
8102 do {
8103 ElementCount *= AILE->getArraySize().getZExtValue();
8104 AILE = dyn_cast<ArrayInitLoopExpr>(AILE->getSubExpr());
8105 } while (AILE);
8106
8107 return ElementCount;
8108}
8109
8110/// getFloatingRank - Return a relative rank for floating point types.
8111/// This routine will assert if passed a built-in type that isn't a float.
8113 if (const auto *CT = T->getAs<ComplexType>())
8114 return getFloatingRank(CT->getElementType());
8115
8116 switch (T->castAs<BuiltinType>()->getKind()) {
8117 default: llvm_unreachable("getFloatingRank(): not a floating type");
8118 case BuiltinType::Float16: return Float16Rank;
8119 case BuiltinType::Half: return HalfRank;
8120 case BuiltinType::Float: return FloatRank;
8121 case BuiltinType::Double: return DoubleRank;
8122 case BuiltinType::LongDouble: return LongDoubleRank;
8123 case BuiltinType::Float128: return Float128Rank;
8124 case BuiltinType::BFloat16: return BFloat16Rank;
8125 case BuiltinType::Ibm128: return Ibm128Rank;
8126 }
8127}
8128
8129/// getFloatingTypeOrder - Compare the rank of the two specified floating
8130/// point types, ignoring the domain of the type (i.e. 'double' ==
8131/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
8132/// LHS < RHS, return -1.
8134 FloatingRank LHSR = getFloatingRank(LHS);
8135 FloatingRank RHSR = getFloatingRank(RHS);
8136
8137 if (LHSR == RHSR)
8138 return 0;
8139 if (LHSR > RHSR)
8140 return 1;
8141 return -1;
8142}
8143
8146 return 0;
8147 return getFloatingTypeOrder(LHS, RHS);
8148}
8149
8150/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
8151/// routine will assert if passed a built-in type that isn't an integer or enum,
8152/// or if it is not canonicalized.
8153unsigned ASTContext::getIntegerRank(const Type *T) const {
8154 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
8155
8156 // Results in this 'losing' to any type of the same size, but winning if
8157 // larger.
8158 if (const auto *EIT = dyn_cast<BitIntType>(T))
8159 return 0 + (EIT->getNumBits() << 3);
8160
8161 switch (cast<BuiltinType>(T)->getKind()) {
8162 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
8163 case BuiltinType::Bool:
8164 return 1 + (getIntWidth(BoolTy) << 3);
8165 case BuiltinType::Char_S:
8166 case BuiltinType::Char_U:
8167 case BuiltinType::SChar:
8168 case BuiltinType::UChar:
8169 return 2 + (getIntWidth(CharTy) << 3);
8170 case BuiltinType::Short:
8171 case BuiltinType::UShort:
8172 return 3 + (getIntWidth(ShortTy) << 3);
8173 case BuiltinType::Int:
8174 case BuiltinType::UInt:
8175 return 4 + (getIntWidth(IntTy) << 3);
8176 case BuiltinType::Long:
8177 case BuiltinType::ULong:
8178 return 5 + (getIntWidth(LongTy) << 3);
8179 case BuiltinType::LongLong:
8180 case BuiltinType::ULongLong:
8181 return 6 + (getIntWidth(LongLongTy) << 3);
8182 case BuiltinType::Int128:
8183 case BuiltinType::UInt128:
8184 return 7 + (getIntWidth(Int128Ty) << 3);
8185
8186 // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
8187 // their underlying types" [c++20 conv.rank]
8188 case BuiltinType::Char8:
8189 return getIntegerRank(UnsignedCharTy.getTypePtr());
8190 case BuiltinType::Char16:
8191 return getIntegerRank(
8192 getFromTargetType(Target->getChar16Type()).getTypePtr());
8193 case BuiltinType::Char32:
8194 return getIntegerRank(
8195 getFromTargetType(Target->getChar32Type()).getTypePtr());
8196 case BuiltinType::WChar_S:
8197 case BuiltinType::WChar_U:
8198 return getIntegerRank(
8199 getFromTargetType(Target->getWCharType()).getTypePtr());
8200 }
8201}
8202
8203/// Whether this is a promotable bitfield reference according
8204/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
8205///
8206/// \returns the type this bit-field will promote to, or NULL if no
8207/// promotion occurs.
8209 if (E->isTypeDependent() || E->isValueDependent())
8210 return {};
8211
8212 // C++ [conv.prom]p5:
8213 // If the bit-field has an enumerated type, it is treated as any other
8214 // value of that type for promotion purposes.
8216 return {};
8217
8218 // FIXME: We should not do this unless E->refersToBitField() is true. This
8219 // matters in C where getSourceBitField() will find bit-fields for various
8220 // cases where the source expression is not a bit-field designator.
8221
8222 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
8223 if (!Field)
8224 return {};
8225
8226 QualType FT = Field->getType();
8227
8228 uint64_t BitWidth = Field->getBitWidthValue();
8229 uint64_t IntSize = getTypeSize(IntTy);
8230 // C++ [conv.prom]p5:
8231 // A prvalue for an integral bit-field can be converted to a prvalue of type
8232 // int if int can represent all the values of the bit-field; otherwise, it
8233 // can be converted to unsigned int if unsigned int can represent all the
8234 // values of the bit-field. If the bit-field is larger yet, no integral
8235 // promotion applies to it.
8236 // C11 6.3.1.1/2:
8237 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
8238 // If an int can represent all values of the original type (as restricted by
8239 // the width, for a bit-field), the value is converted to an int; otherwise,
8240 // it is converted to an unsigned int.
8241 //
8242 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
8243 // We perform that promotion here to match GCC and C++.
8244 // FIXME: C does not permit promotion of an enum bit-field whose rank is
8245 // greater than that of 'int'. We perform that promotion to match GCC.
8246 //
8247 // C23 6.3.1.1p2:
8248 // The value from a bit-field of a bit-precise integer type is converted to
8249 // the corresponding bit-precise integer type. (The rest is the same as in
8250 // C11.)
8251 if (QualType QT = Field->getType(); QT->isBitIntType())
8252 return QT;
8253
8254 if (BitWidth < IntSize)
8255 return IntTy;
8256
8257 if (BitWidth == IntSize)
8258 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
8259
8260 // Bit-fields wider than int are not subject to promotions, and therefore act
8261 // like the base type. GCC has some weird bugs in this area that we
8262 // deliberately do not follow (GCC follows a pre-standard resolution to
8263 // C's DR315 which treats bit-width as being part of the type, and this leaks
8264 // into their semantics in some cases).
8265 return {};
8266}
8267
8268/// getPromotedIntegerType - Returns the type that Promotable will
8269/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
8270/// integer type.
8272 assert(!Promotable.isNull());
8273 assert(isPromotableIntegerType(Promotable));
8274 if (const auto *ED = Promotable->getAsEnumDecl())
8275 return ED->getPromotionType();
8276
8277 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
8278 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
8279 // (3.9.1) can be converted to a prvalue of the first of the following
8280 // types that can represent all the values of its underlying type:
8281 // int, unsigned int, long int, unsigned long int, long long int, or
8282 // unsigned long long int [...]
8283 // FIXME: Is there some better way to compute this?
8284 if (BT->getKind() == BuiltinType::WChar_S ||
8285 BT->getKind() == BuiltinType::WChar_U ||
8286 BT->getKind() == BuiltinType::Char8 ||
8287 BT->getKind() == BuiltinType::Char16 ||
8288 BT->getKind() == BuiltinType::Char32) {
8289 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
8290 uint64_t FromSize = getTypeSize(BT);
8291 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
8293 for (const auto &PT : PromoteTypes) {
8294 uint64_t ToSize = getTypeSize(PT);
8295 if (FromSize < ToSize ||
8296 (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
8297 return PT;
8298 }
8299 llvm_unreachable("char type should fit into long long");
8300 }
8301 }
8302
8303 // At this point, we should have a signed or unsigned integer type.
8304 if (Promotable->isSignedIntegerType())
8305 return IntTy;
8306 uint64_t PromotableSize = getIntWidth(Promotable);
8307 uint64_t IntSize = getIntWidth(IntTy);
8308 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
8309 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
8310}
8311
8312/// Recurses in pointer/array types until it finds an objc retainable
8313/// type and returns its ownership.
8315 while (!T.isNull()) {
8316 if (T.getObjCLifetime() != Qualifiers::OCL_None)
8317 return T.getObjCLifetime();
8318 if (T->isArrayType())
8320 else if (const auto *PT = T->getAs<PointerType>())
8321 T = PT->getPointeeType();
8322 else if (const auto *RT = T->getAs<ReferenceType>())
8323 T = RT->getPointeeType();
8324 else
8325 break;
8326 }
8327
8328 return Qualifiers::OCL_None;
8329}
8330
8331static const Type *getIntegerTypeForEnum(const EnumType *ET) {
8332 // Incomplete enum types are not treated as integer types.
8333 // FIXME: In C++, enum types are never integer types.
8334 const EnumDecl *ED = ET->getOriginalDecl()->getDefinitionOrSelf();
8335 if (ED->isComplete() && !ED->isScoped())
8336 return ED->getIntegerType().getTypePtr();
8337 return nullptr;
8338}
8339
8340/// getIntegerTypeOrder - Returns the highest ranked integer type:
8341/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
8342/// LHS < RHS, return -1.
8344 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
8345 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
8346
8347 // Unwrap enums to their underlying type.
8348 if (const auto *ET = dyn_cast<EnumType>(LHSC))
8349 LHSC = getIntegerTypeForEnum(ET);
8350 if (const auto *ET = dyn_cast<EnumType>(RHSC))
8351 RHSC = getIntegerTypeForEnum(ET);
8352
8353 if (LHSC == RHSC) return 0;
8354
8355 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
8356 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
8357
8358 unsigned LHSRank = getIntegerRank(LHSC);
8359 unsigned RHSRank = getIntegerRank(RHSC);
8360
8361 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
8362 if (LHSRank == RHSRank) return 0;
8363 return LHSRank > RHSRank ? 1 : -1;
8364 }
8365
8366 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
8367 if (LHSUnsigned) {
8368 // If the unsigned [LHS] type is larger, return it.
8369 if (LHSRank >= RHSRank)
8370 return 1;
8371
8372 // If the signed type can represent all values of the unsigned type, it
8373 // wins. Because we are dealing with 2's complement and types that are
8374 // powers of two larger than each other, this is always safe.
8375 return -1;
8376 }
8377
8378 // If the unsigned [RHS] type is larger, return it.
8379 if (RHSRank >= LHSRank)
8380 return -1;
8381
8382 // If the signed type can represent all values of the unsigned type, it
8383 // wins. Because we are dealing with 2's complement and types that are
8384 // powers of two larger than each other, this is always safe.
8385 return 1;
8386}
8387
8389 if (CFConstantStringTypeDecl)
8390 return CFConstantStringTypeDecl;
8391
8392 assert(!CFConstantStringTagDecl &&
8393 "tag and typedef should be initialized together");
8394 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
8395 CFConstantStringTagDecl->startDefinition();
8396
8397 struct {
8398 QualType Type;
8399 const char *Name;
8400 } Fields[5];
8401 unsigned Count = 0;
8402
8403 /// Objective-C ABI
8404 ///
8405 /// typedef struct __NSConstantString_tag {
8406 /// const int *isa;
8407 /// int flags;
8408 /// const char *str;
8409 /// long length;
8410 /// } __NSConstantString;
8411 ///
8412 /// Swift ABI (4.1, 4.2)
8413 ///
8414 /// typedef struct __NSConstantString_tag {
8415 /// uintptr_t _cfisa;
8416 /// uintptr_t _swift_rc;
8417 /// _Atomic(uint64_t) _cfinfoa;
8418 /// const char *_ptr;
8419 /// uint32_t _length;
8420 /// } __NSConstantString;
8421 ///
8422 /// Swift ABI (5.0)
8423 ///
8424 /// typedef struct __NSConstantString_tag {
8425 /// uintptr_t _cfisa;
8426 /// uintptr_t _swift_rc;
8427 /// _Atomic(uint64_t) _cfinfoa;
8428 /// const char *_ptr;
8429 /// uintptr_t _length;
8430 /// } __NSConstantString;
8431
8432 const auto CFRuntime = getLangOpts().CFRuntime;
8433 if (static_cast<unsigned>(CFRuntime) <
8434 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
8435 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
8436 Fields[Count++] = { IntTy, "flags" };
8437 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
8438 Fields[Count++] = { LongTy, "length" };
8439 } else {
8440 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
8441 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
8442 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
8443 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
8446 Fields[Count++] = { IntTy, "_ptr" };
8447 else
8448 Fields[Count++] = { getUIntPtrType(), "_ptr" };
8449 }
8450
8451 // Create fields
8452 for (unsigned i = 0; i < Count; ++i) {
8453 FieldDecl *Field =
8454 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
8455 SourceLocation(), &Idents.get(Fields[i].Name),
8456 Fields[i].Type, /*TInfo=*/nullptr,
8457 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8458 Field->setAccess(AS_public);
8459 CFConstantStringTagDecl->addDecl(Field);
8460 }
8461
8462 CFConstantStringTagDecl->completeDefinition();
8463 // This type is designed to be compatible with NSConstantString, but cannot
8464 // use the same name, since NSConstantString is an interface.
8465 CanQualType tagType = getCanonicalTagType(CFConstantStringTagDecl);
8466 CFConstantStringTypeDecl =
8467 buildImplicitTypedef(tagType, "__NSConstantString");
8468
8469 return CFConstantStringTypeDecl;
8470}
8471
8473 if (!CFConstantStringTagDecl)
8474 getCFConstantStringDecl(); // Build the tag and the typedef.
8475 return CFConstantStringTagDecl;
8476}
8477
8478// getCFConstantStringType - Return the type used for constant CFStrings.
8483
8485 if (ObjCSuperType.isNull()) {
8486 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
8487 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl);
8488 ObjCSuperType = getCanonicalTagType(ObjCSuperTypeDecl);
8489 }
8490 return ObjCSuperType;
8491}
8492
8494 const auto *TT = T->castAs<TypedefType>();
8495 CFConstantStringTypeDecl = cast<TypedefDecl>(TT->getDecl());
8496 CFConstantStringTagDecl = TT->castAsRecordDecl();
8497}
8498
8500 if (BlockDescriptorType)
8501 return getCanonicalTagType(BlockDescriptorType);
8502
8503 RecordDecl *RD;
8504 // FIXME: Needs the FlagAppleBlock bit.
8505 RD = buildImplicitRecord("__block_descriptor");
8506 RD->startDefinition();
8507
8508 QualType FieldTypes[] = {
8511 };
8512
8513 static const char *const FieldNames[] = {
8514 "reserved",
8515 "Size"
8516 };
8517
8518 for (size_t i = 0; i < 2; ++i) {
8520 *this, RD, SourceLocation(), SourceLocation(),
8521 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8522 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8523 Field->setAccess(AS_public);
8524 RD->addDecl(Field);
8525 }
8526
8527 RD->completeDefinition();
8528
8529 BlockDescriptorType = RD;
8530
8531 return getCanonicalTagType(BlockDescriptorType);
8532}
8533
8535 if (BlockDescriptorExtendedType)
8536 return getCanonicalTagType(BlockDescriptorExtendedType);
8537
8538 RecordDecl *RD;
8539 // FIXME: Needs the FlagAppleBlock bit.
8540 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
8541 RD->startDefinition();
8542
8543 QualType FieldTypes[] = {
8548 };
8549
8550 static const char *const FieldNames[] = {
8551 "reserved",
8552 "Size",
8553 "CopyFuncPtr",
8554 "DestroyFuncPtr"
8555 };
8556
8557 for (size_t i = 0; i < 4; ++i) {
8559 *this, RD, SourceLocation(), SourceLocation(),
8560 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8561 /*BitWidth=*/nullptr,
8562 /*Mutable=*/false, ICIS_NoInit);
8563 Field->setAccess(AS_public);
8564 RD->addDecl(Field);
8565 }
8566
8567 RD->completeDefinition();
8568
8569 BlockDescriptorExtendedType = RD;
8570 return getCanonicalTagType(BlockDescriptorExtendedType);
8571}
8572
8574 const auto *BT = dyn_cast<BuiltinType>(T);
8575
8576 if (!BT) {
8577 if (isa<PipeType>(T))
8578 return OCLTK_Pipe;
8579
8580 return OCLTK_Default;
8581 }
8582
8583 switch (BT->getKind()) {
8584#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8585 case BuiltinType::Id: \
8586 return OCLTK_Image;
8587#include "clang/Basic/OpenCLImageTypes.def"
8588
8589 case BuiltinType::OCLClkEvent:
8590 return OCLTK_ClkEvent;
8591
8592 case BuiltinType::OCLEvent:
8593 return OCLTK_Event;
8594
8595 case BuiltinType::OCLQueue:
8596 return OCLTK_Queue;
8597
8598 case BuiltinType::OCLReserveID:
8599 return OCLTK_ReserveID;
8600
8601 case BuiltinType::OCLSampler:
8602 return OCLTK_Sampler;
8603
8604 default:
8605 return OCLTK_Default;
8606 }
8607}
8608
8610 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
8611}
8612
8613/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
8614/// requires copy/dispose. Note that this must match the logic
8615/// in buildByrefHelpers.
8617 const VarDecl *D) {
8618 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
8619 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
8620 if (!copyExpr && record->hasTrivialDestructor()) return false;
8621
8622 return true;
8623 }
8624
8626 return true;
8627
8628 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
8629 // move or destroy.
8631 return true;
8632
8633 if (!Ty->isObjCRetainableType()) return false;
8634
8635 Qualifiers qs = Ty.getQualifiers();
8636
8637 // If we have lifetime, that dominates.
8638 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
8639 switch (lifetime) {
8640 case Qualifiers::OCL_None: llvm_unreachable("impossible");
8641
8642 // These are just bits as far as the runtime is concerned.
8645 return false;
8646
8647 // These cases should have been taken care of when checking the type's
8648 // non-triviality.
8651 llvm_unreachable("impossible");
8652 }
8653 llvm_unreachable("fell out of lifetime switch!");
8654 }
8655 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
8657}
8658
8660 Qualifiers::ObjCLifetime &LifeTime,
8661 bool &HasByrefExtendedLayout) const {
8662 if (!getLangOpts().ObjC ||
8663 getLangOpts().getGC() != LangOptions::NonGC)
8664 return false;
8665
8666 HasByrefExtendedLayout = false;
8667 if (Ty->isRecordType()) {
8668 HasByrefExtendedLayout = true;
8669 LifeTime = Qualifiers::OCL_None;
8670 } else if ((LifeTime = Ty.getObjCLifetime())) {
8671 // Honor the ARC qualifiers.
8672 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
8673 // The MRR rule.
8675 } else {
8676 LifeTime = Qualifiers::OCL_None;
8677 }
8678 return true;
8679}
8680
8682 assert(Target && "Expected target to be initialized");
8683 const llvm::Triple &T = Target->getTriple();
8684 // Windows is LLP64 rather than LP64
8685 if (T.isOSWindows() && T.isArch64Bit())
8686 return UnsignedLongLongTy;
8687 return UnsignedLongTy;
8688}
8689
8691 assert(Target && "Expected target to be initialized");
8692 const llvm::Triple &T = Target->getTriple();
8693 // Windows is LLP64 rather than LP64
8694 if (T.isOSWindows() && T.isArch64Bit())
8695 return LongLongTy;
8696 return LongTy;
8697}
8698
8700 if (!ObjCInstanceTypeDecl)
8701 ObjCInstanceTypeDecl =
8702 buildImplicitTypedef(getObjCIdType(), "instancetype");
8703 return ObjCInstanceTypeDecl;
8704}
8705
8706// This returns true if a type has been typedefed to BOOL:
8707// typedef <type> BOOL;
8709 if (const auto *TT = dyn_cast<TypedefType>(T))
8710 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
8711 return II->isStr("BOOL");
8712
8713 return false;
8714}
8715
8716/// getObjCEncodingTypeSize returns size of type for objective-c encoding
8717/// purpose.
8719 if (!type->isIncompleteArrayType() && type->isIncompleteType())
8720 return CharUnits::Zero();
8721
8723
8724 // Make all integer and enum types at least as large as an int
8725 if (sz.isPositive() && type->isIntegralOrEnumerationType())
8726 sz = std::max(sz, getTypeSizeInChars(IntTy));
8727 // Treat arrays as pointers, since that's how they're passed in.
8728 else if (type->isArrayType())
8730 return sz;
8731}
8732
8739
8742 if (!VD->isInline())
8744
8745 // In almost all cases, it's a weak definition.
8746 auto *First = VD->getFirstDecl();
8747 if (First->isInlineSpecified() || !First->isStaticDataMember())
8749
8750 // If there's a file-context declaration in this translation unit, it's a
8751 // non-discardable definition.
8752 for (auto *D : VD->redecls())
8754 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
8756
8757 // If we've not seen one yet, we don't know.
8759}
8760
8761static std::string charUnitsToString(const CharUnits &CU) {
8762 return llvm::itostr(CU.getQuantity());
8763}
8764
8765/// getObjCEncodingForBlock - Return the encoded type for this block
8766/// declaration.
8768 std::string S;
8769
8770 const BlockDecl *Decl = Expr->getBlockDecl();
8771 QualType BlockTy =
8773 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
8774 // Encode result type.
8775 if (getLangOpts().EncodeExtendedBlockSig)
8777 true /*Extended*/);
8778 else
8779 getObjCEncodingForType(BlockReturnTy, S);
8780 // Compute size of all parameters.
8781 // Start with computing size of a pointer in number of bytes.
8782 // FIXME: There might(should) be a better way of doing this computation!
8784 CharUnits ParmOffset = PtrSize;
8785 for (auto *PI : Decl->parameters()) {
8786 QualType PType = PI->getType();
8788 if (sz.isZero())
8789 continue;
8790 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
8791 ParmOffset += sz;
8792 }
8793 // Size of the argument frame
8794 S += charUnitsToString(ParmOffset);
8795 // Block pointer and offset.
8796 S += "@?0";
8797
8798 // Argument types.
8799 ParmOffset = PtrSize;
8800 for (auto *PVDecl : Decl->parameters()) {
8801 QualType PType = PVDecl->getOriginalType();
8802 if (const auto *AT =
8803 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8804 // Use array's original type only if it has known number of
8805 // elements.
8806 if (!isa<ConstantArrayType>(AT))
8807 PType = PVDecl->getType();
8808 } else if (PType->isFunctionType())
8809 PType = PVDecl->getType();
8810 if (getLangOpts().EncodeExtendedBlockSig)
8812 S, true /*Extended*/);
8813 else
8814 getObjCEncodingForType(PType, S);
8815 S += charUnitsToString(ParmOffset);
8816 ParmOffset += getObjCEncodingTypeSize(PType);
8817 }
8818
8819 return S;
8820}
8821
8822std::string
8824 std::string S;
8825 // Encode result type.
8826 getObjCEncodingForType(Decl->getReturnType(), S);
8827 CharUnits ParmOffset;
8828 // Compute size of all parameters.
8829 for (auto *PI : Decl->parameters()) {
8830 QualType PType = PI->getType();
8832 if (sz.isZero())
8833 continue;
8834
8835 assert(sz.isPositive() &&
8836 "getObjCEncodingForFunctionDecl - Incomplete param type");
8837 ParmOffset += sz;
8838 }
8839 S += charUnitsToString(ParmOffset);
8840 ParmOffset = CharUnits::Zero();
8841
8842 // Argument types.
8843 for (auto *PVDecl : Decl->parameters()) {
8844 QualType PType = PVDecl->getOriginalType();
8845 if (const auto *AT =
8846 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8847 // Use array's original type only if it has known number of
8848 // elements.
8849 if (!isa<ConstantArrayType>(AT))
8850 PType = PVDecl->getType();
8851 } else if (PType->isFunctionType())
8852 PType = PVDecl->getType();
8853 getObjCEncodingForType(PType, S);
8854 S += charUnitsToString(ParmOffset);
8855 ParmOffset += getObjCEncodingTypeSize(PType);
8856 }
8857
8858 return S;
8859}
8860
8861/// getObjCEncodingForMethodParameter - Return the encoded type for a single
8862/// method parameter or return type. If Extended, include class names and
8863/// block object types.
8865 QualType T, std::string& S,
8866 bool Extended) const {
8867 // Encode type qualifier, 'in', 'inout', etc. for the parameter.
8869 // Encode parameter type.
8870 ObjCEncOptions Options = ObjCEncOptions()
8871 .setExpandPointedToStructures()
8872 .setExpandStructures()
8873 .setIsOutermostType();
8874 if (Extended)
8875 Options.setEncodeBlockParameters().setEncodeClassNames();
8876 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
8877}
8878
8879/// getObjCEncodingForMethodDecl - Return the encoded type for this method
8880/// declaration.
8882 bool Extended) const {
8883 // FIXME: This is not very efficient.
8884 // Encode return type.
8885 std::string S;
8886 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
8887 Decl->getReturnType(), S, Extended);
8888 // Compute size of all parameters.
8889 // Start with computing size of a pointer in number of bytes.
8890 // FIXME: There might(should) be a better way of doing this computation!
8892 // The first two arguments (self and _cmd) are pointers; account for
8893 // their size.
8894 CharUnits ParmOffset = 2 * PtrSize;
8895 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8896 E = Decl->sel_param_end(); PI != E; ++PI) {
8897 QualType PType = (*PI)->getType();
8899 if (sz.isZero())
8900 continue;
8901
8902 assert(sz.isPositive() &&
8903 "getObjCEncodingForMethodDecl - Incomplete param type");
8904 ParmOffset += sz;
8905 }
8906 S += charUnitsToString(ParmOffset);
8907 S += "@0:";
8908 S += charUnitsToString(PtrSize);
8909
8910 // Argument types.
8911 ParmOffset = 2 * PtrSize;
8912 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8913 E = Decl->sel_param_end(); PI != E; ++PI) {
8914 const ParmVarDecl *PVDecl = *PI;
8915 QualType PType = PVDecl->getOriginalType();
8916 if (const auto *AT =
8917 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8918 // Use array's original type only if it has known number of
8919 // elements.
8920 if (!isa<ConstantArrayType>(AT))
8921 PType = PVDecl->getType();
8922 } else if (PType->isFunctionType())
8923 PType = PVDecl->getType();
8925 PType, S, Extended);
8926 S += charUnitsToString(ParmOffset);
8927 ParmOffset += getObjCEncodingTypeSize(PType);
8928 }
8929
8930 return S;
8931}
8932
8935 const ObjCPropertyDecl *PD,
8936 const Decl *Container) const {
8937 if (!Container)
8938 return nullptr;
8939 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
8940 for (auto *PID : CID->property_impls())
8941 if (PID->getPropertyDecl() == PD)
8942 return PID;
8943 } else {
8944 const auto *OID = cast<ObjCImplementationDecl>(Container);
8945 for (auto *PID : OID->property_impls())
8946 if (PID->getPropertyDecl() == PD)
8947 return PID;
8948 }
8949 return nullptr;
8950}
8951
8952/// getObjCEncodingForPropertyDecl - Return the encoded type for this
8953/// property declaration. If non-NULL, Container must be either an
8954/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
8955/// NULL when getting encodings for protocol properties.
8956/// Property attributes are stored as a comma-delimited C string. The simple
8957/// attributes readonly and bycopy are encoded as single characters. The
8958/// parametrized attributes, getter=name, setter=name, and ivar=name, are
8959/// encoded as single characters, followed by an identifier. Property types
8960/// are also encoded as a parametrized attribute. The characters used to encode
8961/// these attributes are defined by the following enumeration:
8962/// @code
8963/// enum PropertyAttributes {
8964/// kPropertyReadOnly = 'R', // property is read-only.
8965/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
8966/// kPropertyByref = '&', // property is a reference to the value last assigned
8967/// kPropertyDynamic = 'D', // property is dynamic
8968/// kPropertyGetter = 'G', // followed by getter selector name
8969/// kPropertySetter = 'S', // followed by setter selector name
8970/// kPropertyInstanceVariable = 'V' // followed by instance variable name
8971/// kPropertyType = 'T' // followed by old-style type encoding.
8972/// kPropertyWeak = 'W' // 'weak' property
8973/// kPropertyStrong = 'P' // property GC'able
8974/// kPropertyNonAtomic = 'N' // property non-atomic
8975/// kPropertyOptional = '?' // property optional
8976/// };
8977/// @endcode
8978std::string
8980 const Decl *Container) const {
8981 // Collect information from the property implementation decl(s).
8982 bool Dynamic = false;
8983 ObjCPropertyImplDecl *SynthesizePID = nullptr;
8984
8985 if (ObjCPropertyImplDecl *PropertyImpDecl =
8987 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
8988 Dynamic = true;
8989 else
8990 SynthesizePID = PropertyImpDecl;
8991 }
8992
8993 // FIXME: This is not very efficient.
8994 std::string S = "T";
8995
8996 // Encode result type.
8997 // GCC has some special rules regarding encoding of properties which
8998 // closely resembles encoding of ivars.
9000
9001 if (PD->isOptional())
9002 S += ",?";
9003
9004 if (PD->isReadOnly()) {
9005 S += ",R";
9007 S += ",C";
9009 S += ",&";
9011 S += ",W";
9012 } else {
9013 switch (PD->getSetterKind()) {
9014 case ObjCPropertyDecl::Assign: break;
9015 case ObjCPropertyDecl::Copy: S += ",C"; break;
9016 case ObjCPropertyDecl::Retain: S += ",&"; break;
9017 case ObjCPropertyDecl::Weak: S += ",W"; break;
9018 }
9019 }
9020
9021 // It really isn't clear at all what this means, since properties
9022 // are "dynamic by default".
9023 if (Dynamic)
9024 S += ",D";
9025
9027 S += ",N";
9028
9030 S += ",G";
9031 S += PD->getGetterName().getAsString();
9032 }
9033
9035 S += ",S";
9036 S += PD->getSetterName().getAsString();
9037 }
9038
9039 if (SynthesizePID) {
9040 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
9041 S += ",V";
9042 S += OID->getNameAsString();
9043 }
9044
9045 // FIXME: OBJCGC: weak & strong
9046 return S;
9047}
9048
9049/// getLegacyIntegralTypeEncoding -
9050/// Another legacy compatibility encoding: 32-bit longs are encoded as
9051/// 'l' or 'L' , but not always. For typedefs, we need to use
9052/// 'i' or 'I' instead if encoding a struct field, or a pointer!
9054 if (PointeeTy->getAs<TypedefType>()) {
9055 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
9056 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
9057 PointeeTy = UnsignedIntTy;
9058 else
9059 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
9060 PointeeTy = IntTy;
9061 }
9062 }
9063}
9064
9066 const FieldDecl *Field,
9067 QualType *NotEncodedT) const {
9068 // We follow the behavior of gcc, expanding structures which are
9069 // directly pointed to, and expanding embedded structures. Note that
9070 // these rules are sufficient to prevent recursive encoding of the
9071 // same type.
9072 getObjCEncodingForTypeImpl(T, S,
9073 ObjCEncOptions()
9074 .setExpandPointedToStructures()
9075 .setExpandStructures()
9076 .setIsOutermostType(),
9077 Field, NotEncodedT);
9078}
9079
9081 std::string& S) const {
9082 // Encode result type.
9083 // GCC has some special rules regarding encoding of properties which
9084 // closely resembles encoding of ivars.
9085 getObjCEncodingForTypeImpl(T, S,
9086 ObjCEncOptions()
9087 .setExpandPointedToStructures()
9088 .setExpandStructures()
9089 .setIsOutermostType()
9090 .setEncodingProperty(),
9091 /*Field=*/nullptr);
9092}
9093
9095 const BuiltinType *BT) {
9096 BuiltinType::Kind kind = BT->getKind();
9097 switch (kind) {
9098 case BuiltinType::Void: return 'v';
9099 case BuiltinType::Bool: return 'B';
9100 case BuiltinType::Char8:
9101 case BuiltinType::Char_U:
9102 case BuiltinType::UChar: return 'C';
9103 case BuiltinType::Char16:
9104 case BuiltinType::UShort: return 'S';
9105 case BuiltinType::Char32:
9106 case BuiltinType::UInt: return 'I';
9107 case BuiltinType::ULong:
9108 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
9109 case BuiltinType::UInt128: return 'T';
9110 case BuiltinType::ULongLong: return 'Q';
9111 case BuiltinType::Char_S:
9112 case BuiltinType::SChar: return 'c';
9113 case BuiltinType::Short: return 's';
9114 case BuiltinType::WChar_S:
9115 case BuiltinType::WChar_U:
9116 case BuiltinType::Int: return 'i';
9117 case BuiltinType::Long:
9118 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
9119 case BuiltinType::LongLong: return 'q';
9120 case BuiltinType::Int128: return 't';
9121 case BuiltinType::Float: return 'f';
9122 case BuiltinType::Double: return 'd';
9123 case BuiltinType::LongDouble: return 'D';
9124 case BuiltinType::NullPtr: return '*'; // like char*
9125
9126 case BuiltinType::BFloat16:
9127 case BuiltinType::Float16:
9128 case BuiltinType::Float128:
9129 case BuiltinType::Ibm128:
9130 case BuiltinType::Half:
9131 case BuiltinType::ShortAccum:
9132 case BuiltinType::Accum:
9133 case BuiltinType::LongAccum:
9134 case BuiltinType::UShortAccum:
9135 case BuiltinType::UAccum:
9136 case BuiltinType::ULongAccum:
9137 case BuiltinType::ShortFract:
9138 case BuiltinType::Fract:
9139 case BuiltinType::LongFract:
9140 case BuiltinType::UShortFract:
9141 case BuiltinType::UFract:
9142 case BuiltinType::ULongFract:
9143 case BuiltinType::SatShortAccum:
9144 case BuiltinType::SatAccum:
9145 case BuiltinType::SatLongAccum:
9146 case BuiltinType::SatUShortAccum:
9147 case BuiltinType::SatUAccum:
9148 case BuiltinType::SatULongAccum:
9149 case BuiltinType::SatShortFract:
9150 case BuiltinType::SatFract:
9151 case BuiltinType::SatLongFract:
9152 case BuiltinType::SatUShortFract:
9153 case BuiltinType::SatUFract:
9154 case BuiltinType::SatULongFract:
9155 // FIXME: potentially need @encodes for these!
9156 return ' ';
9157
9158#define SVE_TYPE(Name, Id, SingletonId) \
9159 case BuiltinType::Id:
9160#include "clang/Basic/AArch64ACLETypes.def"
9161#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9162#include "clang/Basic/RISCVVTypes.def"
9163#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9164#include "clang/Basic/WebAssemblyReferenceTypes.def"
9165#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
9166#include "clang/Basic/AMDGPUTypes.def"
9167 {
9168 DiagnosticsEngine &Diags = C->getDiagnostics();
9169 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
9170 "cannot yet @encode type %0");
9171 Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
9172 return ' ';
9173 }
9174
9175 case BuiltinType::ObjCId:
9176 case BuiltinType::ObjCClass:
9177 case BuiltinType::ObjCSel:
9178 llvm_unreachable("@encoding ObjC primitive type");
9179
9180 // OpenCL and placeholder types don't need @encodings.
9181#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
9182 case BuiltinType::Id:
9183#include "clang/Basic/OpenCLImageTypes.def"
9184#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
9185 case BuiltinType::Id:
9186#include "clang/Basic/OpenCLExtensionTypes.def"
9187 case BuiltinType::OCLEvent:
9188 case BuiltinType::OCLClkEvent:
9189 case BuiltinType::OCLQueue:
9190 case BuiltinType::OCLReserveID:
9191 case BuiltinType::OCLSampler:
9192 case BuiltinType::Dependent:
9193#define PPC_VECTOR_TYPE(Name, Id, Size) \
9194 case BuiltinType::Id:
9195#include "clang/Basic/PPCTypes.def"
9196#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9197#include "clang/Basic/HLSLIntangibleTypes.def"
9198#define BUILTIN_TYPE(KIND, ID)
9199#define PLACEHOLDER_TYPE(KIND, ID) \
9200 case BuiltinType::KIND:
9201#include "clang/AST/BuiltinTypes.def"
9202 llvm_unreachable("invalid builtin type for @encode");
9203 }
9204 llvm_unreachable("invalid BuiltinType::Kind value");
9205}
9206
9207static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED) {
9209
9210 // The encoding of an non-fixed enum type is always 'i', regardless of size.
9211 if (!Enum->isFixed())
9212 return 'i';
9213
9214 // The encoding of a fixed enum type matches its fixed underlying type.
9215 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
9217}
9218
9219static void EncodeBitField(const ASTContext *Ctx, std::string& S,
9220 QualType T, const FieldDecl *FD) {
9221 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
9222 S += 'b';
9223 // The NeXT runtime encodes bit fields as b followed by the number of bits.
9224 // The GNU runtime requires more information; bitfields are encoded as b,
9225 // then the offset (in bits) of the first element, then the type of the
9226 // bitfield, then the size in bits. For example, in this structure:
9227 //
9228 // struct
9229 // {
9230 // int integer;
9231 // int flags:2;
9232 // };
9233 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
9234 // runtime, but b32i2 for the GNU runtime. The reason for this extra
9235 // information is not especially sensible, but we're stuck with it for
9236 // compatibility with GCC, although providing it breaks anything that
9237 // actually uses runtime introspection and wants to work on both runtimes...
9238 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
9239 uint64_t Offset;
9240
9241 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
9242 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), IVD);
9243 } else {
9244 const RecordDecl *RD = FD->getParent();
9245 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
9246 Offset = RL.getFieldOffset(FD->getFieldIndex());
9247 }
9248
9249 S += llvm::utostr(Offset);
9250
9251 if (const auto *ET = T->getAsCanonical<EnumType>())
9252 S += ObjCEncodingForEnumDecl(Ctx, ET->getOriginalDecl());
9253 else {
9254 const auto *BT = T->castAs<BuiltinType>();
9255 S += getObjCEncodingForPrimitiveType(Ctx, BT);
9256 }
9257 }
9258 S += llvm::utostr(FD->getBitWidthValue());
9259}
9260
9261// Helper function for determining whether the encoded type string would include
9262// a template specialization type.
9264 bool VisitBasesAndFields) {
9265 T = T->getBaseElementTypeUnsafe();
9266
9267 if (auto *PT = T->getAs<PointerType>())
9269 PT->getPointeeType().getTypePtr(), false);
9270
9271 auto *CXXRD = T->getAsCXXRecordDecl();
9272
9273 if (!CXXRD)
9274 return false;
9275
9277 return true;
9278
9279 if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
9280 return false;
9281
9282 for (const auto &B : CXXRD->bases())
9283 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
9284 true))
9285 return true;
9286
9287 for (auto *FD : CXXRD->fields())
9288 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
9289 true))
9290 return true;
9291
9292 return false;
9293}
9294
9295// FIXME: Use SmallString for accumulating string.
9296void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
9297 const ObjCEncOptions Options,
9298 const FieldDecl *FD,
9299 QualType *NotEncodedT) const {
9301 switch (CT->getTypeClass()) {
9302 case Type::Builtin:
9303 case Type::Enum:
9304 if (FD && FD->isBitField())
9305 return EncodeBitField(this, S, T, FD);
9306 if (const auto *BT = dyn_cast<BuiltinType>(CT))
9307 S += getObjCEncodingForPrimitiveType(this, BT);
9308 else
9309 S += ObjCEncodingForEnumDecl(this, cast<EnumType>(CT)->getOriginalDecl());
9310 return;
9311
9312 case Type::Complex:
9313 S += 'j';
9314 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
9315 ObjCEncOptions(),
9316 /*Field=*/nullptr);
9317 return;
9318
9319 case Type::Atomic:
9320 S += 'A';
9321 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
9322 ObjCEncOptions(),
9323 /*Field=*/nullptr);
9324 return;
9325
9326 // encoding for pointer or reference types.
9327 case Type::Pointer:
9328 case Type::LValueReference:
9329 case Type::RValueReference: {
9330 QualType PointeeTy;
9331 if (isa<PointerType>(CT)) {
9332 const auto *PT = T->castAs<PointerType>();
9333 if (PT->isObjCSelType()) {
9334 S += ':';
9335 return;
9336 }
9337 PointeeTy = PT->getPointeeType();
9338 } else {
9339 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
9340 }
9341
9342 bool isReadOnly = false;
9343 // For historical/compatibility reasons, the read-only qualifier of the
9344 // pointee gets emitted _before_ the '^'. The read-only qualifier of
9345 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
9346 // Also, do not emit the 'r' for anything but the outermost type!
9347 if (T->getAs<TypedefType>()) {
9348 if (Options.IsOutermostType() && T.isConstQualified()) {
9349 isReadOnly = true;
9350 S += 'r';
9351 }
9352 } else if (Options.IsOutermostType()) {
9353 QualType P = PointeeTy;
9354 while (auto PT = P->getAs<PointerType>())
9355 P = PT->getPointeeType();
9356 if (P.isConstQualified()) {
9357 isReadOnly = true;
9358 S += 'r';
9359 }
9360 }
9361 if (isReadOnly) {
9362 // Another legacy compatibility encoding. Some ObjC qualifier and type
9363 // combinations need to be rearranged.
9364 // Rewrite "in const" from "nr" to "rn"
9365 if (StringRef(S).ends_with("nr"))
9366 S.replace(S.end()-2, S.end(), "rn");
9367 }
9368
9369 if (PointeeTy->isCharType()) {
9370 // char pointer types should be encoded as '*' unless it is a
9371 // type that has been typedef'd to 'BOOL'.
9372 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
9373 S += '*';
9374 return;
9375 }
9376 } else if (const auto *RTy = PointeeTy->getAsCanonical<RecordType>()) {
9377 const IdentifierInfo *II = RTy->getOriginalDecl()->getIdentifier();
9378 // GCC binary compat: Need to convert "struct objc_class *" to "#".
9379 if (II == &Idents.get("objc_class")) {
9380 S += '#';
9381 return;
9382 }
9383 // GCC binary compat: Need to convert "struct objc_object *" to "@".
9384 if (II == &Idents.get("objc_object")) {
9385 S += '@';
9386 return;
9387 }
9388 // If the encoded string for the class includes template names, just emit
9389 // "^v" for pointers to the class.
9390 if (getLangOpts().CPlusPlus &&
9391 (!getLangOpts().EncodeCXXClassTemplateSpec &&
9393 RTy, Options.ExpandPointedToStructures()))) {
9394 S += "^v";
9395 return;
9396 }
9397 // fall through...
9398 }
9399 S += '^';
9401
9402 ObjCEncOptions NewOptions;
9403 if (Options.ExpandPointedToStructures())
9404 NewOptions.setExpandStructures();
9405 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
9406 /*Field=*/nullptr, NotEncodedT);
9407 return;
9408 }
9409
9410 case Type::ConstantArray:
9411 case Type::IncompleteArray:
9412 case Type::VariableArray: {
9413 const auto *AT = cast<ArrayType>(CT);
9414
9415 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
9416 // Incomplete arrays are encoded as a pointer to the array element.
9417 S += '^';
9418
9419 getObjCEncodingForTypeImpl(
9420 AT->getElementType(), S,
9421 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
9422 } else {
9423 S += '[';
9424
9425 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
9426 S += llvm::utostr(CAT->getZExtSize());
9427 else {
9428 //Variable length arrays are encoded as a regular array with 0 elements.
9430 "Unknown array type!");
9431 S += '0';
9432 }
9433
9434 getObjCEncodingForTypeImpl(
9435 AT->getElementType(), S,
9436 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
9437 NotEncodedT);
9438 S += ']';
9439 }
9440 return;
9441 }
9442
9443 case Type::FunctionNoProto:
9444 case Type::FunctionProto:
9445 S += '?';
9446 return;
9447
9448 case Type::Record: {
9449 RecordDecl *RDecl = cast<RecordType>(CT)->getOriginalDecl();
9450 S += RDecl->isUnion() ? '(' : '{';
9451 // Anonymous structures print as '?'
9452 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
9453 S += II->getName();
9454 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
9455 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
9456 llvm::raw_string_ostream OS(S);
9457 printTemplateArgumentList(OS, TemplateArgs.asArray(),
9459 }
9460 } else {
9461 S += '?';
9462 }
9463 if (Options.ExpandStructures()) {
9464 S += '=';
9465 if (!RDecl->isUnion()) {
9466 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
9467 } else {
9468 for (const auto *Field : RDecl->fields()) {
9469 if (FD) {
9470 S += '"';
9471 S += Field->getNameAsString();
9472 S += '"';
9473 }
9474
9475 // Special case bit-fields.
9476 if (Field->isBitField()) {
9477 getObjCEncodingForTypeImpl(Field->getType(), S,
9478 ObjCEncOptions().setExpandStructures(),
9479 Field);
9480 } else {
9481 QualType qt = Field->getType();
9483 getObjCEncodingForTypeImpl(
9484 qt, S,
9485 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
9486 NotEncodedT);
9487 }
9488 }
9489 }
9490 }
9491 S += RDecl->isUnion() ? ')' : '}';
9492 return;
9493 }
9494
9495 case Type::BlockPointer: {
9496 const auto *BT = T->castAs<BlockPointerType>();
9497 S += "@?"; // Unlike a pointer-to-function, which is "^?".
9498 if (Options.EncodeBlockParameters()) {
9499 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
9500
9501 S += '<';
9502 // Block return type
9503 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
9504 Options.forComponentType(), FD, NotEncodedT);
9505 // Block self
9506 S += "@?";
9507 // Block parameters
9508 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
9509 for (const auto &I : FPT->param_types())
9510 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
9511 NotEncodedT);
9512 }
9513 S += '>';
9514 }
9515 return;
9516 }
9517
9518 case Type::ObjCObject: {
9519 // hack to match legacy encoding of *id and *Class
9520 QualType Ty = getObjCObjectPointerType(CT);
9521 if (Ty->isObjCIdType()) {
9522 S += "{objc_object=}";
9523 return;
9524 }
9525 else if (Ty->isObjCClassType()) {
9526 S += "{objc_class=}";
9527 return;
9528 }
9529 // TODO: Double check to make sure this intentionally falls through.
9530 [[fallthrough]];
9531 }
9532
9533 case Type::ObjCInterface: {
9534 // Ignore protocol qualifiers when mangling at this level.
9535 // @encode(class_name)
9536 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
9537 S += '{';
9538 S += OI->getObjCRuntimeNameAsString();
9539 if (Options.ExpandStructures()) {
9540 S += '=';
9541 SmallVector<const ObjCIvarDecl*, 32> Ivars;
9542 DeepCollectObjCIvars(OI, true, Ivars);
9543 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
9544 const FieldDecl *Field = Ivars[i];
9545 if (Field->isBitField())
9546 getObjCEncodingForTypeImpl(Field->getType(), S,
9547 ObjCEncOptions().setExpandStructures(),
9548 Field);
9549 else
9550 getObjCEncodingForTypeImpl(Field->getType(), S,
9551 ObjCEncOptions().setExpandStructures(), FD,
9552 NotEncodedT);
9553 }
9554 }
9555 S += '}';
9556 return;
9557 }
9558
9559 case Type::ObjCObjectPointer: {
9560 const auto *OPT = T->castAs<ObjCObjectPointerType>();
9561 if (OPT->isObjCIdType()) {
9562 S += '@';
9563 return;
9564 }
9565
9566 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
9567 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
9568 // Since this is a binary compatibility issue, need to consult with
9569 // runtime folks. Fortunately, this is a *very* obscure construct.
9570 S += '#';
9571 return;
9572 }
9573
9574 if (OPT->isObjCQualifiedIdType()) {
9575 getObjCEncodingForTypeImpl(
9576 getObjCIdType(), S,
9577 Options.keepingOnly(ObjCEncOptions()
9578 .setExpandPointedToStructures()
9579 .setExpandStructures()),
9580 FD);
9581 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
9582 // Note that we do extended encoding of protocol qualifier list
9583 // Only when doing ivar or property encoding.
9584 S += '"';
9585 for (const auto *I : OPT->quals()) {
9586 S += '<';
9587 S += I->getObjCRuntimeNameAsString();
9588 S += '>';
9589 }
9590 S += '"';
9591 }
9592 return;
9593 }
9594
9595 S += '@';
9596 if (OPT->getInterfaceDecl() &&
9597 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
9598 S += '"';
9599 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
9600 for (const auto *I : OPT->quals()) {
9601 S += '<';
9602 S += I->getObjCRuntimeNameAsString();
9603 S += '>';
9604 }
9605 S += '"';
9606 }
9607 return;
9608 }
9609
9610 // gcc just blithely ignores member pointers.
9611 // FIXME: we should do better than that. 'M' is available.
9612 case Type::MemberPointer:
9613 // This matches gcc's encoding, even though technically it is insufficient.
9614 //FIXME. We should do a better job than gcc.
9615 case Type::Vector:
9616 case Type::ExtVector:
9617 // Until we have a coherent encoding of these three types, issue warning.
9618 if (NotEncodedT)
9619 *NotEncodedT = T;
9620 return;
9621
9622 case Type::ConstantMatrix:
9623 if (NotEncodedT)
9624 *NotEncodedT = T;
9625 return;
9626
9627 case Type::BitInt:
9628 if (NotEncodedT)
9629 *NotEncodedT = T;
9630 return;
9631
9632 // We could see an undeduced auto type here during error recovery.
9633 // Just ignore it.
9634 case Type::Auto:
9635 case Type::DeducedTemplateSpecialization:
9636 return;
9637
9638 case Type::HLSLAttributedResource:
9639 case Type::HLSLInlineSpirv:
9640 llvm_unreachable("unexpected type");
9641
9642 case Type::ArrayParameter:
9643 case Type::Pipe:
9644#define ABSTRACT_TYPE(KIND, BASE)
9645#define TYPE(KIND, BASE)
9646#define DEPENDENT_TYPE(KIND, BASE) \
9647 case Type::KIND:
9648#define NON_CANONICAL_TYPE(KIND, BASE) \
9649 case Type::KIND:
9650#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
9651 case Type::KIND:
9652#include "clang/AST/TypeNodes.inc"
9653 llvm_unreachable("@encode for dependent type!");
9654 }
9655 llvm_unreachable("bad type kind!");
9656}
9657
9658void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
9659 std::string &S,
9660 const FieldDecl *FD,
9661 bool includeVBases,
9662 QualType *NotEncodedT) const {
9663 assert(RDecl && "Expected non-null RecordDecl");
9664 assert(!RDecl->isUnion() && "Should not be called for unions");
9665 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
9666 return;
9667
9668 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
9669 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
9670 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
9671
9672 if (CXXRec) {
9673 for (const auto &BI : CXXRec->bases()) {
9674 if (!BI.isVirtual()) {
9675 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9676 if (base->isEmpty())
9677 continue;
9678 uint64_t offs = toBits(layout.getBaseClassOffset(base));
9679 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9680 std::make_pair(offs, base));
9681 }
9682 }
9683 }
9684
9685 for (FieldDecl *Field : RDecl->fields()) {
9686 if (!Field->isZeroLengthBitField() && Field->isZeroSize(*this))
9687 continue;
9688 uint64_t offs = layout.getFieldOffset(Field->getFieldIndex());
9689 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9690 std::make_pair(offs, Field));
9691 }
9692
9693 if (CXXRec && includeVBases) {
9694 for (const auto &BI : CXXRec->vbases()) {
9695 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9696 if (base->isEmpty())
9697 continue;
9698 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
9699 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
9700 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
9701 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
9702 std::make_pair(offs, base));
9703 }
9704 }
9705
9706 CharUnits size;
9707 if (CXXRec) {
9708 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
9709 } else {
9710 size = layout.getSize();
9711 }
9712
9713#ifndef NDEBUG
9714 uint64_t CurOffs = 0;
9715#endif
9716 std::multimap<uint64_t, NamedDecl *>::iterator
9717 CurLayObj = FieldOrBaseOffsets.begin();
9718
9719 if (CXXRec && CXXRec->isDynamicClass() &&
9720 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
9721 if (FD) {
9722 S += "\"_vptr$";
9723 std::string recname = CXXRec->getNameAsString();
9724 if (recname.empty()) recname = "?";
9725 S += recname;
9726 S += '"';
9727 }
9728 S += "^^?";
9729#ifndef NDEBUG
9730 CurOffs += getTypeSize(VoidPtrTy);
9731#endif
9732 }
9733
9734 if (!RDecl->hasFlexibleArrayMember()) {
9735 // Mark the end of the structure.
9736 uint64_t offs = toBits(size);
9737 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9738 std::make_pair(offs, nullptr));
9739 }
9740
9741 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
9742#ifndef NDEBUG
9743 assert(CurOffs <= CurLayObj->first);
9744 if (CurOffs < CurLayObj->first) {
9745 uint64_t padding = CurLayObj->first - CurOffs;
9746 // FIXME: There doesn't seem to be a way to indicate in the encoding that
9747 // packing/alignment of members is different that normal, in which case
9748 // the encoding will be out-of-sync with the real layout.
9749 // If the runtime switches to just consider the size of types without
9750 // taking into account alignment, we could make padding explicit in the
9751 // encoding (e.g. using arrays of chars). The encoding strings would be
9752 // longer then though.
9753 CurOffs += padding;
9754 }
9755#endif
9756
9757 NamedDecl *dcl = CurLayObj->second;
9758 if (!dcl)
9759 break; // reached end of structure.
9760
9761 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
9762 // We expand the bases without their virtual bases since those are going
9763 // in the initial structure. Note that this differs from gcc which
9764 // expands virtual bases each time one is encountered in the hierarchy,
9765 // making the encoding type bigger than it really is.
9766 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
9767 NotEncodedT);
9768 assert(!base->isEmpty());
9769#ifndef NDEBUG
9770 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
9771#endif
9772 } else {
9773 const auto *field = cast<FieldDecl>(dcl);
9774 if (FD) {
9775 S += '"';
9776 S += field->getNameAsString();
9777 S += '"';
9778 }
9779
9780 if (field->isBitField()) {
9781 EncodeBitField(this, S, field->getType(), field);
9782#ifndef NDEBUG
9783 CurOffs += field->getBitWidthValue();
9784#endif
9785 } else {
9786 QualType qt = field->getType();
9788 getObjCEncodingForTypeImpl(
9789 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
9790 FD, NotEncodedT);
9791#ifndef NDEBUG
9792 CurOffs += getTypeSize(field->getType());
9793#endif
9794 }
9795 }
9796 }
9797}
9798
9800 std::string& S) const {
9801 if (QT & Decl::OBJC_TQ_In)
9802 S += 'n';
9803 if (QT & Decl::OBJC_TQ_Inout)
9804 S += 'N';
9805 if (QT & Decl::OBJC_TQ_Out)
9806 S += 'o';
9807 if (QT & Decl::OBJC_TQ_Bycopy)
9808 S += 'O';
9809 if (QT & Decl::OBJC_TQ_Byref)
9810 S += 'R';
9811 if (QT & Decl::OBJC_TQ_Oneway)
9812 S += 'V';
9813}
9814
9816 if (!ObjCIdDecl) {
9819 ObjCIdDecl = buildImplicitTypedef(T, "id");
9820 }
9821 return ObjCIdDecl;
9822}
9823
9825 if (!ObjCSelDecl) {
9827 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
9828 }
9829 return ObjCSelDecl;
9830}
9831
9833 if (!ObjCClassDecl) {
9836 ObjCClassDecl = buildImplicitTypedef(T, "Class");
9837 }
9838 return ObjCClassDecl;
9839}
9840
9842 if (!ObjCProtocolClassDecl) {
9843 ObjCProtocolClassDecl
9846 &Idents.get("Protocol"),
9847 /*typeParamList=*/nullptr,
9848 /*PrevDecl=*/nullptr,
9849 SourceLocation(), true);
9850 }
9851
9852 return ObjCProtocolClassDecl;
9853}
9854
9856 if (!getLangOpts().PointerAuthObjcInterfaceSel)
9857 return PointerAuthQualifier();
9859 getLangOpts().PointerAuthObjcInterfaceSelKey,
9860 /*isAddressDiscriminated=*/true, SelPointerConstantDiscriminator,
9862 /*isIsaPointer=*/false,
9863 /*authenticatesNullValues=*/false);
9864}
9865
9866//===----------------------------------------------------------------------===//
9867// __builtin_va_list Construction Functions
9868//===----------------------------------------------------------------------===//
9869
9871 StringRef Name) {
9872 // typedef char* __builtin[_ms]_va_list;
9873 QualType T = Context->getPointerType(Context->CharTy);
9874 return Context->buildImplicitTypedef(T, Name);
9875}
9876
9878 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
9879}
9880
9882 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
9883}
9884
9886 // typedef void* __builtin_va_list;
9887 QualType T = Context->getPointerType(Context->VoidTy);
9888 return Context->buildImplicitTypedef(T, "__builtin_va_list");
9889}
9890
9891static TypedefDecl *
9893 // struct __va_list
9894 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
9895 if (Context->getLangOpts().CPlusPlus) {
9896 // namespace std { struct __va_list {
9897 auto *NS = NamespaceDecl::Create(
9898 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(),
9899 /*Inline=*/false, SourceLocation(), SourceLocation(),
9900 &Context->Idents.get("std"),
9901 /*PrevDecl=*/nullptr, /*Nested=*/false);
9902 NS->setImplicit();
9904 }
9905
9906 VaListTagDecl->startDefinition();
9907
9908 const size_t NumFields = 5;
9909 QualType FieldTypes[NumFields];
9910 const char *FieldNames[NumFields];
9911
9912 // void *__stack;
9913 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
9914 FieldNames[0] = "__stack";
9915
9916 // void *__gr_top;
9917 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
9918 FieldNames[1] = "__gr_top";
9919
9920 // void *__vr_top;
9921 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9922 FieldNames[2] = "__vr_top";
9923
9924 // int __gr_offs;
9925 FieldTypes[3] = Context->IntTy;
9926 FieldNames[3] = "__gr_offs";
9927
9928 // int __vr_offs;
9929 FieldTypes[4] = Context->IntTy;
9930 FieldNames[4] = "__vr_offs";
9931
9932 // Create fields
9933 for (unsigned i = 0; i < NumFields; ++i) {
9934 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9938 &Context->Idents.get(FieldNames[i]),
9939 FieldTypes[i], /*TInfo=*/nullptr,
9940 /*BitWidth=*/nullptr,
9941 /*Mutable=*/false,
9942 ICIS_NoInit);
9943 Field->setAccess(AS_public);
9944 VaListTagDecl->addDecl(Field);
9945 }
9946 VaListTagDecl->completeDefinition();
9947 Context->VaListTagDecl = VaListTagDecl;
9948 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
9949
9950 // } __builtin_va_list;
9951 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
9952}
9953
9955 // typedef struct __va_list_tag {
9957
9958 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9959 VaListTagDecl->startDefinition();
9960
9961 const size_t NumFields = 5;
9962 QualType FieldTypes[NumFields];
9963 const char *FieldNames[NumFields];
9964
9965 // unsigned char gpr;
9966 FieldTypes[0] = Context->UnsignedCharTy;
9967 FieldNames[0] = "gpr";
9968
9969 // unsigned char fpr;
9970 FieldTypes[1] = Context->UnsignedCharTy;
9971 FieldNames[1] = "fpr";
9972
9973 // unsigned short reserved;
9974 FieldTypes[2] = Context->UnsignedShortTy;
9975 FieldNames[2] = "reserved";
9976
9977 // void* overflow_arg_area;
9978 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
9979 FieldNames[3] = "overflow_arg_area";
9980
9981 // void* reg_save_area;
9982 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
9983 FieldNames[4] = "reg_save_area";
9984
9985 // Create fields
9986 for (unsigned i = 0; i < NumFields; ++i) {
9987 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
9990 &Context->Idents.get(FieldNames[i]),
9991 FieldTypes[i], /*TInfo=*/nullptr,
9992 /*BitWidth=*/nullptr,
9993 /*Mutable=*/false,
9994 ICIS_NoInit);
9995 Field->setAccess(AS_public);
9996 VaListTagDecl->addDecl(Field);
9997 }
9998 VaListTagDecl->completeDefinition();
9999 Context->VaListTagDecl = VaListTagDecl;
10000 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10001
10002 // } __va_list_tag;
10003 TypedefDecl *VaListTagTypedefDecl =
10004 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10005
10006 QualType VaListTagTypedefType =
10007 Context->getTypedefType(ElaboratedTypeKeyword::None,
10008 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10009
10010 // typedef __va_list_tag __builtin_va_list[1];
10011 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10012 QualType VaListTagArrayType = Context->getConstantArrayType(
10013 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10014 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10015}
10016
10017static TypedefDecl *
10019 // struct __va_list_tag {
10021 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10022 VaListTagDecl->startDefinition();
10023
10024 const size_t NumFields = 4;
10025 QualType FieldTypes[NumFields];
10026 const char *FieldNames[NumFields];
10027
10028 // unsigned gp_offset;
10029 FieldTypes[0] = Context->UnsignedIntTy;
10030 FieldNames[0] = "gp_offset";
10031
10032 // unsigned fp_offset;
10033 FieldTypes[1] = Context->UnsignedIntTy;
10034 FieldNames[1] = "fp_offset";
10035
10036 // void* overflow_arg_area;
10037 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10038 FieldNames[2] = "overflow_arg_area";
10039
10040 // void* reg_save_area;
10041 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10042 FieldNames[3] = "reg_save_area";
10043
10044 // Create fields
10045 for (unsigned i = 0; i < NumFields; ++i) {
10046 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10050 &Context->Idents.get(FieldNames[i]),
10051 FieldTypes[i], /*TInfo=*/nullptr,
10052 /*BitWidth=*/nullptr,
10053 /*Mutable=*/false,
10054 ICIS_NoInit);
10055 Field->setAccess(AS_public);
10056 VaListTagDecl->addDecl(Field);
10057 }
10058 VaListTagDecl->completeDefinition();
10059 Context->VaListTagDecl = VaListTagDecl;
10060 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10061
10062 // };
10063
10064 // typedef struct __va_list_tag __builtin_va_list[1];
10065 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10066 QualType VaListTagArrayType = Context->getConstantArrayType(
10067 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10068 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10069}
10070
10071static TypedefDecl *
10073 // struct __va_list
10074 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
10075 if (Context->getLangOpts().CPlusPlus) {
10076 // namespace std { struct __va_list {
10077 NamespaceDecl *NS;
10078 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
10079 Context->getTranslationUnitDecl(),
10080 /*Inline=*/false, SourceLocation(),
10081 SourceLocation(), &Context->Idents.get("std"),
10082 /*PrevDecl=*/nullptr, /*Nested=*/false);
10083 NS->setImplicit();
10084 VaListDecl->setDeclContext(NS);
10085 }
10086
10087 VaListDecl->startDefinition();
10088
10089 // void * __ap;
10090 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10091 VaListDecl,
10094 &Context->Idents.get("__ap"),
10095 Context->getPointerType(Context->VoidTy),
10096 /*TInfo=*/nullptr,
10097 /*BitWidth=*/nullptr,
10098 /*Mutable=*/false,
10099 ICIS_NoInit);
10100 Field->setAccess(AS_public);
10101 VaListDecl->addDecl(Field);
10102
10103 // };
10104 VaListDecl->completeDefinition();
10105 Context->VaListTagDecl = VaListDecl;
10106
10107 // typedef struct __va_list __builtin_va_list;
10108 CanQualType T = Context->getCanonicalTagType(VaListDecl);
10109 return Context->buildImplicitTypedef(T, "__builtin_va_list");
10110}
10111
10112static TypedefDecl *
10114 // struct __va_list_tag {
10116 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10117 VaListTagDecl->startDefinition();
10118
10119 const size_t NumFields = 4;
10120 QualType FieldTypes[NumFields];
10121 const char *FieldNames[NumFields];
10122
10123 // long __gpr;
10124 FieldTypes[0] = Context->LongTy;
10125 FieldNames[0] = "__gpr";
10126
10127 // long __fpr;
10128 FieldTypes[1] = Context->LongTy;
10129 FieldNames[1] = "__fpr";
10130
10131 // void *__overflow_arg_area;
10132 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10133 FieldNames[2] = "__overflow_arg_area";
10134
10135 // void *__reg_save_area;
10136 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10137 FieldNames[3] = "__reg_save_area";
10138
10139 // Create fields
10140 for (unsigned i = 0; i < NumFields; ++i) {
10141 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10145 &Context->Idents.get(FieldNames[i]),
10146 FieldTypes[i], /*TInfo=*/nullptr,
10147 /*BitWidth=*/nullptr,
10148 /*Mutable=*/false,
10149 ICIS_NoInit);
10150 Field->setAccess(AS_public);
10151 VaListTagDecl->addDecl(Field);
10152 }
10153 VaListTagDecl->completeDefinition();
10154 Context->VaListTagDecl = VaListTagDecl;
10155 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10156
10157 // };
10158
10159 // typedef __va_list_tag __builtin_va_list[1];
10160 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10161 QualType VaListTagArrayType = Context->getConstantArrayType(
10162 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10163
10164 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10165}
10166
10168 // typedef struct __va_list_tag {
10170 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10171 VaListTagDecl->startDefinition();
10172
10173 const size_t NumFields = 3;
10174 QualType FieldTypes[NumFields];
10175 const char *FieldNames[NumFields];
10176
10177 // void *CurrentSavedRegisterArea;
10178 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
10179 FieldNames[0] = "__current_saved_reg_area_pointer";
10180
10181 // void *SavedRegAreaEnd;
10182 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
10183 FieldNames[1] = "__saved_reg_area_end_pointer";
10184
10185 // void *OverflowArea;
10186 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10187 FieldNames[2] = "__overflow_area_pointer";
10188
10189 // Create fields
10190 for (unsigned i = 0; i < NumFields; ++i) {
10192 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
10193 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
10194 /*TInfo=*/nullptr,
10195 /*BitWidth=*/nullptr,
10196 /*Mutable=*/false, ICIS_NoInit);
10197 Field->setAccess(AS_public);
10198 VaListTagDecl->addDecl(Field);
10199 }
10200 VaListTagDecl->completeDefinition();
10201 Context->VaListTagDecl = VaListTagDecl;
10202 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10203
10204 // } __va_list_tag;
10205 TypedefDecl *VaListTagTypedefDecl =
10206 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10207
10208 QualType VaListTagTypedefType =
10209 Context->getTypedefType(ElaboratedTypeKeyword::None,
10210 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10211
10212 // typedef __va_list_tag __builtin_va_list[1];
10213 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10214 QualType VaListTagArrayType = Context->getConstantArrayType(
10215 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10216
10217 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10218}
10219
10220static TypedefDecl *
10222 // typedef struct __va_list_tag {
10223 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10224
10225 VaListTagDecl->startDefinition();
10226
10227 // int* __va_stk;
10228 // int* __va_reg;
10229 // int __va_ndx;
10230 constexpr size_t NumFields = 3;
10231 QualType FieldTypes[NumFields] = {Context->getPointerType(Context->IntTy),
10232 Context->getPointerType(Context->IntTy),
10233 Context->IntTy};
10234 const char *FieldNames[NumFields] = {"__va_stk", "__va_reg", "__va_ndx"};
10235
10236 // Create fields
10237 for (unsigned i = 0; i < NumFields; ++i) {
10240 &Context->Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
10241 /*BitWidth=*/nullptr,
10242 /*Mutable=*/false, ICIS_NoInit);
10243 Field->setAccess(AS_public);
10244 VaListTagDecl->addDecl(Field);
10245 }
10246 VaListTagDecl->completeDefinition();
10247 Context->VaListTagDecl = VaListTagDecl;
10248 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10249
10250 // } __va_list_tag;
10251 TypedefDecl *VaListTagTypedefDecl =
10252 Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
10253
10254 return VaListTagTypedefDecl;
10255}
10256
10259 switch (Kind) {
10261 return CreateCharPtrBuiltinVaListDecl(Context);
10263 return CreateVoidPtrBuiltinVaListDecl(Context);
10265 return CreateAArch64ABIBuiltinVaListDecl(Context);
10267 return CreatePowerABIBuiltinVaListDecl(Context);
10269 return CreateX86_64ABIBuiltinVaListDecl(Context);
10271 return CreateAAPCSABIBuiltinVaListDecl(Context);
10273 return CreateSystemZBuiltinVaListDecl(Context);
10275 return CreateHexagonBuiltinVaListDecl(Context);
10277 return CreateXtensaABIBuiltinVaListDecl(Context);
10278 }
10279
10280 llvm_unreachable("Unhandled __builtin_va_list type kind");
10281}
10282
10284 if (!BuiltinVaListDecl) {
10285 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
10286 assert(BuiltinVaListDecl->isImplicit());
10287 }
10288
10289 return BuiltinVaListDecl;
10290}
10291
10293 // Force the creation of VaListTagDecl by building the __builtin_va_list
10294 // declaration.
10295 if (!VaListTagDecl)
10296 (void)getBuiltinVaListDecl();
10297
10298 return VaListTagDecl;
10299}
10300
10302 if (!BuiltinMSVaListDecl)
10303 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
10304
10305 return BuiltinMSVaListDecl;
10306}
10307
10309 // Allow redecl custom type checking builtin for HLSL.
10310 if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
10311 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10312 return true;
10313 // Allow redecl custom type checking builtin for SPIR-V.
10314 if (getTargetInfo().getTriple().isSPIROrSPIRV() &&
10315 BuiltinInfo.isTSBuiltin(FD->getBuiltinID()) &&
10316 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10317 return true;
10318 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
10319}
10320
10322 assert(ObjCConstantStringType.isNull() &&
10323 "'NSConstantString' type already set!");
10324
10325 ObjCConstantStringType = getObjCInterfaceType(Decl);
10326}
10327
10328/// Retrieve the template name that corresponds to a non-empty
10329/// lookup.
10332 UnresolvedSetIterator End) const {
10333 unsigned size = End - Begin;
10334 assert(size > 1 && "set is not overloaded!");
10335
10336 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
10337 size * sizeof(FunctionTemplateDecl*));
10338 auto *OT = new (memory) OverloadedTemplateStorage(size);
10339
10340 NamedDecl **Storage = OT->getStorage();
10341 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
10342 NamedDecl *D = *I;
10343 assert(isa<FunctionTemplateDecl>(D) ||
10347 *Storage++ = D;
10348 }
10349
10350 return TemplateName(OT);
10351}
10352
10353/// Retrieve a template name representing an unqualified-id that has been
10354/// assumed to name a template for ADL purposes.
10356 auto *OT = new (*this) AssumedTemplateStorage(Name);
10357 return TemplateName(OT);
10358}
10359
10360/// Retrieve the template name that represents a qualified
10361/// template name such as \c std::vector.
10363 bool TemplateKeyword,
10364 TemplateName Template) const {
10365 assert(Template.getKind() == TemplateName::Template ||
10367
10368 if (Template.getAsTemplateDecl()->getKind() == Decl::TemplateTemplateParm) {
10369 assert(!Qualifier && "unexpected qualified template template parameter");
10370 assert(TemplateKeyword == false);
10371 return Template;
10372 }
10373
10374 // FIXME: Canonicalization?
10375 llvm::FoldingSetNodeID ID;
10376 QualifiedTemplateName::Profile(ID, Qualifier, TemplateKeyword, Template);
10377
10378 void *InsertPos = nullptr;
10380 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
10381 if (!QTN) {
10382 QTN = new (*this, alignof(QualifiedTemplateName))
10383 QualifiedTemplateName(Qualifier, TemplateKeyword, Template);
10384 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
10385 }
10386
10387 return TemplateName(QTN);
10388}
10389
10390/// Retrieve the template name that represents a dependent
10391/// template name such as \c MetaFun::template operator+.
10394 llvm::FoldingSetNodeID ID;
10395 S.Profile(ID);
10396
10397 void *InsertPos = nullptr;
10398 if (DependentTemplateName *QTN =
10399 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos))
10400 return TemplateName(QTN);
10401
10403 new (*this, alignof(DependentTemplateName)) DependentTemplateName(S);
10404 DependentTemplateNames.InsertNode(QTN, InsertPos);
10405 return TemplateName(QTN);
10406}
10407
10409 Decl *AssociatedDecl,
10410 unsigned Index,
10411 UnsignedOrNone PackIndex,
10412 bool Final) const {
10413 llvm::FoldingSetNodeID ID;
10414 SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
10415 Index, PackIndex, Final);
10416
10417 void *insertPos = nullptr;
10419 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
10420
10421 if (!subst) {
10422 subst = new (*this) SubstTemplateTemplateParmStorage(
10423 Replacement, AssociatedDecl, Index, PackIndex, Final);
10424 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
10425 }
10426
10427 return TemplateName(subst);
10428}
10429
10432 Decl *AssociatedDecl,
10433 unsigned Index, bool Final) const {
10434 auto &Self = const_cast<ASTContext &>(*this);
10435 llvm::FoldingSetNodeID ID;
10437 AssociatedDecl, Index, Final);
10438
10439 void *InsertPos = nullptr;
10441 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
10442
10443 if (!Subst) {
10444 Subst = new (*this) SubstTemplateTemplateParmPackStorage(
10445 ArgPack.pack_elements(), AssociatedDecl, Index, Final);
10446 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
10447 }
10448
10449 return TemplateName(Subst);
10450}
10451
10452/// Retrieve the template name that represents a template name
10453/// deduced from a specialization.
10456 DefaultArguments DefaultArgs) const {
10457 if (!DefaultArgs)
10458 return Underlying;
10459
10460 llvm::FoldingSetNodeID ID;
10461 DeducedTemplateStorage::Profile(ID, *this, Underlying, DefaultArgs);
10462
10463 void *InsertPos = nullptr;
10465 DeducedTemplates.FindNodeOrInsertPos(ID, InsertPos);
10466 if (!DTS) {
10467 void *Mem = Allocate(sizeof(DeducedTemplateStorage) +
10468 sizeof(TemplateArgument) * DefaultArgs.Args.size(),
10469 alignof(DeducedTemplateStorage));
10470 DTS = new (Mem) DeducedTemplateStorage(Underlying, DefaultArgs);
10471 DeducedTemplates.InsertNode(DTS, InsertPos);
10472 }
10473 return TemplateName(DTS);
10474}
10475
10476/// getFromTargetType - Given one of the integer types provided by
10477/// TargetInfo, produce the corresponding type. The unsigned @p Type
10478/// is actually a value of type @c TargetInfo::IntType.
10479CanQualType ASTContext::getFromTargetType(unsigned Type) const {
10480 switch (Type) {
10481 case TargetInfo::NoInt: return {};
10484 case TargetInfo::SignedShort: return ShortTy;
10486 case TargetInfo::SignedInt: return IntTy;
10488 case TargetInfo::SignedLong: return LongTy;
10492 }
10493
10494 llvm_unreachable("Unhandled TargetInfo::IntType value");
10495}
10496
10497//===----------------------------------------------------------------------===//
10498// Type Predicates.
10499//===----------------------------------------------------------------------===//
10500
10501/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
10502/// garbage collection attribute.
10503///
10505 if (getLangOpts().getGC() == LangOptions::NonGC)
10506 return Qualifiers::GCNone;
10507
10508 assert(getLangOpts().ObjC);
10509 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
10510
10511 // Default behaviour under objective-C's gc is for ObjC pointers
10512 // (or pointers to them) be treated as though they were declared
10513 // as __strong.
10514 if (GCAttrs == Qualifiers::GCNone) {
10516 return Qualifiers::Strong;
10517 else if (Ty->isPointerType())
10519 } else {
10520 // It's not valid to set GC attributes on anything that isn't a
10521 // pointer.
10522#ifndef NDEBUG
10524 while (const auto *AT = dyn_cast<ArrayType>(CT))
10525 CT = AT->getElementType();
10526 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
10527#endif
10528 }
10529 return GCAttrs;
10530}
10531
10532//===----------------------------------------------------------------------===//
10533// Type Compatibility Testing
10534//===----------------------------------------------------------------------===//
10535
10536/// areCompatVectorTypes - Return true if the two specified vector types are
10537/// compatible.
10538static bool areCompatVectorTypes(const VectorType *LHS,
10539 const VectorType *RHS) {
10540 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10541 return LHS->getElementType() == RHS->getElementType() &&
10542 LHS->getNumElements() == RHS->getNumElements();
10543}
10544
10545/// areCompatMatrixTypes - Return true if the two specified matrix types are
10546/// compatible.
10548 const ConstantMatrixType *RHS) {
10549 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10550 return LHS->getElementType() == RHS->getElementType() &&
10551 LHS->getNumRows() == RHS->getNumRows() &&
10552 LHS->getNumColumns() == RHS->getNumColumns();
10553}
10554
10556 QualType SecondVec) {
10557 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
10558 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
10559
10560 if (hasSameUnqualifiedType(FirstVec, SecondVec))
10561 return true;
10562
10563 // Treat Neon vector types and most AltiVec vector types as if they are the
10564 // equivalent GCC vector types.
10565 const auto *First = FirstVec->castAs<VectorType>();
10566 const auto *Second = SecondVec->castAs<VectorType>();
10567 if (First->getNumElements() == Second->getNumElements() &&
10568 hasSameType(First->getElementType(), Second->getElementType()) &&
10569 First->getVectorKind() != VectorKind::AltiVecPixel &&
10570 First->getVectorKind() != VectorKind::AltiVecBool &&
10573 First->getVectorKind() != VectorKind::SveFixedLengthData &&
10574 First->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10577 First->getVectorKind() != VectorKind::RVVFixedLengthData &&
10579 First->getVectorKind() != VectorKind::RVVFixedLengthMask &&
10581 First->getVectorKind() != VectorKind::RVVFixedLengthMask_1 &&
10583 First->getVectorKind() != VectorKind::RVVFixedLengthMask_2 &&
10585 First->getVectorKind() != VectorKind::RVVFixedLengthMask_4 &&
10587 return true;
10588
10589 return false;
10590}
10591
10592/// getRVVTypeSize - Return RVV vector register size.
10593static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) {
10594 assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type");
10595 auto VScale = Context.getTargetInfo().getVScaleRange(
10596 Context.getLangOpts(), TargetInfo::ArmStreamingKind::NotStreaming);
10597 if (!VScale)
10598 return 0;
10599
10600 ASTContext::BuiltinVectorTypeInfo Info = Context.getBuiltinVectorTypeInfo(Ty);
10601
10602 uint64_t EltSize = Context.getTypeSize(Info.ElementType);
10603 if (Info.ElementType == Context.BoolTy)
10604 EltSize = 1;
10605
10606 uint64_t MinElts = Info.EC.getKnownMinValue();
10607 return VScale->first * MinElts * EltSize;
10608}
10609
10611 QualType SecondType) {
10612 assert(
10613 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10614 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10615 "Expected RVV builtin type and vector type!");
10616
10617 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10618 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10619 if (const auto *VT = SecondType->getAs<VectorType>()) {
10620 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask) {
10622 return FirstType->isRVVVLSBuiltinType() &&
10623 Info.ElementType == BoolTy &&
10624 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)));
10625 }
10626 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1) {
10628 return FirstType->isRVVVLSBuiltinType() &&
10629 Info.ElementType == BoolTy &&
10630 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT) * 8));
10631 }
10632 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2) {
10634 return FirstType->isRVVVLSBuiltinType() &&
10635 Info.ElementType == BoolTy &&
10636 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 4);
10637 }
10638 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10640 return FirstType->isRVVVLSBuiltinType() &&
10641 Info.ElementType == BoolTy &&
10642 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 2);
10643 }
10644 if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
10645 VT->getVectorKind() == VectorKind::Generic)
10646 return FirstType->isRVVVLSBuiltinType() &&
10647 getTypeSize(SecondType) == getRVVTypeSize(*this, BT) &&
10648 hasSameType(VT->getElementType(),
10649 getBuiltinVectorTypeInfo(BT).ElementType);
10650 }
10651 }
10652 return false;
10653 };
10654
10655 return IsValidCast(FirstType, SecondType) ||
10656 IsValidCast(SecondType, FirstType);
10657}
10658
10660 QualType SecondType) {
10661 assert(
10662 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10663 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10664 "Expected RVV builtin type and vector type!");
10665
10666 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10667 const auto *BT = FirstType->getAs<BuiltinType>();
10668 if (!BT)
10669 return false;
10670
10671 if (!BT->isRVVVLSBuiltinType())
10672 return false;
10673
10674 const auto *VecTy = SecondType->getAs<VectorType>();
10675 if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) {
10677 getLangOpts().getLaxVectorConversions();
10678
10679 // If __riscv_v_fixed_vlen != N do not allow vector lax conversion.
10680 if (getTypeSize(SecondType) != getRVVTypeSize(*this, BT))
10681 return false;
10682
10683 // If -flax-vector-conversions=all is specified, the types are
10684 // certainly compatible.
10686 return true;
10687
10688 // If -flax-vector-conversions=integer is specified, the types are
10689 // compatible if the elements are integer types.
10691 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10692 FirstType->getRVVEltType(*this)->isIntegerType();
10693 }
10694
10695 return false;
10696 };
10697
10698 return IsLaxCompatible(FirstType, SecondType) ||
10699 IsLaxCompatible(SecondType, FirstType);
10700}
10701
10703 while (true) {
10704 // __strong id
10705 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
10706 if (Attr->getAttrKind() == attr::ObjCOwnership)
10707 return true;
10708
10709 Ty = Attr->getModifiedType();
10710
10711 // X *__strong (...)
10712 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
10713 Ty = Paren->getInnerType();
10714
10715 // We do not want to look through typedefs, typeof(expr),
10716 // typeof(type), or any other way that the type is somehow
10717 // abstracted.
10718 } else {
10719 return false;
10720 }
10721 }
10722}
10723
10724//===----------------------------------------------------------------------===//
10725// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
10726//===----------------------------------------------------------------------===//
10727
10728/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
10729/// inheritance hierarchy of 'rProto'.
10730bool
10732 ObjCProtocolDecl *rProto) const {
10733 if (declaresSameEntity(lProto, rProto))
10734 return true;
10735 for (auto *PI : rProto->protocols())
10736 if (ProtocolCompatibleWithProtocol(lProto, PI))
10737 return true;
10738 return false;
10739}
10740
10741/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
10742/// Class<pr1, ...>.
10744 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
10745 for (auto *lhsProto : lhs->quals()) {
10746 bool match = false;
10747 for (auto *rhsProto : rhs->quals()) {
10748 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
10749 match = true;
10750 break;
10751 }
10752 }
10753 if (!match)
10754 return false;
10755 }
10756 return true;
10757}
10758
10759/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
10760/// ObjCQualifiedIDType.
10762 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
10763 bool compare) {
10764 // Allow id<P..> and an 'id' in all cases.
10765 if (lhs->isObjCIdType() || rhs->isObjCIdType())
10766 return true;
10767
10768 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
10769 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
10771 return false;
10772
10773 if (lhs->isObjCQualifiedIdType()) {
10774 if (rhs->qual_empty()) {
10775 // If the RHS is a unqualified interface pointer "NSString*",
10776 // make sure we check the class hierarchy.
10777 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10778 for (auto *I : lhs->quals()) {
10779 // when comparing an id<P> on lhs with a static type on rhs,
10780 // see if static class implements all of id's protocols, directly or
10781 // through its super class and categories.
10782 if (!rhsID->ClassImplementsProtocol(I, true))
10783 return false;
10784 }
10785 }
10786 // If there are no qualifiers and no interface, we have an 'id'.
10787 return true;
10788 }
10789 // Both the right and left sides have qualifiers.
10790 for (auto *lhsProto : lhs->quals()) {
10791 bool match = false;
10792
10793 // when comparing an id<P> on lhs with a static type on rhs,
10794 // see if static class implements all of id's protocols, directly or
10795 // through its super class and categories.
10796 for (auto *rhsProto : rhs->quals()) {
10797 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10798 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10799 match = true;
10800 break;
10801 }
10802 }
10803 // If the RHS is a qualified interface pointer "NSString<P>*",
10804 // make sure we check the class hierarchy.
10805 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10806 for (auto *I : lhs->quals()) {
10807 // when comparing an id<P> on lhs with a static type on rhs,
10808 // see if static class implements all of id's protocols, directly or
10809 // through its super class and categories.
10810 if (rhsID->ClassImplementsProtocol(I, true)) {
10811 match = true;
10812 break;
10813 }
10814 }
10815 }
10816 if (!match)
10817 return false;
10818 }
10819
10820 return true;
10821 }
10822
10823 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
10824
10825 if (lhs->getInterfaceType()) {
10826 // If both the right and left sides have qualifiers.
10827 for (auto *lhsProto : lhs->quals()) {
10828 bool match = false;
10829
10830 // when comparing an id<P> on rhs with a static type on lhs,
10831 // see if static class implements all of id's protocols, directly or
10832 // through its super class and categories.
10833 // First, lhs protocols in the qualifier list must be found, direct
10834 // or indirect in rhs's qualifier list or it is a mismatch.
10835 for (auto *rhsProto : rhs->quals()) {
10836 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10837 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10838 match = true;
10839 break;
10840 }
10841 }
10842 if (!match)
10843 return false;
10844 }
10845
10846 // Static class's protocols, or its super class or category protocols
10847 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
10848 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
10849 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
10850 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
10851 // This is rather dubious but matches gcc's behavior. If lhs has
10852 // no type qualifier and its class has no static protocol(s)
10853 // assume that it is mismatch.
10854 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
10855 return false;
10856 for (auto *lhsProto : LHSInheritedProtocols) {
10857 bool match = false;
10858 for (auto *rhsProto : rhs->quals()) {
10859 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10860 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10861 match = true;
10862 break;
10863 }
10864 }
10865 if (!match)
10866 return false;
10867 }
10868 }
10869 return true;
10870 }
10871 return false;
10872}
10873
10874/// canAssignObjCInterfaces - Return true if the two interface types are
10875/// compatible for assignment from RHS to LHS. This handles validation of any
10876/// protocol qualifiers on the LHS or RHS.
10878 const ObjCObjectPointerType *RHSOPT) {
10879 const ObjCObjectType* LHS = LHSOPT->getObjectType();
10880 const ObjCObjectType* RHS = RHSOPT->getObjectType();
10881
10882 // If either type represents the built-in 'id' type, return true.
10883 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
10884 return true;
10885
10886 // Function object that propagates a successful result or handles
10887 // __kindof types.
10888 auto finish = [&](bool succeeded) -> bool {
10889 if (succeeded)
10890 return true;
10891
10892 if (!RHS->isKindOfType())
10893 return false;
10894
10895 // Strip off __kindof and protocol qualifiers, then check whether
10896 // we can assign the other way.
10898 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
10899 };
10900
10901 // Casts from or to id<P> are allowed when the other side has compatible
10902 // protocols.
10903 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
10904 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
10905 }
10906
10907 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
10908 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
10909 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
10910 }
10911
10912 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
10913 if (LHS->isObjCClass() && RHS->isObjCClass()) {
10914 return true;
10915 }
10916
10917 // If we have 2 user-defined types, fall into that path.
10918 if (LHS->getInterface() && RHS->getInterface()) {
10919 return finish(canAssignObjCInterfaces(LHS, RHS));
10920 }
10921
10922 return false;
10923}
10924
10925/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
10926/// for providing type-safety for objective-c pointers used to pass/return
10927/// arguments in block literals. When passed as arguments, passing 'A*' where
10928/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
10929/// not OK. For the return type, the opposite is not OK.
10931 const ObjCObjectPointerType *LHSOPT,
10932 const ObjCObjectPointerType *RHSOPT,
10933 bool BlockReturnType) {
10934
10935 // Function object that propagates a successful result or handles
10936 // __kindof types.
10937 auto finish = [&](bool succeeded) -> bool {
10938 if (succeeded)
10939 return true;
10940
10941 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
10942 if (!Expected->isKindOfType())
10943 return false;
10944
10945 // Strip off __kindof and protocol qualifiers, then check whether
10946 // we can assign the other way.
10948 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
10949 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
10950 BlockReturnType);
10951 };
10952
10953 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
10954 return true;
10955
10956 if (LHSOPT->isObjCBuiltinType()) {
10957 return finish(RHSOPT->isObjCBuiltinType() ||
10958 RHSOPT->isObjCQualifiedIdType());
10959 }
10960
10961 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
10962 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
10963 // Use for block parameters previous type checking for compatibility.
10964 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
10965 // Or corrected type checking as in non-compat mode.
10966 (!BlockReturnType &&
10967 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
10968 else
10970 (BlockReturnType ? LHSOPT : RHSOPT),
10971 (BlockReturnType ? RHSOPT : LHSOPT), false));
10972 }
10973
10974 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
10975 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
10976 if (LHS && RHS) { // We have 2 user-defined types.
10977 if (LHS != RHS) {
10978 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
10979 return finish(BlockReturnType);
10980 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
10981 return finish(!BlockReturnType);
10982 }
10983 else
10984 return true;
10985 }
10986 return false;
10987}
10988
10989/// Comparison routine for Objective-C protocols to be used with
10990/// llvm::array_pod_sort.
10992 ObjCProtocolDecl * const *rhs) {
10993 return (*lhs)->getName().compare((*rhs)->getName());
10994}
10995
10996/// getIntersectionOfProtocols - This routine finds the intersection of set
10997/// of protocols inherited from two distinct objective-c pointer objects with
10998/// the given common base.
10999/// It is used to build composite qualifier list of the composite type of
11000/// the conditional expression involving two objective-c pointer objects.
11001static
11003 const ObjCInterfaceDecl *CommonBase,
11004 const ObjCObjectPointerType *LHSOPT,
11005 const ObjCObjectPointerType *RHSOPT,
11006 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
11007
11008 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11009 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11010 assert(LHS->getInterface() && "LHS must have an interface base");
11011 assert(RHS->getInterface() && "RHS must have an interface base");
11012
11013 // Add all of the protocols for the LHS.
11015
11016 // Start with the protocol qualifiers.
11017 for (auto *proto : LHS->quals()) {
11018 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
11019 }
11020
11021 // Also add the protocols associated with the LHS interface.
11022 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
11023
11024 // Add all of the protocols for the RHS.
11026
11027 // Start with the protocol qualifiers.
11028 for (auto *proto : RHS->quals()) {
11029 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
11030 }
11031
11032 // Also add the protocols associated with the RHS interface.
11033 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
11034
11035 // Compute the intersection of the collected protocol sets.
11036 for (auto *proto : LHSProtocolSet) {
11037 if (RHSProtocolSet.count(proto))
11038 IntersectionSet.push_back(proto);
11039 }
11040
11041 // Compute the set of protocols that is implied by either the common type or
11042 // the protocols within the intersection.
11044 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
11045
11046 // Remove any implied protocols from the list of inherited protocols.
11047 if (!ImpliedProtocols.empty()) {
11048 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool {
11049 return ImpliedProtocols.contains(proto);
11050 });
11051 }
11052
11053 // Sort the remaining protocols by name.
11054 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
11056}
11057
11058/// Determine whether the first type is a subtype of the second.
11060 QualType rhs) {
11061 // Common case: two object pointers.
11062 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
11063 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
11064 if (lhsOPT && rhsOPT)
11065 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
11066
11067 // Two block pointers.
11068 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
11069 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
11070 if (lhsBlock && rhsBlock)
11071 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
11072
11073 // If either is an unqualified 'id' and the other is a block, it's
11074 // acceptable.
11075 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
11076 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
11077 return true;
11078
11079 return false;
11080}
11081
11082// Check that the given Objective-C type argument lists are equivalent.
11084 const ObjCInterfaceDecl *iface,
11085 ArrayRef<QualType> lhsArgs,
11086 ArrayRef<QualType> rhsArgs,
11087 bool stripKindOf) {
11088 if (lhsArgs.size() != rhsArgs.size())
11089 return false;
11090
11091 ObjCTypeParamList *typeParams = iface->getTypeParamList();
11092 if (!typeParams)
11093 return false;
11094
11095 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
11096 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
11097 continue;
11098
11099 switch (typeParams->begin()[i]->getVariance()) {
11101 if (!stripKindOf ||
11102 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
11103 rhsArgs[i].stripObjCKindOfType(ctx))) {
11104 return false;
11105 }
11106 break;
11107
11109 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
11110 return false;
11111 break;
11112
11114 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
11115 return false;
11116 break;
11117 }
11118 }
11119
11120 return true;
11121}
11122
11124 const ObjCObjectPointerType *Lptr,
11125 const ObjCObjectPointerType *Rptr) {
11126 const ObjCObjectType *LHS = Lptr->getObjectType();
11127 const ObjCObjectType *RHS = Rptr->getObjectType();
11128 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
11129 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
11130
11131 if (!LDecl || !RDecl)
11132 return {};
11133
11134 // When either LHS or RHS is a kindof type, we should return a kindof type.
11135 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
11136 // kindof(A).
11137 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
11138
11139 // Follow the left-hand side up the class hierarchy until we either hit a
11140 // root or find the RHS. Record the ancestors in case we don't find it.
11141 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
11142 LHSAncestors;
11143 while (true) {
11144 // Record this ancestor. We'll need this if the common type isn't in the
11145 // path from the LHS to the root.
11146 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
11147
11148 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
11149 // Get the type arguments.
11150 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
11151 bool anyChanges = false;
11152 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11153 // Both have type arguments, compare them.
11154 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11155 LHS->getTypeArgs(), RHS->getTypeArgs(),
11156 /*stripKindOf=*/true))
11157 return {};
11158 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11159 // If only one has type arguments, the result will not have type
11160 // arguments.
11161 LHSTypeArgs = {};
11162 anyChanges = true;
11163 }
11164
11165 // Compute the intersection of protocols.
11167 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
11168 Protocols);
11169 if (!Protocols.empty())
11170 anyChanges = true;
11171
11172 // If anything in the LHS will have changed, build a new result type.
11173 // If we need to return a kindof type but LHS is not a kindof type, we
11174 // build a new result type.
11175 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
11176 QualType Result = getObjCInterfaceType(LHS->getInterface());
11177 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
11178 anyKindOf || LHS->isKindOfType());
11180 }
11181
11182 return getObjCObjectPointerType(QualType(LHS, 0));
11183 }
11184
11185 // Find the superclass.
11186 QualType LHSSuperType = LHS->getSuperClassType();
11187 if (LHSSuperType.isNull())
11188 break;
11189
11190 LHS = LHSSuperType->castAs<ObjCObjectType>();
11191 }
11192
11193 // We didn't find anything by following the LHS to its root; now check
11194 // the RHS against the cached set of ancestors.
11195 while (true) {
11196 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
11197 if (KnownLHS != LHSAncestors.end()) {
11198 LHS = KnownLHS->second;
11199
11200 // Get the type arguments.
11201 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
11202 bool anyChanges = false;
11203 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11204 // Both have type arguments, compare them.
11205 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11206 LHS->getTypeArgs(), RHS->getTypeArgs(),
11207 /*stripKindOf=*/true))
11208 return {};
11209 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11210 // If only one has type arguments, the result will not have type
11211 // arguments.
11212 RHSTypeArgs = {};
11213 anyChanges = true;
11214 }
11215
11216 // Compute the intersection of protocols.
11218 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
11219 Protocols);
11220 if (!Protocols.empty())
11221 anyChanges = true;
11222
11223 // If we need to return a kindof type but RHS is not a kindof type, we
11224 // build a new result type.
11225 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
11226 QualType Result = getObjCInterfaceType(RHS->getInterface());
11227 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
11228 anyKindOf || RHS->isKindOfType());
11230 }
11231
11232 return getObjCObjectPointerType(QualType(RHS, 0));
11233 }
11234
11235 // Find the superclass of the RHS.
11236 QualType RHSSuperType = RHS->getSuperClassType();
11237 if (RHSSuperType.isNull())
11238 break;
11239
11240 RHS = RHSSuperType->castAs<ObjCObjectType>();
11241 }
11242
11243 return {};
11244}
11245
11247 const ObjCObjectType *RHS) {
11248 assert(LHS->getInterface() && "LHS is not an interface type");
11249 assert(RHS->getInterface() && "RHS is not an interface type");
11250
11251 // Verify that the base decls are compatible: the RHS must be a subclass of
11252 // the LHS.
11253 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
11254 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
11255 if (!IsSuperClass)
11256 return false;
11257
11258 // If the LHS has protocol qualifiers, determine whether all of them are
11259 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
11260 // LHS).
11261 if (LHS->getNumProtocols() > 0) {
11262 // OK if conversion of LHS to SuperClass results in narrowing of types
11263 // ; i.e., SuperClass may implement at least one of the protocols
11264 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
11265 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
11266 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
11267 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
11268 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
11269 // qualifiers.
11270 for (auto *RHSPI : RHS->quals())
11271 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
11272 // If there is no protocols associated with RHS, it is not a match.
11273 if (SuperClassInheritedProtocols.empty())
11274 return false;
11275
11276 for (const auto *LHSProto : LHS->quals()) {
11277 bool SuperImplementsProtocol = false;
11278 for (auto *SuperClassProto : SuperClassInheritedProtocols)
11279 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
11280 SuperImplementsProtocol = true;
11281 break;
11282 }
11283 if (!SuperImplementsProtocol)
11284 return false;
11285 }
11286 }
11287
11288 // If the LHS is specialized, we may need to check type arguments.
11289 if (LHS->isSpecialized()) {
11290 // Follow the superclass chain until we've matched the LHS class in the
11291 // hierarchy. This substitutes type arguments through.
11292 const ObjCObjectType *RHSSuper = RHS;
11293 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
11294 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
11295
11296 // If the RHS is specializd, compare type arguments.
11297 if (RHSSuper->isSpecialized() &&
11298 !sameObjCTypeArgs(*this, LHS->getInterface(),
11299 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
11300 /*stripKindOf=*/true)) {
11301 return false;
11302 }
11303 }
11304
11305 return true;
11306}
11307
11309 // get the "pointed to" types
11310 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
11311 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
11312
11313 if (!LHSOPT || !RHSOPT)
11314 return false;
11315
11316 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
11317 canAssignObjCInterfaces(RHSOPT, LHSOPT);
11318}
11319
11322 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
11323 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
11324}
11325
11326/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
11327/// both shall have the identically qualified version of a compatible type.
11328/// C99 6.2.7p1: Two types have compatible types if their types are the
11329/// same. See 6.7.[2,3,5] for additional rules.
11331 bool CompareUnqualified) {
11332 if (getLangOpts().CPlusPlus)
11333 return hasSameType(LHS, RHS);
11334
11335 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
11336}
11337
11339 return typesAreCompatible(LHS, RHS);
11340}
11341
11343 return !mergeTypes(LHS, RHS, true).isNull();
11344}
11345
11346/// mergeTransparentUnionType - if T is a transparent union type and a member
11347/// of T is compatible with SubType, return the merged type, else return
11348/// QualType()
11350 bool OfBlockPointer,
11351 bool Unqualified) {
11352 if (const RecordType *UT = T->getAsUnionType()) {
11353 RecordDecl *UD = UT->getOriginalDecl()->getMostRecentDecl();
11354 if (UD->hasAttr<TransparentUnionAttr>()) {
11355 for (const auto *I : UD->fields()) {
11356 QualType ET = I->getType().getUnqualifiedType();
11357 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
11358 if (!MT.isNull())
11359 return MT;
11360 }
11361 }
11362 }
11363
11364 return {};
11365}
11366
11367/// mergeFunctionParameterTypes - merge two types which appear as function
11368/// parameter types
11370 bool OfBlockPointer,
11371 bool Unqualified) {
11372 // GNU extension: two types are compatible if they appear as a function
11373 // argument, one of the types is a transparent union type and the other
11374 // type is compatible with a union member
11375 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
11376 Unqualified);
11377 if (!lmerge.isNull())
11378 return lmerge;
11379
11380 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
11381 Unqualified);
11382 if (!rmerge.isNull())
11383 return rmerge;
11384
11385 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
11386}
11387
11389 bool OfBlockPointer, bool Unqualified,
11390 bool AllowCXX,
11391 bool IsConditionalOperator) {
11392 const auto *lbase = lhs->castAs<FunctionType>();
11393 const auto *rbase = rhs->castAs<FunctionType>();
11394 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
11395 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
11396 bool allLTypes = true;
11397 bool allRTypes = true;
11398
11399 // Check return type
11400 QualType retType;
11401 if (OfBlockPointer) {
11402 QualType RHS = rbase->getReturnType();
11403 QualType LHS = lbase->getReturnType();
11404 bool UnqualifiedResult = Unqualified;
11405 if (!UnqualifiedResult)
11406 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
11407 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
11408 }
11409 else
11410 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
11411 Unqualified);
11412 if (retType.isNull())
11413 return {};
11414
11415 if (Unqualified)
11416 retType = retType.getUnqualifiedType();
11417
11418 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
11419 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
11420 if (Unqualified) {
11421 LRetType = LRetType.getUnqualifiedType();
11422 RRetType = RRetType.getUnqualifiedType();
11423 }
11424
11425 if (getCanonicalType(retType) != LRetType)
11426 allLTypes = false;
11427 if (getCanonicalType(retType) != RRetType)
11428 allRTypes = false;
11429
11430 // FIXME: double check this
11431 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
11432 // rbase->getRegParmAttr() != 0 &&
11433 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
11434 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
11435 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
11436
11437 // Compatible functions must have compatible calling conventions
11438 if (lbaseInfo.getCC() != rbaseInfo.getCC())
11439 return {};
11440
11441 // Regparm is part of the calling convention.
11442 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
11443 return {};
11444 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
11445 return {};
11446
11447 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
11448 return {};
11449 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
11450 return {};
11451 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
11452 return {};
11453
11454 // When merging declarations, it's common for supplemental information like
11455 // attributes to only be present in one of the declarations, and we generally
11456 // want type merging to preserve the union of information. So a merged
11457 // function type should be noreturn if it was noreturn in *either* operand
11458 // type.
11459 //
11460 // But for the conditional operator, this is backwards. The result of the
11461 // operator could be either operand, and its type should conservatively
11462 // reflect that. So a function type in a composite type is noreturn only
11463 // if it's noreturn in *both* operand types.
11464 //
11465 // Arguably, noreturn is a kind of subtype, and the conditional operator
11466 // ought to produce the most specific common supertype of its operand types.
11467 // That would differ from this rule in contravariant positions. However,
11468 // neither C nor C++ generally uses this kind of subtype reasoning. Also,
11469 // as a practical matter, it would only affect C code that does abstraction of
11470 // higher-order functions (taking noreturn callbacks!), which is uncommon to
11471 // say the least. So we use the simpler rule.
11472 bool NoReturn = IsConditionalOperator
11473 ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
11474 : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
11475 if (lbaseInfo.getNoReturn() != NoReturn)
11476 allLTypes = false;
11477 if (rbaseInfo.getNoReturn() != NoReturn)
11478 allRTypes = false;
11479
11480 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
11481
11482 std::optional<FunctionEffectSet> MergedFX;
11483
11484 if (lproto && rproto) { // two C99 style function prototypes
11485 assert((AllowCXX ||
11486 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
11487 "C++ shouldn't be here");
11488 // Compatible functions must have the same number of parameters
11489 if (lproto->getNumParams() != rproto->getNumParams())
11490 return {};
11491
11492 // Variadic and non-variadic functions aren't compatible
11493 if (lproto->isVariadic() != rproto->isVariadic())
11494 return {};
11495
11496 if (lproto->getMethodQuals() != rproto->getMethodQuals())
11497 return {};
11498
11499 // Function protos with different 'cfi_salt' values aren't compatible.
11500 if (lproto->getExtraAttributeInfo().CFISalt !=
11501 rproto->getExtraAttributeInfo().CFISalt)
11502 return {};
11503
11504 // Function effects are handled similarly to noreturn, see above.
11505 FunctionEffectsRef LHSFX = lproto->getFunctionEffects();
11506 FunctionEffectsRef RHSFX = rproto->getFunctionEffects();
11507 if (LHSFX != RHSFX) {
11508 if (IsConditionalOperator)
11509 MergedFX = FunctionEffectSet::getIntersection(LHSFX, RHSFX);
11510 else {
11512 MergedFX = FunctionEffectSet::getUnion(LHSFX, RHSFX, Errs);
11513 // Here we're discarding a possible error due to conflicts in the effect
11514 // sets. But we're not in a context where we can report it. The
11515 // operation does however guarantee maintenance of invariants.
11516 }
11517 if (*MergedFX != LHSFX)
11518 allLTypes = false;
11519 if (*MergedFX != RHSFX)
11520 allRTypes = false;
11521 }
11522
11524 bool canUseLeft, canUseRight;
11525 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
11526 newParamInfos))
11527 return {};
11528
11529 if (!canUseLeft)
11530 allLTypes = false;
11531 if (!canUseRight)
11532 allRTypes = false;
11533
11534 // Check parameter type compatibility
11536 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
11537 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
11538 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
11540 lParamType, rParamType, OfBlockPointer, Unqualified);
11541 if (paramType.isNull())
11542 return {};
11543
11544 if (Unqualified)
11545 paramType = paramType.getUnqualifiedType();
11546
11547 types.push_back(paramType);
11548 if (Unqualified) {
11549 lParamType = lParamType.getUnqualifiedType();
11550 rParamType = rParamType.getUnqualifiedType();
11551 }
11552
11553 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
11554 allLTypes = false;
11555 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
11556 allRTypes = false;
11557 }
11558
11559 if (allLTypes) return lhs;
11560 if (allRTypes) return rhs;
11561
11562 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
11563 EPI.ExtInfo = einfo;
11564 EPI.ExtParameterInfos =
11565 newParamInfos.empty() ? nullptr : newParamInfos.data();
11566 if (MergedFX)
11567 EPI.FunctionEffects = *MergedFX;
11568 return getFunctionType(retType, types, EPI);
11569 }
11570
11571 if (lproto) allRTypes = false;
11572 if (rproto) allLTypes = false;
11573
11574 const FunctionProtoType *proto = lproto ? lproto : rproto;
11575 if (proto) {
11576 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
11577 if (proto->isVariadic())
11578 return {};
11579 // Check that the types are compatible with the types that
11580 // would result from default argument promotions (C99 6.7.5.3p15).
11581 // The only types actually affected are promotable integer
11582 // types and floats, which would be passed as a different
11583 // type depending on whether the prototype is visible.
11584 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
11585 QualType paramTy = proto->getParamType(i);
11586
11587 // Look at the converted type of enum types, since that is the type used
11588 // to pass enum values.
11589 if (const auto *ED = paramTy->getAsEnumDecl()) {
11590 paramTy = ED->getIntegerType();
11591 if (paramTy.isNull())
11592 return {};
11593 }
11594
11595 if (isPromotableIntegerType(paramTy) ||
11596 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
11597 return {};
11598 }
11599
11600 if (allLTypes) return lhs;
11601 if (allRTypes) return rhs;
11602
11604 EPI.ExtInfo = einfo;
11605 if (MergedFX)
11606 EPI.FunctionEffects = *MergedFX;
11607 return getFunctionType(retType, proto->getParamTypes(), EPI);
11608 }
11609
11610 if (allLTypes) return lhs;
11611 if (allRTypes) return rhs;
11612 return getFunctionNoProtoType(retType, einfo);
11613}
11614
11615/// Given that we have an enum type and a non-enum type, try to merge them.
11616static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
11617 QualType other, bool isBlockReturnType) {
11618 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
11619 // a signed integer type, or an unsigned integer type.
11620 // Compatibility is based on the underlying type, not the promotion
11621 // type.
11622 QualType underlyingType =
11623 ET->getOriginalDecl()->getDefinitionOrSelf()->getIntegerType();
11624 if (underlyingType.isNull())
11625 return {};
11626 if (Context.hasSameType(underlyingType, other))
11627 return other;
11628
11629 // In block return types, we're more permissive and accept any
11630 // integral type of the same size.
11631 if (isBlockReturnType && other->isIntegerType() &&
11632 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
11633 return other;
11634
11635 return {};
11636}
11637
11639 // C17 and earlier and C++ disallow two tag definitions within the same TU
11640 // from being compatible.
11641 if (LangOpts.CPlusPlus || !LangOpts.C23)
11642 return {};
11643
11644 // C23, on the other hand, requires the members to be "the same enough", so
11645 // we use a structural equivalence check.
11648 getLangOpts(), *this, *this, NonEquivalentDecls,
11649 StructuralEquivalenceKind::Default, /*StrictTypeSpelling=*/false,
11650 /*Complain=*/false, /*ErrorOnTagTypeMismatch=*/true);
11651 return Ctx.IsEquivalent(LHS, RHS) ? LHS : QualType{};
11652}
11653
11654QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
11655 bool Unqualified, bool BlockReturnType,
11656 bool IsConditionalOperator) {
11657 // For C++ we will not reach this code with reference types (see below),
11658 // for OpenMP variant call overloading we might.
11659 //
11660 // C++ [expr]: If an expression initially has the type "reference to T", the
11661 // type is adjusted to "T" prior to any further analysis, the expression
11662 // designates the object or function denoted by the reference, and the
11663 // expression is an lvalue unless the reference is an rvalue reference and
11664 // the expression is a function call (possibly inside parentheses).
11665 auto *LHSRefTy = LHS->getAs<ReferenceType>();
11666 auto *RHSRefTy = RHS->getAs<ReferenceType>();
11667 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
11668 LHS->getTypeClass() == RHS->getTypeClass())
11669 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(),
11670 OfBlockPointer, Unqualified, BlockReturnType);
11671 if (LHSRefTy || RHSRefTy)
11672 return {};
11673
11674 if (Unqualified) {
11675 LHS = LHS.getUnqualifiedType();
11676 RHS = RHS.getUnqualifiedType();
11677 }
11678
11679 QualType LHSCan = getCanonicalType(LHS),
11680 RHSCan = getCanonicalType(RHS);
11681
11682 // If two types are identical, they are compatible.
11683 if (LHSCan == RHSCan)
11684 return LHS;
11685
11686 // If the qualifiers are different, the types aren't compatible... mostly.
11687 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11688 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11689 if (LQuals != RQuals) {
11690 // If any of these qualifiers are different, we have a type
11691 // mismatch.
11692 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11693 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
11694 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
11695 !LQuals.getPointerAuth().isEquivalent(RQuals.getPointerAuth()) ||
11696 LQuals.hasUnaligned() != RQuals.hasUnaligned())
11697 return {};
11698
11699 // Exactly one GC qualifier difference is allowed: __strong is
11700 // okay if the other type has no GC qualifier but is an Objective
11701 // C object pointer (i.e. implicitly strong by default). We fix
11702 // this by pretending that the unqualified type was actually
11703 // qualified __strong.
11704 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11705 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11706 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11707
11708 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
11709 return {};
11710
11711 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
11713 }
11714 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
11716 }
11717 return {};
11718 }
11719
11720 // Okay, qualifiers are equal.
11721
11722 Type::TypeClass LHSClass = LHSCan->getTypeClass();
11723 Type::TypeClass RHSClass = RHSCan->getTypeClass();
11724
11725 // We want to consider the two function types to be the same for these
11726 // comparisons, just force one to the other.
11727 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
11728 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
11729
11730 // Same as above for arrays
11731 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
11732 LHSClass = Type::ConstantArray;
11733 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
11734 RHSClass = Type::ConstantArray;
11735
11736 // ObjCInterfaces are just specialized ObjCObjects.
11737 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
11738 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
11739
11740 // Canonicalize ExtVector -> Vector.
11741 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
11742 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
11743
11744 // If the canonical type classes don't match.
11745 if (LHSClass != RHSClass) {
11746 // Note that we only have special rules for turning block enum
11747 // returns into block int returns, not vice-versa.
11748 if (const auto *ETy = LHS->getAsCanonical<EnumType>()) {
11749 return mergeEnumWithInteger(*this, ETy, RHS, false);
11750 }
11751 if (const EnumType *ETy = RHS->getAsCanonical<EnumType>()) {
11752 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
11753 }
11754 // allow block pointer type to match an 'id' type.
11755 if (OfBlockPointer && !BlockReturnType) {
11756 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
11757 return LHS;
11758 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
11759 return RHS;
11760 }
11761 // Allow __auto_type to match anything; it merges to the type with more
11762 // information.
11763 if (const auto *AT = LHS->getAs<AutoType>()) {
11764 if (!AT->isDeduced() && AT->isGNUAutoType())
11765 return RHS;
11766 }
11767 if (const auto *AT = RHS->getAs<AutoType>()) {
11768 if (!AT->isDeduced() && AT->isGNUAutoType())
11769 return LHS;
11770 }
11771 return {};
11772 }
11773
11774 // The canonical type classes match.
11775 switch (LHSClass) {
11776#define TYPE(Class, Base)
11777#define ABSTRACT_TYPE(Class, Base)
11778#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
11779#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
11780#define DEPENDENT_TYPE(Class, Base) case Type::Class:
11781#include "clang/AST/TypeNodes.inc"
11782 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
11783
11784 case Type::Auto:
11785 case Type::DeducedTemplateSpecialization:
11786 case Type::LValueReference:
11787 case Type::RValueReference:
11788 case Type::MemberPointer:
11789 llvm_unreachable("C++ should never be in mergeTypes");
11790
11791 case Type::ObjCInterface:
11792 case Type::IncompleteArray:
11793 case Type::VariableArray:
11794 case Type::FunctionProto:
11795 case Type::ExtVector:
11796 llvm_unreachable("Types are eliminated above");
11797
11798 case Type::Pointer:
11799 {
11800 // Merge two pointer types, while trying to preserve typedef info
11801 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
11802 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
11803 if (Unqualified) {
11804 LHSPointee = LHSPointee.getUnqualifiedType();
11805 RHSPointee = RHSPointee.getUnqualifiedType();
11806 }
11807 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
11808 Unqualified);
11809 if (ResultType.isNull())
11810 return {};
11811 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
11812 return LHS;
11813 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
11814 return RHS;
11815 return getPointerType(ResultType);
11816 }
11817 case Type::BlockPointer:
11818 {
11819 // Merge two block pointer types, while trying to preserve typedef info
11820 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
11821 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
11822 if (Unqualified) {
11823 LHSPointee = LHSPointee.getUnqualifiedType();
11824 RHSPointee = RHSPointee.getUnqualifiedType();
11825 }
11826 if (getLangOpts().OpenCL) {
11827 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
11828 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
11829 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
11830 // 6.12.5) thus the following check is asymmetric.
11831 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual, *this))
11832 return {};
11833 LHSPteeQual.removeAddressSpace();
11834 RHSPteeQual.removeAddressSpace();
11835 LHSPointee =
11836 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
11837 RHSPointee =
11838 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
11839 }
11840 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
11841 Unqualified);
11842 if (ResultType.isNull())
11843 return {};
11844 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
11845 return LHS;
11846 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
11847 return RHS;
11848 return getBlockPointerType(ResultType);
11849 }
11850 case Type::Atomic:
11851 {
11852 // Merge two pointer types, while trying to preserve typedef info
11853 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
11854 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
11855 if (Unqualified) {
11856 LHSValue = LHSValue.getUnqualifiedType();
11857 RHSValue = RHSValue.getUnqualifiedType();
11858 }
11859 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
11860 Unqualified);
11861 if (ResultType.isNull())
11862 return {};
11863 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
11864 return LHS;
11865 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
11866 return RHS;
11867 return getAtomicType(ResultType);
11868 }
11869 case Type::ConstantArray:
11870 {
11871 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
11872 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
11873 if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize())
11874 return {};
11875
11876 QualType LHSElem = getAsArrayType(LHS)->getElementType();
11877 QualType RHSElem = getAsArrayType(RHS)->getElementType();
11878 if (Unqualified) {
11879 LHSElem = LHSElem.getUnqualifiedType();
11880 RHSElem = RHSElem.getUnqualifiedType();
11881 }
11882
11883 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
11884 if (ResultType.isNull())
11885 return {};
11886
11887 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
11888 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
11889
11890 // If either side is a variable array, and both are complete, check whether
11891 // the current dimension is definite.
11892 if (LVAT || RVAT) {
11893 auto SizeFetch = [this](const VariableArrayType* VAT,
11894 const ConstantArrayType* CAT)
11895 -> std::pair<bool,llvm::APInt> {
11896 if (VAT) {
11897 std::optional<llvm::APSInt> TheInt;
11898 Expr *E = VAT->getSizeExpr();
11899 if (E && (TheInt = E->getIntegerConstantExpr(*this)))
11900 return std::make_pair(true, *TheInt);
11901 return std::make_pair(false, llvm::APSInt());
11902 }
11903 if (CAT)
11904 return std::make_pair(true, CAT->getSize());
11905 return std::make_pair(false, llvm::APInt());
11906 };
11907
11908 bool HaveLSize, HaveRSize;
11909 llvm::APInt LSize, RSize;
11910 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
11911 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
11912 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
11913 return {}; // Definite, but unequal, array dimension
11914 }
11915
11916 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
11917 return LHS;
11918 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
11919 return RHS;
11920 if (LCAT)
11921 return getConstantArrayType(ResultType, LCAT->getSize(),
11922 LCAT->getSizeExpr(), ArraySizeModifier(), 0);
11923 if (RCAT)
11924 return getConstantArrayType(ResultType, RCAT->getSize(),
11925 RCAT->getSizeExpr(), ArraySizeModifier(), 0);
11926 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
11927 return LHS;
11928 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
11929 return RHS;
11930 if (LVAT) {
11931 // FIXME: This isn't correct! But tricky to implement because
11932 // the array's size has to be the size of LHS, but the type
11933 // has to be different.
11934 return LHS;
11935 }
11936 if (RVAT) {
11937 // FIXME: This isn't correct! But tricky to implement because
11938 // the array's size has to be the size of RHS, but the type
11939 // has to be different.
11940 return RHS;
11941 }
11942 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
11943 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
11944 return getIncompleteArrayType(ResultType, ArraySizeModifier(), 0);
11945 }
11946 case Type::FunctionNoProto:
11947 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified,
11948 /*AllowCXX=*/false, IsConditionalOperator);
11949 case Type::Record:
11950 case Type::Enum:
11951 return mergeTagDefinitions(LHS, RHS);
11952 case Type::Builtin:
11953 // Only exactly equal builtin types are compatible, which is tested above.
11954 return {};
11955 case Type::Complex:
11956 // Distinct complex types are incompatible.
11957 return {};
11958 case Type::Vector:
11959 // FIXME: The merged type should be an ExtVector!
11960 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
11961 RHSCan->castAs<VectorType>()))
11962 return LHS;
11963 return {};
11964 case Type::ConstantMatrix:
11966 RHSCan->castAs<ConstantMatrixType>()))
11967 return LHS;
11968 return {};
11969 case Type::ObjCObject: {
11970 // Check if the types are assignment compatible.
11971 // FIXME: This should be type compatibility, e.g. whether
11972 // "LHS x; RHS x;" at global scope is legal.
11974 RHS->castAs<ObjCObjectType>()))
11975 return LHS;
11976 return {};
11977 }
11978 case Type::ObjCObjectPointer:
11979 if (OfBlockPointer) {
11982 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
11983 return LHS;
11984 return {};
11985 }
11988 return LHS;
11989 return {};
11990 case Type::Pipe:
11991 assert(LHS != RHS &&
11992 "Equivalent pipe types should have already been handled!");
11993 return {};
11994 case Type::ArrayParameter:
11995 assert(LHS != RHS &&
11996 "Equivalent ArrayParameter types should have already been handled!");
11997 return {};
11998 case Type::BitInt: {
11999 // Merge two bit-precise int types, while trying to preserve typedef info.
12000 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
12001 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
12002 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
12003 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
12004
12005 // Like unsigned/int, shouldn't have a type if they don't match.
12006 if (LHSUnsigned != RHSUnsigned)
12007 return {};
12008
12009 if (LHSBits != RHSBits)
12010 return {};
12011 return LHS;
12012 }
12013 case Type::HLSLAttributedResource: {
12014 const HLSLAttributedResourceType *LHSTy =
12015 LHS->castAs<HLSLAttributedResourceType>();
12016 const HLSLAttributedResourceType *RHSTy =
12017 RHS->castAs<HLSLAttributedResourceType>();
12018 assert(LHSTy->getWrappedType() == RHSTy->getWrappedType() &&
12019 LHSTy->getWrappedType()->isHLSLResourceType() &&
12020 "HLSLAttributedResourceType should always wrap __hlsl_resource_t");
12021
12022 if (LHSTy->getAttrs() == RHSTy->getAttrs() &&
12023 LHSTy->getContainedType() == RHSTy->getContainedType())
12024 return LHS;
12025 return {};
12026 }
12027 case Type::HLSLInlineSpirv:
12028 const HLSLInlineSpirvType *LHSTy = LHS->castAs<HLSLInlineSpirvType>();
12029 const HLSLInlineSpirvType *RHSTy = RHS->castAs<HLSLInlineSpirvType>();
12030
12031 if (LHSTy->getOpcode() == RHSTy->getOpcode() &&
12032 LHSTy->getSize() == RHSTy->getSize() &&
12033 LHSTy->getAlignment() == RHSTy->getAlignment()) {
12034 for (size_t I = 0; I < LHSTy->getOperands().size(); I++)
12035 if (LHSTy->getOperands()[I] != RHSTy->getOperands()[I])
12036 return {};
12037
12038 return LHS;
12039 }
12040 return {};
12041 }
12042
12043 llvm_unreachable("Invalid Type::Class!");
12044}
12045
12047 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
12048 bool &CanUseFirst, bool &CanUseSecond,
12050 assert(NewParamInfos.empty() && "param info list not empty");
12051 CanUseFirst = CanUseSecond = true;
12052 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
12053 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
12054
12055 // Fast path: if the first type doesn't have ext parameter infos,
12056 // we match if and only if the second type also doesn't have them.
12057 if (!FirstHasInfo && !SecondHasInfo)
12058 return true;
12059
12060 bool NeedParamInfo = false;
12061 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
12062 : SecondFnType->getExtParameterInfos().size();
12063
12064 for (size_t I = 0; I < E; ++I) {
12065 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
12066 if (FirstHasInfo)
12067 FirstParam = FirstFnType->getExtParameterInfo(I);
12068 if (SecondHasInfo)
12069 SecondParam = SecondFnType->getExtParameterInfo(I);
12070
12071 // Cannot merge unless everything except the noescape flag matches.
12072 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
12073 return false;
12074
12075 bool FirstNoEscape = FirstParam.isNoEscape();
12076 bool SecondNoEscape = SecondParam.isNoEscape();
12077 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
12078 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
12079 if (NewParamInfos.back().getOpaqueValue())
12080 NeedParamInfo = true;
12081 if (FirstNoEscape != IsNoEscape)
12082 CanUseFirst = false;
12083 if (SecondNoEscape != IsNoEscape)
12084 CanUseSecond = false;
12085 }
12086
12087 if (!NeedParamInfo)
12088 NewParamInfos.clear();
12089
12090 return true;
12091}
12092
12094 if (auto It = ObjCLayouts.find(D); It != ObjCLayouts.end()) {
12095 It->second = nullptr;
12096 for (auto *SubClass : ObjCSubClasses[D])
12097 ResetObjCLayout(SubClass);
12098 }
12099}
12100
12101/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
12102/// 'RHS' attributes and returns the merged version; including for function
12103/// return types.
12105 QualType LHSCan = getCanonicalType(LHS),
12106 RHSCan = getCanonicalType(RHS);
12107 // If two types are identical, they are compatible.
12108 if (LHSCan == RHSCan)
12109 return LHS;
12110 if (RHSCan->isFunctionType()) {
12111 if (!LHSCan->isFunctionType())
12112 return {};
12113 QualType OldReturnType =
12114 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
12115 QualType NewReturnType =
12116 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
12117 QualType ResReturnType =
12118 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
12119 if (ResReturnType.isNull())
12120 return {};
12121 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
12122 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
12123 // In either case, use OldReturnType to build the new function type.
12124 const auto *F = LHS->castAs<FunctionType>();
12125 if (const auto *FPT = cast<FunctionProtoType>(F)) {
12126 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12127 EPI.ExtInfo = getFunctionExtInfo(LHS);
12128 QualType ResultType =
12129 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
12130 return ResultType;
12131 }
12132 }
12133 return {};
12134 }
12135
12136 // If the qualifiers are different, the types can still be merged.
12137 Qualifiers LQuals = LHSCan.getLocalQualifiers();
12138 Qualifiers RQuals = RHSCan.getLocalQualifiers();
12139 if (LQuals != RQuals) {
12140 // If any of these qualifiers are different, we have a type mismatch.
12141 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
12142 LQuals.getAddressSpace() != RQuals.getAddressSpace())
12143 return {};
12144
12145 // Exactly one GC qualifier difference is allowed: __strong is
12146 // okay if the other type has no GC qualifier but is an Objective
12147 // C object pointer (i.e. implicitly strong by default). We fix
12148 // this by pretending that the unqualified type was actually
12149 // qualified __strong.
12150 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
12151 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
12152 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
12153
12154 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
12155 return {};
12156
12157 if (GC_L == Qualifiers::Strong)
12158 return LHS;
12159 if (GC_R == Qualifiers::Strong)
12160 return RHS;
12161 return {};
12162 }
12163
12164 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
12165 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12166 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12167 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
12168 if (ResQT == LHSBaseQT)
12169 return LHS;
12170 if (ResQT == RHSBaseQT)
12171 return RHS;
12172 }
12173 return {};
12174}
12175
12176//===----------------------------------------------------------------------===//
12177// Integer Predicates
12178//===----------------------------------------------------------------------===//
12179
12181 if (const auto *ED = T->getAsEnumDecl())
12182 T = ED->getIntegerType();
12183 if (T->isBooleanType())
12184 return 1;
12185 if (const auto *EIT = T->getAs<BitIntType>())
12186 return EIT->getNumBits();
12187 // For builtin types, just use the standard type sizing method
12188 return (unsigned)getTypeSize(T);
12189}
12190
12192 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12193 T->isFixedPointType()) &&
12194 "Unexpected type");
12195
12196 // Turn <4 x signed int> -> <4 x unsigned int>
12197 if (const auto *VTy = T->getAs<VectorType>())
12198 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
12199 VTy->getNumElements(), VTy->getVectorKind());
12200
12201 // For _BitInt, return an unsigned _BitInt with same width.
12202 if (const auto *EITy = T->getAs<BitIntType>())
12203 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits());
12204
12205 // For enums, get the underlying integer type of the enum, and let the general
12206 // integer type signchanging code handle it.
12207 if (const auto *ED = T->getAsEnumDecl())
12208 T = ED->getIntegerType();
12209
12210 switch (T->castAs<BuiltinType>()->getKind()) {
12211 case BuiltinType::Char_U:
12212 // Plain `char` is mapped to `unsigned char` even if it's already unsigned
12213 case BuiltinType::Char_S:
12214 case BuiltinType::SChar:
12215 case BuiltinType::Char8:
12216 return UnsignedCharTy;
12217 case BuiltinType::Short:
12218 return UnsignedShortTy;
12219 case BuiltinType::Int:
12220 return UnsignedIntTy;
12221 case BuiltinType::Long:
12222 return UnsignedLongTy;
12223 case BuiltinType::LongLong:
12224 return UnsignedLongLongTy;
12225 case BuiltinType::Int128:
12226 return UnsignedInt128Ty;
12227 // wchar_t is special. It is either signed or not, but when it's signed,
12228 // there's no matching "unsigned wchar_t". Therefore we return the unsigned
12229 // version of its underlying type instead.
12230 case BuiltinType::WChar_S:
12231 return getUnsignedWCharType();
12232
12233 case BuiltinType::ShortAccum:
12234 return UnsignedShortAccumTy;
12235 case BuiltinType::Accum:
12236 return UnsignedAccumTy;
12237 case BuiltinType::LongAccum:
12238 return UnsignedLongAccumTy;
12239 case BuiltinType::SatShortAccum:
12241 case BuiltinType::SatAccum:
12242 return SatUnsignedAccumTy;
12243 case BuiltinType::SatLongAccum:
12245 case BuiltinType::ShortFract:
12246 return UnsignedShortFractTy;
12247 case BuiltinType::Fract:
12248 return UnsignedFractTy;
12249 case BuiltinType::LongFract:
12250 return UnsignedLongFractTy;
12251 case BuiltinType::SatShortFract:
12253 case BuiltinType::SatFract:
12254 return SatUnsignedFractTy;
12255 case BuiltinType::SatLongFract:
12257 default:
12258 assert((T->hasUnsignedIntegerRepresentation() ||
12259 T->isUnsignedFixedPointType()) &&
12260 "Unexpected signed integer or fixed point type");
12261 return T;
12262 }
12263}
12264
12266 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12267 T->isFixedPointType()) &&
12268 "Unexpected type");
12269
12270 // Turn <4 x unsigned int> -> <4 x signed int>
12271 if (const auto *VTy = T->getAs<VectorType>())
12272 return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
12273 VTy->getNumElements(), VTy->getVectorKind());
12274
12275 // For _BitInt, return a signed _BitInt with same width.
12276 if (const auto *EITy = T->getAs<BitIntType>())
12277 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits());
12278
12279 // For enums, get the underlying integer type of the enum, and let the general
12280 // integer type signchanging code handle it.
12281 if (const auto *ED = T->getAsEnumDecl())
12282 T = ED->getIntegerType();
12283
12284 switch (T->castAs<BuiltinType>()->getKind()) {
12285 case BuiltinType::Char_S:
12286 // Plain `char` is mapped to `signed char` even if it's already signed
12287 case BuiltinType::Char_U:
12288 case BuiltinType::UChar:
12289 case BuiltinType::Char8:
12290 return SignedCharTy;
12291 case BuiltinType::UShort:
12292 return ShortTy;
12293 case BuiltinType::UInt:
12294 return IntTy;
12295 case BuiltinType::ULong:
12296 return LongTy;
12297 case BuiltinType::ULongLong:
12298 return LongLongTy;
12299 case BuiltinType::UInt128:
12300 return Int128Ty;
12301 // wchar_t is special. It is either unsigned or not, but when it's unsigned,
12302 // there's no matching "signed wchar_t". Therefore we return the signed
12303 // version of its underlying type instead.
12304 case BuiltinType::WChar_U:
12305 return getSignedWCharType();
12306
12307 case BuiltinType::UShortAccum:
12308 return ShortAccumTy;
12309 case BuiltinType::UAccum:
12310 return AccumTy;
12311 case BuiltinType::ULongAccum:
12312 return LongAccumTy;
12313 case BuiltinType::SatUShortAccum:
12314 return SatShortAccumTy;
12315 case BuiltinType::SatUAccum:
12316 return SatAccumTy;
12317 case BuiltinType::SatULongAccum:
12318 return SatLongAccumTy;
12319 case BuiltinType::UShortFract:
12320 return ShortFractTy;
12321 case BuiltinType::UFract:
12322 return FractTy;
12323 case BuiltinType::ULongFract:
12324 return LongFractTy;
12325 case BuiltinType::SatUShortFract:
12326 return SatShortFractTy;
12327 case BuiltinType::SatUFract:
12328 return SatFractTy;
12329 case BuiltinType::SatULongFract:
12330 return SatLongFractTy;
12331 default:
12332 assert(
12333 (T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
12334 "Unexpected signed integer or fixed point type");
12335 return T;
12336 }
12337}
12338
12340
12343
12344//===----------------------------------------------------------------------===//
12345// Builtin Type Computation
12346//===----------------------------------------------------------------------===//
12347
12348/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
12349/// pointer over the consumed characters. This returns the resultant type. If
12350/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
12351/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
12352/// a vector of "i*".
12353///
12354/// RequiresICE is filled in on return to indicate whether the value is required
12355/// to be an Integer Constant Expression.
12356static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
12358 bool &RequiresICE,
12359 bool AllowTypeModifiers) {
12360 // Modifiers.
12361 int HowLong = 0;
12362 bool Signed = false, Unsigned = false;
12363 RequiresICE = false;
12364
12365 // Read the prefixed modifiers first.
12366 bool Done = false;
12367 #ifndef NDEBUG
12368 bool IsSpecial = false;
12369 #endif
12370 while (!Done) {
12371 switch (*Str++) {
12372 default: Done = true; --Str; break;
12373 case 'I':
12374 RequiresICE = true;
12375 break;
12376 case 'S':
12377 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
12378 assert(!Signed && "Can't use 'S' modifier multiple times!");
12379 Signed = true;
12380 break;
12381 case 'U':
12382 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
12383 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
12384 Unsigned = true;
12385 break;
12386 case 'L':
12387 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
12388 assert(HowLong <= 2 && "Can't have LLLL modifier");
12389 ++HowLong;
12390 break;
12391 case 'N':
12392 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
12393 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12394 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
12395 #ifndef NDEBUG
12396 IsSpecial = true;
12397 #endif
12398 if (Context.getTargetInfo().getLongWidth() == 32)
12399 ++HowLong;
12400 break;
12401 case 'W':
12402 // This modifier represents int64 type.
12403 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12404 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
12405 #ifndef NDEBUG
12406 IsSpecial = true;
12407 #endif
12408 switch (Context.getTargetInfo().getInt64Type()) {
12409 default:
12410 llvm_unreachable("Unexpected integer type");
12412 HowLong = 1;
12413 break;
12415 HowLong = 2;
12416 break;
12417 }
12418 break;
12419 case 'Z':
12420 // This modifier represents int32 type.
12421 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12422 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
12423 #ifndef NDEBUG
12424 IsSpecial = true;
12425 #endif
12426 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
12427 default:
12428 llvm_unreachable("Unexpected integer type");
12430 HowLong = 0;
12431 break;
12433 HowLong = 1;
12434 break;
12436 HowLong = 2;
12437 break;
12438 }
12439 break;
12440 case 'O':
12441 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12442 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
12443 #ifndef NDEBUG
12444 IsSpecial = true;
12445 #endif
12446 if (Context.getLangOpts().OpenCL)
12447 HowLong = 1;
12448 else
12449 HowLong = 2;
12450 break;
12451 }
12452 }
12453
12454 QualType Type;
12455
12456 // Read the base type.
12457 switch (*Str++) {
12458 default: llvm_unreachable("Unknown builtin type letter!");
12459 case 'x':
12460 assert(HowLong == 0 && !Signed && !Unsigned &&
12461 "Bad modifiers used with 'x'!");
12462 Type = Context.Float16Ty;
12463 break;
12464 case 'y':
12465 assert(HowLong == 0 && !Signed && !Unsigned &&
12466 "Bad modifiers used with 'y'!");
12467 Type = Context.BFloat16Ty;
12468 break;
12469 case 'v':
12470 assert(HowLong == 0 && !Signed && !Unsigned &&
12471 "Bad modifiers used with 'v'!");
12472 Type = Context.VoidTy;
12473 break;
12474 case 'h':
12475 assert(HowLong == 0 && !Signed && !Unsigned &&
12476 "Bad modifiers used with 'h'!");
12477 Type = Context.HalfTy;
12478 break;
12479 case 'f':
12480 assert(HowLong == 0 && !Signed && !Unsigned &&
12481 "Bad modifiers used with 'f'!");
12482 Type = Context.FloatTy;
12483 break;
12484 case 'd':
12485 assert(HowLong < 3 && !Signed && !Unsigned &&
12486 "Bad modifiers used with 'd'!");
12487 if (HowLong == 1)
12488 Type = Context.LongDoubleTy;
12489 else if (HowLong == 2)
12490 Type = Context.Float128Ty;
12491 else
12492 Type = Context.DoubleTy;
12493 break;
12494 case 's':
12495 assert(HowLong == 0 && "Bad modifiers used with 's'!");
12496 if (Unsigned)
12497 Type = Context.UnsignedShortTy;
12498 else
12499 Type = Context.ShortTy;
12500 break;
12501 case 'i':
12502 if (HowLong == 3)
12503 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
12504 else if (HowLong == 2)
12505 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
12506 else if (HowLong == 1)
12507 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
12508 else
12509 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
12510 break;
12511 case 'c':
12512 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
12513 if (Signed)
12514 Type = Context.SignedCharTy;
12515 else if (Unsigned)
12516 Type = Context.UnsignedCharTy;
12517 else
12518 Type = Context.CharTy;
12519 break;
12520 case 'b': // boolean
12521 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
12522 Type = Context.BoolTy;
12523 break;
12524 case 'z': // size_t.
12525 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
12526 Type = Context.getSizeType();
12527 break;
12528 case 'w': // wchar_t.
12529 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
12530 Type = Context.getWideCharType();
12531 break;
12532 case 'F':
12533 Type = Context.getCFConstantStringType();
12534 break;
12535 case 'G':
12536 Type = Context.getObjCIdType();
12537 break;
12538 case 'H':
12539 Type = Context.getObjCSelType();
12540 break;
12541 case 'M':
12542 Type = Context.getObjCSuperType();
12543 break;
12544 case 'a':
12545 Type = Context.getBuiltinVaListType();
12546 assert(!Type.isNull() && "builtin va list type not initialized!");
12547 break;
12548 case 'A':
12549 // This is a "reference" to a va_list; however, what exactly
12550 // this means depends on how va_list is defined. There are two
12551 // different kinds of va_list: ones passed by value, and ones
12552 // passed by reference. An example of a by-value va_list is
12553 // x86, where va_list is a char*. An example of by-ref va_list
12554 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
12555 // we want this argument to be a char*&; for x86-64, we want
12556 // it to be a __va_list_tag*.
12557 Type = Context.getBuiltinVaListType();
12558 assert(!Type.isNull() && "builtin va list type not initialized!");
12559 if (Type->isArrayType())
12560 Type = Context.getArrayDecayedType(Type);
12561 else
12562 Type = Context.getLValueReferenceType(Type);
12563 break;
12564 case 'q': {
12565 char *End;
12566 unsigned NumElements = strtoul(Str, &End, 10);
12567 assert(End != Str && "Missing vector size");
12568 Str = End;
12569
12570 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12571 RequiresICE, false);
12572 assert(!RequiresICE && "Can't require vector ICE");
12573
12574 Type = Context.getScalableVectorType(ElementType, NumElements);
12575 break;
12576 }
12577 case 'Q': {
12578 switch (*Str++) {
12579 case 'a': {
12580 Type = Context.SveCountTy;
12581 break;
12582 }
12583 case 'b': {
12584 Type = Context.AMDGPUBufferRsrcTy;
12585 break;
12586 }
12587 default:
12588 llvm_unreachable("Unexpected target builtin type");
12589 }
12590 break;
12591 }
12592 case 'V': {
12593 char *End;
12594 unsigned NumElements = strtoul(Str, &End, 10);
12595 assert(End != Str && "Missing vector size");
12596 Str = End;
12597
12598 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12599 RequiresICE, false);
12600 assert(!RequiresICE && "Can't require vector ICE");
12601
12602 // TODO: No way to make AltiVec vectors in builtins yet.
12603 Type = Context.getVectorType(ElementType, NumElements, VectorKind::Generic);
12604 break;
12605 }
12606 case 'E': {
12607 char *End;
12608
12609 unsigned NumElements = strtoul(Str, &End, 10);
12610 assert(End != Str && "Missing vector size");
12611
12612 Str = End;
12613
12614 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12615 false);
12616 Type = Context.getExtVectorType(ElementType, NumElements);
12617 break;
12618 }
12619 case 'X': {
12620 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12621 false);
12622 assert(!RequiresICE && "Can't require complex ICE");
12623 Type = Context.getComplexType(ElementType);
12624 break;
12625 }
12626 case 'Y':
12627 Type = Context.getPointerDiffType();
12628 break;
12629 case 'P':
12630 Type = Context.getFILEType();
12631 if (Type.isNull()) {
12633 return {};
12634 }
12635 break;
12636 case 'J':
12637 if (Signed)
12638 Type = Context.getsigjmp_bufType();
12639 else
12640 Type = Context.getjmp_bufType();
12641
12642 if (Type.isNull()) {
12644 return {};
12645 }
12646 break;
12647 case 'K':
12648 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
12649 Type = Context.getucontext_tType();
12650
12651 if (Type.isNull()) {
12653 return {};
12654 }
12655 break;
12656 case 'p':
12657 Type = Context.getProcessIDType();
12658 break;
12659 case 'm':
12660 Type = Context.MFloat8Ty;
12661 break;
12662 }
12663
12664 // If there are modifiers and if we're allowed to parse them, go for it.
12665 Done = !AllowTypeModifiers;
12666 while (!Done) {
12667 switch (char c = *Str++) {
12668 default: Done = true; --Str; break;
12669 case '*':
12670 case '&': {
12671 // Both pointers and references can have their pointee types
12672 // qualified with an address space.
12673 char *End;
12674 unsigned AddrSpace = strtoul(Str, &End, 10);
12675 if (End != Str) {
12676 // Note AddrSpace == 0 is not the same as an unspecified address space.
12677 Type = Context.getAddrSpaceQualType(
12678 Type,
12679 Context.getLangASForBuiltinAddressSpace(AddrSpace));
12680 Str = End;
12681 }
12682 if (c == '*')
12683 Type = Context.getPointerType(Type);
12684 else
12685 Type = Context.getLValueReferenceType(Type);
12686 break;
12687 }
12688 // FIXME: There's no way to have a built-in with an rvalue ref arg.
12689 case 'C':
12690 Type = Type.withConst();
12691 break;
12692 case 'D':
12693 Type = Context.getVolatileType(Type);
12694 break;
12695 case 'R':
12696 Type = Type.withRestrict();
12697 break;
12698 }
12699 }
12700
12701 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
12702 "Integer constant 'I' type must be an integer");
12703
12704 return Type;
12705}
12706
12707// On some targets such as PowerPC, some of the builtins are defined with custom
12708// type descriptors for target-dependent types. These descriptors are decoded in
12709// other functions, but it may be useful to be able to fall back to default
12710// descriptor decoding to define builtins mixing target-dependent and target-
12711// independent types. This function allows decoding one type descriptor with
12712// default decoding.
12713QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
12714 GetBuiltinTypeError &Error, bool &RequireICE,
12715 bool AllowTypeModifiers) const {
12716 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
12717}
12718
12719/// GetBuiltinType - Return the type for the specified builtin.
12722 unsigned *IntegerConstantArgs) const {
12723 const char *TypeStr = BuiltinInfo.getTypeString(Id);
12724 if (TypeStr[0] == '\0') {
12726 return {};
12727 }
12728
12729 SmallVector<QualType, 8> ArgTypes;
12730
12731 bool RequiresICE = false;
12732 Error = GE_None;
12733 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
12734 RequiresICE, true);
12735 if (Error != GE_None)
12736 return {};
12737
12738 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
12739
12740 while (TypeStr[0] && TypeStr[0] != '.') {
12741 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
12742 if (Error != GE_None)
12743 return {};
12744
12745 // If this argument is required to be an IntegerConstantExpression and the
12746 // caller cares, fill in the bitmask we return.
12747 if (RequiresICE && IntegerConstantArgs)
12748 *IntegerConstantArgs |= 1 << ArgTypes.size();
12749
12750 // Do array -> pointer decay. The builtin should use the decayed type.
12751 if (Ty->isArrayType())
12752 Ty = getArrayDecayedType(Ty);
12753
12754 ArgTypes.push_back(Ty);
12755 }
12756
12757 if (Id == Builtin::BI__GetExceptionInfo)
12758 return {};
12759
12760 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
12761 "'.' should only occur at end of builtin type list!");
12762
12763 bool Variadic = (TypeStr[0] == '.');
12764
12765 FunctionType::ExtInfo EI(Target->getDefaultCallingConv());
12766 if (BuiltinInfo.isNoReturn(Id))
12767 EI = EI.withNoReturn(true);
12768
12769 // We really shouldn't be making a no-proto type here.
12770 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
12771 return getFunctionNoProtoType(ResType, EI);
12772
12774 EPI.ExtInfo = EI;
12775 EPI.Variadic = Variadic;
12776 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
12777 EPI.ExceptionSpec.Type =
12779
12780 return getFunctionType(ResType, ArgTypes, EPI);
12781}
12782
12784 const FunctionDecl *FD) {
12785 if (!FD->isExternallyVisible())
12786 return GVA_Internal;
12787
12788 // Non-user-provided functions get emitted as weak definitions with every
12789 // use, no matter whether they've been explicitly instantiated etc.
12790 if (!FD->isUserProvided())
12791 return GVA_DiscardableODR;
12792
12794 switch (FD->getTemplateSpecializationKind()) {
12795 case TSK_Undeclared:
12798 break;
12799
12801 return GVA_StrongODR;
12802
12803 // C++11 [temp.explicit]p10:
12804 // [ Note: The intent is that an inline function that is the subject of
12805 // an explicit instantiation declaration will still be implicitly
12806 // instantiated when used so that the body can be considered for
12807 // inlining, but that no out-of-line copy of the inline function would be
12808 // generated in the translation unit. -- end note ]
12811
12814 break;
12815 }
12816
12817 if (!FD->isInlined())
12818 return External;
12819
12820 if ((!Context.getLangOpts().CPlusPlus &&
12821 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12822 !FD->hasAttr<DLLExportAttr>()) ||
12823 FD->hasAttr<GNUInlineAttr>()) {
12824 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
12825
12826 // GNU or C99 inline semantics. Determine whether this symbol should be
12827 // externally visible.
12829 return External;
12830
12831 // C99 inline semantics, where the symbol is not externally visible.
12833 }
12834
12835 // Functions specified with extern and inline in -fms-compatibility mode
12836 // forcibly get emitted. While the body of the function cannot be later
12837 // replaced, the function definition cannot be discarded.
12838 if (FD->isMSExternInline())
12839 return GVA_StrongODR;
12840
12841 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12843 cast<CXXConstructorDecl>(FD)->isInheritingConstructor())
12844 // Our approach to inheriting constructors is fundamentally different from
12845 // that used by the MS ABI, so keep our inheriting constructor thunks
12846 // internal rather than trying to pick an unambiguous mangling for them.
12847 return GVA_Internal;
12848
12849 return GVA_DiscardableODR;
12850}
12851
12853 const Decl *D, GVALinkage L) {
12854 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
12855 // dllexport/dllimport on inline functions.
12856 if (D->hasAttr<DLLImportAttr>()) {
12857 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
12859 } else if (D->hasAttr<DLLExportAttr>()) {
12860 if (L == GVA_DiscardableODR)
12861 return GVA_StrongODR;
12862 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
12863 // Device-side functions with __global__ attribute must always be
12864 // visible externally so they can be launched from host.
12865 if (D->hasAttr<CUDAGlobalAttr>() &&
12866 (L == GVA_DiscardableODR || L == GVA_Internal))
12867 return GVA_StrongODR;
12868 // Single source offloading languages like CUDA/HIP need to be able to
12869 // access static device variables from host code of the same compilation
12870 // unit. This is done by externalizing the static variable with a shared
12871 // name between the host and device compilation which is the same for the
12872 // same compilation unit whereas different among different compilation
12873 // units.
12874 if (Context.shouldExternalize(D))
12875 return GVA_StrongExternal;
12876 }
12877 return L;
12878}
12879
12880/// Adjust the GVALinkage for a declaration based on what an external AST source
12881/// knows about whether there can be other definitions of this declaration.
12882static GVALinkage
12884 GVALinkage L) {
12885 ExternalASTSource *Source = Ctx.getExternalSource();
12886 if (!Source)
12887 return L;
12888
12889 switch (Source->hasExternalDefinitions(D)) {
12891 // Other translation units rely on us to provide the definition.
12892 if (L == GVA_DiscardableODR)
12893 return GVA_StrongODR;
12894 break;
12895
12898
12900 break;
12901 }
12902 return L;
12903}
12904
12910
12912 const VarDecl *VD) {
12913 // As an extension for interactive REPLs, make sure constant variables are
12914 // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
12915 // marking them as internal.
12916 if (Context.getLangOpts().CPlusPlus &&
12917 Context.getLangOpts().IncrementalExtensions &&
12918 VD->getType().isConstQualified() &&
12919 !VD->getType().isVolatileQualified() && !VD->isInline() &&
12921 return GVA_DiscardableODR;
12922
12923 if (!VD->isExternallyVisible())
12924 return GVA_Internal;
12925
12926 if (VD->isStaticLocal()) {
12927 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
12928 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
12929 LexicalContext = LexicalContext->getLexicalParent();
12930
12931 // ObjC Blocks can create local variables that don't have a FunctionDecl
12932 // LexicalContext.
12933 if (!LexicalContext)
12934 return GVA_DiscardableODR;
12935
12936 // Otherwise, let the static local variable inherit its linkage from the
12937 // nearest enclosing function.
12938 auto StaticLocalLinkage =
12939 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
12940
12941 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
12942 // be emitted in any object with references to the symbol for the object it
12943 // contains, whether inline or out-of-line."
12944 // Similar behavior is observed with MSVC. An alternative ABI could use
12945 // StrongODR/AvailableExternally to match the function, but none are
12946 // known/supported currently.
12947 if (StaticLocalLinkage == GVA_StrongODR ||
12948 StaticLocalLinkage == GVA_AvailableExternally)
12949 return GVA_DiscardableODR;
12950 return StaticLocalLinkage;
12951 }
12952
12953 // MSVC treats in-class initialized static data members as definitions.
12954 // By giving them non-strong linkage, out-of-line definitions won't
12955 // cause link errors.
12956 if (Context.isMSStaticDataMemberInlineDefinition(VD))
12957 return GVA_DiscardableODR;
12958
12959 // Most non-template variables have strong linkage; inline variables are
12960 // linkonce_odr or (occasionally, for compatibility) weak_odr.
12961 GVALinkage StrongLinkage;
12962 switch (Context.getInlineVariableDefinitionKind(VD)) {
12964 StrongLinkage = GVA_StrongExternal;
12965 break;
12968 StrongLinkage = GVA_DiscardableODR;
12969 break;
12971 StrongLinkage = GVA_StrongODR;
12972 break;
12973 }
12974
12975 switch (VD->getTemplateSpecializationKind()) {
12976 case TSK_Undeclared:
12977 return StrongLinkage;
12978
12980 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12981 VD->isStaticDataMember()
12983 : StrongLinkage;
12984
12986 return GVA_StrongODR;
12987
12990
12992 return GVA_DiscardableODR;
12993 }
12994
12995 llvm_unreachable("Invalid Linkage!");
12996}
12997
13003
13005 if (const auto *VD = dyn_cast<VarDecl>(D)) {
13006 if (!VD->isFileVarDecl())
13007 return false;
13008 // Global named register variables (GNU extension) are never emitted.
13009 if (VD->getStorageClass() == SC_Register)
13010 return false;
13011 if (VD->getDescribedVarTemplate() ||
13013 return false;
13014 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13015 // We never need to emit an uninstantiated function template.
13016 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13017 return false;
13018 } else if (isa<PragmaCommentDecl>(D))
13019 return true;
13021 return true;
13022 else if (isa<OMPRequiresDecl>(D))
13023 return true;
13024 else if (isa<OMPThreadPrivateDecl>(D))
13025 return !D->getDeclContext()->isDependentContext();
13026 else if (isa<OMPAllocateDecl>(D))
13027 return !D->getDeclContext()->isDependentContext();
13029 return !D->getDeclContext()->isDependentContext();
13030 else if (isa<ImportDecl>(D))
13031 return true;
13032 else
13033 return false;
13034
13035 // If this is a member of a class template, we do not need to emit it.
13037 return false;
13038
13039 // Weak references don't produce any output by themselves.
13040 if (D->hasAttr<WeakRefAttr>())
13041 return false;
13042
13043 // SYCL device compilation requires that functions defined with the
13044 // sycl_kernel_entry_point or sycl_external attributes be emitted. All
13045 // other entities are emitted only if they are used by a function
13046 // defined with one of those attributes.
13047 if (LangOpts.SYCLIsDevice)
13048 return isa<FunctionDecl>(D) && (D->hasAttr<SYCLKernelEntryPointAttr>() ||
13049 D->hasAttr<SYCLExternalAttr>());
13050
13051 // Aliases and used decls are required.
13052 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
13053 return true;
13054
13055 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13056 // Forward declarations aren't required.
13057 if (!FD->doesThisDeclarationHaveABody())
13058 return FD->doesDeclarationForceExternallyVisibleDefinition();
13059
13060 // Constructors and destructors are required.
13061 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
13062 return true;
13063
13064 // The key function for a class is required. This rule only comes
13065 // into play when inline functions can be key functions, though.
13066 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13067 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13068 const CXXRecordDecl *RD = MD->getParent();
13069 if (MD->isOutOfLine() && RD->isDynamicClass()) {
13070 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
13071 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
13072 return true;
13073 }
13074 }
13075 }
13076
13078
13079 // static, static inline, always_inline, and extern inline functions can
13080 // always be deferred. Normal inline functions can be deferred in C99/C++.
13081 // Implicit template instantiations can also be deferred in C++.
13083 }
13084
13085 const auto *VD = cast<VarDecl>(D);
13086 assert(VD->isFileVarDecl() && "Expected file scoped var");
13087
13088 // If the decl is marked as `declare target to`, it should be emitted for the
13089 // host and for the device.
13090 if (LangOpts.OpenMP &&
13091 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
13092 return true;
13093
13094 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
13096 return false;
13097
13098 if (VD->shouldEmitInExternalSource())
13099 return false;
13100
13101 // Variables that can be needed in other TUs are required.
13104 return true;
13105
13106 // We never need to emit a variable that is available in another TU.
13108 return false;
13109
13110 // Variables that have destruction with side-effects are required.
13111 if (VD->needsDestruction(*this))
13112 return true;
13113
13114 // Variables that have initialization with side-effects are required.
13115 if (VD->hasInitWithSideEffects())
13116 return true;
13117
13118 // Likewise, variables with tuple-like bindings are required if their
13119 // bindings have side-effects.
13120 if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) {
13121 for (const auto *BD : DD->flat_bindings())
13122 if (const auto *BindingVD = BD->getHoldingVar())
13123 if (DeclMustBeEmitted(BindingVD))
13124 return true;
13125 }
13126
13127 return false;
13128}
13129
13131 const FunctionDecl *FD,
13132 llvm::function_ref<void(FunctionDecl *)> Pred) const {
13133 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
13134 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
13135 FD = FD->getMostRecentDecl();
13136 // FIXME: The order of traversal here matters and depends on the order of
13137 // lookup results, which happens to be (mostly) oldest-to-newest, but we
13138 // shouldn't rely on that.
13139 for (auto *CurDecl :
13141 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
13142 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
13143 SeenDecls.insert(CurFD).second) {
13144 Pred(CurFD);
13145 }
13146 }
13147}
13148
13150 bool IsCXXMethod) const {
13151 // Pass through to the C++ ABI object
13152 if (IsCXXMethod)
13153 return ABI->getDefaultMethodCallConv(IsVariadic);
13154
13155 switch (LangOpts.getDefaultCallingConv()) {
13157 break;
13159 return CC_C;
13161 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
13162 return CC_X86FastCall;
13163 break;
13165 if (!IsVariadic)
13166 return CC_X86StdCall;
13167 break;
13169 // __vectorcall cannot be applied to variadic functions.
13170 if (!IsVariadic)
13171 return CC_X86VectorCall;
13172 break;
13174 // __regcall cannot be applied to variadic functions.
13175 if (!IsVariadic)
13176 return CC_X86RegCall;
13177 break;
13179 if (!IsVariadic)
13180 return CC_M68kRTD;
13181 break;
13182 }
13183 return Target->getDefaultCallingConv();
13184}
13185
13187 // Pass through to the C++ ABI object
13188 return ABI->isNearlyEmpty(RD);
13189}
13190
13192 if (!VTContext) {
13193 auto ABI = Target->getCXXABI();
13194 if (ABI.isMicrosoft())
13195 VTContext.reset(new MicrosoftVTableContext(*this));
13196 else {
13197 auto ComponentLayout = getLangOpts().RelativeCXXABIVTables
13200 VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout));
13201 }
13202 }
13203 return VTContext.get();
13204}
13205
13207 if (!T)
13208 T = Target;
13209 switch (T->getCXXABI().getKind()) {
13210 case TargetCXXABI::AppleARM64:
13211 case TargetCXXABI::Fuchsia:
13212 case TargetCXXABI::GenericAArch64:
13213 case TargetCXXABI::GenericItanium:
13214 case TargetCXXABI::GenericARM:
13215 case TargetCXXABI::GenericMIPS:
13216 case TargetCXXABI::iOS:
13217 case TargetCXXABI::WebAssembly:
13218 case TargetCXXABI::WatchOS:
13219 case TargetCXXABI::XL:
13221 case TargetCXXABI::Microsoft:
13223 }
13224 llvm_unreachable("Unsupported ABI");
13225}
13226
13228 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
13229 "Device mangle context does not support Microsoft mangling.");
13230 switch (T.getCXXABI().getKind()) {
13231 case TargetCXXABI::AppleARM64:
13232 case TargetCXXABI::Fuchsia:
13233 case TargetCXXABI::GenericAArch64:
13234 case TargetCXXABI::GenericItanium:
13235 case TargetCXXABI::GenericARM:
13236 case TargetCXXABI::GenericMIPS:
13237 case TargetCXXABI::iOS:
13238 case TargetCXXABI::WebAssembly:
13239 case TargetCXXABI::WatchOS:
13240 case TargetCXXABI::XL:
13242 *this, getDiagnostics(),
13243 [](ASTContext &, const NamedDecl *ND) -> UnsignedOrNone {
13244 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
13245 return RD->getDeviceLambdaManglingNumber();
13246 return std::nullopt;
13247 },
13248 /*IsAux=*/true);
13249 case TargetCXXABI::Microsoft:
13251 /*IsAux=*/true);
13252 }
13253 llvm_unreachable("Unsupported ABI");
13254}
13255
13256CXXABI::~CXXABI() = default;
13257
13259 return ASTRecordLayouts.getMemorySize() +
13260 llvm::capacity_in_bytes(ObjCLayouts) +
13261 llvm::capacity_in_bytes(KeyFunctions) +
13262 llvm::capacity_in_bytes(ObjCImpls) +
13263 llvm::capacity_in_bytes(BlockVarCopyInits) +
13264 llvm::capacity_in_bytes(DeclAttrs) +
13265 llvm::capacity_in_bytes(TemplateOrInstantiation) +
13266 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
13267 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
13268 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
13269 llvm::capacity_in_bytes(OverriddenMethods) +
13270 llvm::capacity_in_bytes(Types) +
13271 llvm::capacity_in_bytes(VariableArrayTypes);
13272}
13273
13274/// getIntTypeForBitwidth -
13275/// sets integer QualTy according to specified details:
13276/// bitwidth, signed/unsigned.
13277/// Returns empty type if there is no appropriate target types.
13279 unsigned Signed) const {
13281 CanQualType QualTy = getFromTargetType(Ty);
13282 if (!QualTy && DestWidth == 128)
13283 return Signed ? Int128Ty : UnsignedInt128Ty;
13284 return QualTy;
13285}
13286
13287/// getRealTypeForBitwidth -
13288/// sets floating point QualTy according to specified bitwidth.
13289/// Returns empty type if there is no appropriate target types.
13291 FloatModeKind ExplicitType) const {
13292 FloatModeKind Ty =
13293 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType);
13294 switch (Ty) {
13296 return HalfTy;
13298 return FloatTy;
13300 return DoubleTy;
13302 return LongDoubleTy;
13304 return Float128Ty;
13306 return Ibm128Ty;
13308 return {};
13309 }
13310
13311 llvm_unreachable("Unhandled TargetInfo::RealType value");
13312}
13313
13314void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
13315 if (Number <= 1)
13316 return;
13317
13318 MangleNumbers[ND] = Number;
13319
13320 if (Listener)
13321 Listener->AddedManglingNumber(ND, Number);
13322}
13323
13325 bool ForAuxTarget) const {
13326 auto I = MangleNumbers.find(ND);
13327 unsigned Res = I != MangleNumbers.end() ? I->second : 1;
13328 // CUDA/HIP host compilation encodes host and device mangling numbers
13329 // as lower and upper half of 32 bit integer.
13330 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
13331 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
13332 } else {
13333 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
13334 "number for aux target");
13335 }
13336 return Res > 1 ? Res : 1;
13337}
13338
13339void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
13340 if (Number <= 1)
13341 return;
13342
13343 StaticLocalNumbers[VD] = Number;
13344
13345 if (Listener)
13346 Listener->AddedStaticLocalNumbers(VD, Number);
13347}
13348
13350 auto I = StaticLocalNumbers.find(VD);
13351 return I != StaticLocalNumbers.end() ? I->second : 1;
13352}
13353
13355 bool IsDestroying) {
13356 if (!IsDestroying) {
13357 assert(!DestroyingOperatorDeletes.contains(FD->getCanonicalDecl()));
13358 return;
13359 }
13360 DestroyingOperatorDeletes.insert(FD->getCanonicalDecl());
13361}
13362
13364 return DestroyingOperatorDeletes.contains(FD->getCanonicalDecl());
13365}
13366
13368 bool IsTypeAware) {
13369 if (!IsTypeAware) {
13370 assert(!TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl()));
13371 return;
13372 }
13373 TypeAwareOperatorNewAndDeletes.insert(FD->getCanonicalDecl());
13374}
13375
13377 return TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl());
13378}
13379
13382 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13383 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
13384 if (!MCtx)
13386 return *MCtx;
13387}
13388
13391 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13392 std::unique_ptr<MangleNumberingContext> &MCtx =
13393 ExtraMangleNumberingContexts[D];
13394 if (!MCtx)
13396 return *MCtx;
13397}
13398
13399std::unique_ptr<MangleNumberingContext>
13401 return ABI->createMangleNumberingContext();
13402}
13403
13404const CXXConstructorDecl *
13406 return ABI->getCopyConstructorForExceptionObject(
13408}
13409
13411 CXXConstructorDecl *CD) {
13412 return ABI->addCopyConstructorForExceptionObject(
13415}
13416
13418 TypedefNameDecl *DD) {
13419 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
13420}
13421
13424 return ABI->getTypedefNameForUnnamedTagDecl(TD);
13425}
13426
13428 DeclaratorDecl *DD) {
13429 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
13430}
13431
13433 return ABI->getDeclaratorForUnnamedTagDecl(TD);
13434}
13435
13437 ParamIndices[D] = index;
13438}
13439
13441 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
13442 assert(I != ParamIndices.end() &&
13443 "ParmIndices lacks entry set by ParmVarDecl");
13444 return I->second;
13445}
13446
13448 unsigned Length) const {
13449 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
13450 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
13451 EltTy = EltTy.withConst();
13452
13453 EltTy = adjustStringLiteralBaseType(EltTy);
13454
13455 // Get an array type for the string, according to C99 6.4.5. This includes
13456 // the null terminator character.
13457 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
13458 ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0);
13459}
13460
13463 StringLiteral *&Result = StringLiteralCache[Key];
13464 if (!Result)
13466 *this, Key, StringLiteralKind::Ordinary,
13467 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
13468 SourceLocation());
13469 return Result;
13470}
13471
13472MSGuidDecl *
13474 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
13475
13476 llvm::FoldingSetNodeID ID;
13477 MSGuidDecl::Profile(ID, Parts);
13478
13479 void *InsertPos;
13480 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
13481 return Existing;
13482
13483 QualType GUIDType = getMSGuidType().withConst();
13484 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
13485 MSGuidDecls.InsertNode(New, InsertPos);
13486 return New;
13487}
13488
13491 const APValue &APVal) const {
13492 llvm::FoldingSetNodeID ID;
13494
13495 void *InsertPos;
13496 if (UnnamedGlobalConstantDecl *Existing =
13497 UnnamedGlobalConstantDecls.FindNodeOrInsertPos(ID, InsertPos))
13498 return Existing;
13499
13501 UnnamedGlobalConstantDecl::Create(*this, Ty, APVal);
13502 UnnamedGlobalConstantDecls.InsertNode(New, InsertPos);
13503 return New;
13504}
13505
13508 assert(T->isRecordType() && "template param object of unexpected type");
13509
13510 // C++ [temp.param]p8:
13511 // [...] a static storage duration object of type 'const T' [...]
13512 T.addConst();
13513
13514 llvm::FoldingSetNodeID ID;
13516
13517 void *InsertPos;
13518 if (TemplateParamObjectDecl *Existing =
13519 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
13520 return Existing;
13521
13522 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
13523 TemplateParamObjectDecls.InsertNode(New, InsertPos);
13524 return New;
13525}
13526
13528 const llvm::Triple &T = getTargetInfo().getTriple();
13529 if (!T.isOSDarwin())
13530 return false;
13531
13532 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
13533 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
13534 return false;
13535
13536 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
13537 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
13538 uint64_t Size = sizeChars.getQuantity();
13539 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
13540 unsigned Align = alignChars.getQuantity();
13541 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
13542 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
13543}
13544
13545bool
13547 const ObjCMethodDecl *MethodImpl) {
13548 // No point trying to match an unavailable/deprecated mothod.
13549 if (MethodDecl->hasAttr<UnavailableAttr>()
13550 || MethodDecl->hasAttr<DeprecatedAttr>())
13551 return false;
13552 if (MethodDecl->getObjCDeclQualifier() !=
13553 MethodImpl->getObjCDeclQualifier())
13554 return false;
13555 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
13556 return false;
13557
13558 if (MethodDecl->param_size() != MethodImpl->param_size())
13559 return false;
13560
13561 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
13562 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
13563 EF = MethodDecl->param_end();
13564 IM != EM && IF != EF; ++IM, ++IF) {
13565 const ParmVarDecl *DeclVar = (*IF);
13566 const ParmVarDecl *ImplVar = (*IM);
13567 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
13568 return false;
13569 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
13570 return false;
13571 }
13572
13573 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
13574}
13575
13577 LangAS AS;
13579 AS = LangAS::Default;
13580 else
13581 AS = QT->getPointeeType().getAddressSpace();
13582
13584}
13585
13588}
13589
13590bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
13591 if (X == Y)
13592 return true;
13593 if (!X || !Y)
13594 return false;
13595 llvm::FoldingSetNodeID IDX, IDY;
13596 X->Profile(IDX, *this, /*Canonical=*/true);
13597 Y->Profile(IDY, *this, /*Canonical=*/true);
13598 return IDX == IDY;
13599}
13600
13601// The getCommon* helpers return, for given 'same' X and Y entities given as
13602// inputs, another entity which is also the 'same' as the inputs, but which
13603// is closer to the canonical form of the inputs, each according to a given
13604// criteria.
13605// The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
13606// the regular ones.
13607
13609 if (!declaresSameEntity(X, Y))
13610 return nullptr;
13611 for (const Decl *DX : X->redecls()) {
13612 // If we reach Y before reaching the first decl, that means X is older.
13613 if (DX == Y)
13614 return X;
13615 // If we reach the first decl, then Y is older.
13616 if (DX->isFirstDecl())
13617 return Y;
13618 }
13619 llvm_unreachable("Corrupt redecls chain");
13620}
13621
13622template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13623static T *getCommonDecl(T *X, T *Y) {
13624 return cast_or_null<T>(
13625 getCommonDecl(const_cast<Decl *>(cast_or_null<Decl>(X)),
13626 const_cast<Decl *>(cast_or_null<Decl>(Y))));
13627}
13628
13629template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13630static T *getCommonDeclChecked(T *X, T *Y) {
13631 return cast<T>(getCommonDecl(const_cast<Decl *>(cast<Decl>(X)),
13632 const_cast<Decl *>(cast<Decl>(Y))));
13633}
13634
13636 TemplateName Y,
13637 bool IgnoreDeduced = false) {
13638 if (X.getAsVoidPointer() == Y.getAsVoidPointer())
13639 return X;
13640 // FIXME: There are cases here where we could find a common template name
13641 // with more sugar. For example one could be a SubstTemplateTemplate*
13642 // replacing the other.
13643 TemplateName CX = Ctx.getCanonicalTemplateName(X, IgnoreDeduced);
13644 if (CX.getAsVoidPointer() !=
13646 return TemplateName();
13647 return CX;
13648}
13649
13652 bool IgnoreDeduced) {
13653 TemplateName R = getCommonTemplateName(Ctx, X, Y, IgnoreDeduced);
13654 assert(R.getAsVoidPointer() != nullptr);
13655 return R;
13656}
13657
13659 ArrayRef<QualType> Ys, bool Unqualified = false) {
13660 assert(Xs.size() == Ys.size());
13661 SmallVector<QualType, 8> Rs(Xs.size());
13662 for (size_t I = 0; I < Rs.size(); ++I)
13663 Rs[I] = Ctx.getCommonSugaredType(Xs[I], Ys[I], Unqualified);
13664 return Rs;
13665}
13666
13667template <class T>
13668static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
13669 return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
13670 : SourceLocation();
13671}
13672
13674 const TemplateArgument &X,
13675 const TemplateArgument &Y) {
13676 if (X.getKind() != Y.getKind())
13677 return TemplateArgument();
13678
13679 switch (X.getKind()) {
13681 if (!Ctx.hasSameType(X.getAsType(), Y.getAsType()))
13682 return TemplateArgument();
13683 return TemplateArgument(
13684 Ctx.getCommonSugaredType(X.getAsType(), Y.getAsType()));
13686 if (!Ctx.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
13687 return TemplateArgument();
13688 return TemplateArgument(
13689 Ctx.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
13690 /*Unqualified=*/true);
13692 if (!Ctx.hasSameType(X.getAsExpr()->getType(), Y.getAsExpr()->getType()))
13693 return TemplateArgument();
13694 // FIXME: Try to keep the common sugar.
13695 return X;
13697 TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
13698 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
13699 if (!CTN.getAsVoidPointer())
13700 return TemplateArgument();
13701 return TemplateArgument(CTN);
13702 }
13704 TemplateName TX = X.getAsTemplateOrTemplatePattern(),
13706 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
13707 if (!CTN.getAsVoidPointer())
13708 return TemplateName();
13709 auto NExpX = X.getNumTemplateExpansions();
13710 assert(NExpX == Y.getNumTemplateExpansions());
13711 return TemplateArgument(CTN, NExpX);
13712 }
13713 default:
13714 // FIXME: Handle the other argument kinds.
13715 return X;
13716 }
13717}
13718
13723 if (Xs.size() != Ys.size())
13724 return true;
13725 R.resize(Xs.size());
13726 for (size_t I = 0; I < R.size(); ++I) {
13727 R[I] = getCommonTemplateArgument(Ctx, Xs[I], Ys[I]);
13728 if (R[I].isNull())
13729 return true;
13730 }
13731 return false;
13732}
13733
13738 bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
13739 assert(!Different);
13740 (void)Different;
13741 return R;
13742}
13743
13744template <class T>
13746 bool IsSame) {
13747 ElaboratedTypeKeyword KX = X->getKeyword(), KY = Y->getKeyword();
13748 if (KX == KY)
13749 return KX;
13751 assert(!IsSame || KX == getCanonicalElaboratedTypeKeyword(KY));
13752 return KX;
13753}
13754
13755/// Returns a NestedNameSpecifier which has only the common sugar
13756/// present in both NNS1 and NNS2.
13759 NestedNameSpecifier NNS2, bool IsSame) {
13760 // If they are identical, all sugar is common.
13761 if (NNS1 == NNS2)
13762 return NNS1;
13763
13764 // IsSame implies both Qualifiers are equivalent.
13765 NestedNameSpecifier Canon = NNS1.getCanonical();
13766 if (Canon != NNS2.getCanonical()) {
13767 assert(!IsSame && "Should be the same NestedNameSpecifier");
13768 // If they are not the same, there is nothing to unify.
13769 return std::nullopt;
13770 }
13771
13772 NestedNameSpecifier R = std::nullopt;
13773 NestedNameSpecifier::Kind Kind = NNS1.getKind();
13774 assert(Kind == NNS2.getKind());
13775 switch (Kind) {
13777 auto [Namespace1, Prefix1] = NNS1.getAsNamespaceAndPrefix();
13778 auto [Namespace2, Prefix2] = NNS2.getAsNamespaceAndPrefix();
13779 auto Kind = Namespace1->getKind();
13780 if (Kind != Namespace2->getKind() ||
13781 (Kind == Decl::NamespaceAlias &&
13782 !declaresSameEntity(Namespace1, Namespace2))) {
13784 Ctx,
13785 ::getCommonDeclChecked(Namespace1->getNamespace(),
13786 Namespace2->getNamespace()),
13787 /*Prefix=*/std::nullopt);
13788 break;
13789 }
13790 // The prefixes for namespaces are not significant, its declaration
13791 // identifies it uniquely.
13792 NestedNameSpecifier Prefix = ::getCommonNNS(Ctx, Prefix1, Prefix2,
13793 /*IsSame=*/false);
13794 R = NestedNameSpecifier(Ctx, ::getCommonDeclChecked(Namespace1, Namespace2),
13795 Prefix);
13796 break;
13797 }
13799 const Type *T1 = NNS1.getAsType(), *T2 = NNS2.getAsType();
13800 const Type *T = Ctx.getCommonSugaredType(QualType(T1, 0), QualType(T2, 0),
13801 /*Unqualified=*/true)
13802 .getTypePtr();
13804 break;
13805 }
13807 // FIXME: Can __super even be used with data members?
13808 // If it's only usable in functions, we will never see it here,
13809 // unless we save the qualifiers used in function types.
13810 // In that case, it might be possible NNS2 is a type,
13811 // in which case we should degrade the result to
13812 // a CXXRecordType.
13814 NNS2.getAsMicrosoftSuper()));
13815 break;
13816 }
13819 // These are singletons.
13820 llvm_unreachable("singletons did not compare equal");
13821 }
13822 assert(R.getCanonical() == Canon);
13823 return R;
13824}
13825
13826template <class T>
13828 const T *Y, bool IsSame) {
13829 return ::getCommonNNS(Ctx, X->getQualifier(), Y->getQualifier(), IsSame);
13830}
13831
13832template <class T>
13833static QualType getCommonElementType(const ASTContext &Ctx, const T *X,
13834 const T *Y) {
13835 return Ctx.getCommonSugaredType(X->getElementType(), Y->getElementType());
13836}
13837
13838template <class T>
13840 Qualifiers &QX, const T *Y,
13841 Qualifiers &QY) {
13842 QualType EX = X->getElementType(), EY = Y->getElementType();
13843 QualType R = Ctx.getCommonSugaredType(EX, EY,
13844 /*Unqualified=*/true);
13845 // Qualifiers common to both element types.
13846 Qualifiers RQ = R.getQualifiers();
13847 // For each side, move to the top level any qualifiers which are not common to
13848 // both element types. The caller must assume top level qualifiers might
13849 // be different, even if they are the same type, and can be treated as sugar.
13850 QX += EX.getQualifiers() - RQ;
13851 QY += EY.getQualifiers() - RQ;
13852 return R;
13853}
13854
13855template <class T>
13856static QualType getCommonPointeeType(const ASTContext &Ctx, const T *X,
13857 const T *Y) {
13858 return Ctx.getCommonSugaredType(X->getPointeeType(), Y->getPointeeType());
13859}
13860
13861template <class T>
13862static auto *getCommonSizeExpr(const ASTContext &Ctx, T *X, T *Y) {
13863 assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
13864 return X->getSizeExpr();
13865}
13866
13867static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
13868 assert(X->getSizeModifier() == Y->getSizeModifier());
13869 return X->getSizeModifier();
13870}
13871
13873 const ArrayType *Y) {
13874 assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
13875 return X->getIndexTypeCVRQualifiers();
13876}
13877
13878// Merges two type lists such that the resulting vector will contain
13879// each type (in a canonical sense) only once, in the order they appear
13880// from X to Y. If they occur in both X and Y, the result will contain
13881// the common sugared type between them.
13882static void mergeTypeLists(const ASTContext &Ctx,
13885 llvm::DenseMap<QualType, unsigned> Found;
13886 for (auto Ts : {X, Y}) {
13887 for (QualType T : Ts) {
13888 auto Res = Found.try_emplace(Ctx.getCanonicalType(T), Out.size());
13889 if (!Res.second) {
13890 QualType &U = Out[Res.first->second];
13891 U = Ctx.getCommonSugaredType(U, T);
13892 } else {
13893 Out.emplace_back(T);
13894 }
13895 }
13896 }
13897}
13898
13899FunctionProtoType::ExceptionSpecInfo
13902 SmallVectorImpl<QualType> &ExceptionTypeStorage,
13903 bool AcceptDependent) const {
13904 ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
13905
13906 // If either of them can throw anything, that is the result.
13907 for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
13908 if (EST1 == I)
13909 return ESI1;
13910 if (EST2 == I)
13911 return ESI2;
13912 }
13913
13914 // If either of them is non-throwing, the result is the other.
13915 for (auto I :
13917 if (EST1 == I)
13918 return ESI2;
13919 if (EST2 == I)
13920 return ESI1;
13921 }
13922
13923 // If we're left with value-dependent computed noexcept expressions, we're
13924 // stuck. Before C++17, we can just drop the exception specification entirely,
13925 // since it's not actually part of the canonical type. And this should never
13926 // happen in C++17, because it would mean we were computing the composite
13927 // pointer type of dependent types, which should never happen.
13928 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
13929 assert(AcceptDependent &&
13930 "computing composite pointer type of dependent types");
13932 }
13933
13934 // Switch over the possibilities so that people adding new values know to
13935 // update this function.
13936 switch (EST1) {
13937 case EST_None:
13938 case EST_DynamicNone:
13939 case EST_MSAny:
13940 case EST_BasicNoexcept:
13942 case EST_NoexceptFalse:
13943 case EST_NoexceptTrue:
13944 case EST_NoThrow:
13945 llvm_unreachable("These ESTs should be handled above");
13946
13947 case EST_Dynamic: {
13948 // This is the fun case: both exception specifications are dynamic. Form
13949 // the union of the two lists.
13950 assert(EST2 == EST_Dynamic && "other cases should already be handled");
13951 mergeTypeLists(*this, ExceptionTypeStorage, ESI1.Exceptions,
13952 ESI2.Exceptions);
13954 Result.Exceptions = ExceptionTypeStorage;
13955 return Result;
13956 }
13957
13958 case EST_Unevaluated:
13959 case EST_Uninstantiated:
13960 case EST_Unparsed:
13961 llvm_unreachable("shouldn't see unresolved exception specifications here");
13962 }
13963
13964 llvm_unreachable("invalid ExceptionSpecificationType");
13965}
13966
13968 Qualifiers &QX, const Type *Y,
13969 Qualifiers &QY) {
13970 Type::TypeClass TC = X->getTypeClass();
13971 assert(TC == Y->getTypeClass());
13972 switch (TC) {
13973#define UNEXPECTED_TYPE(Class, Kind) \
13974 case Type::Class: \
13975 llvm_unreachable("Unexpected " Kind ": " #Class);
13976
13977#define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
13978#define TYPE(Class, Base)
13979#include "clang/AST/TypeNodes.inc"
13980
13981#define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
13983 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
13984 SUGAR_FREE_TYPE(DependentBitInt)
13986 SUGAR_FREE_TYPE(ObjCInterface)
13987 SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
13988 SUGAR_FREE_TYPE(SubstBuiltinTemplatePack)
13989 SUGAR_FREE_TYPE(UnresolvedUsing)
13990 SUGAR_FREE_TYPE(HLSLAttributedResource)
13991 SUGAR_FREE_TYPE(HLSLInlineSpirv)
13992#undef SUGAR_FREE_TYPE
13993#define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
13994 NON_UNIQUE_TYPE(TypeOfExpr)
13995 NON_UNIQUE_TYPE(VariableArray)
13996#undef NON_UNIQUE_TYPE
13997
13998 UNEXPECTED_TYPE(TypeOf, "sugar")
13999
14000#undef UNEXPECTED_TYPE
14001
14002 case Type::Auto: {
14003 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14004 assert(AX->getDeducedType().isNull());
14005 assert(AY->getDeducedType().isNull());
14006 assert(AX->getKeyword() == AY->getKeyword());
14007 assert(AX->isInstantiationDependentType() ==
14008 AY->isInstantiationDependentType());
14009 auto As = getCommonTemplateArguments(Ctx, AX->getTypeConstraintArguments(),
14010 AY->getTypeConstraintArguments());
14011 return Ctx.getAutoType(QualType(), AX->getKeyword(),
14013 AX->containsUnexpandedParameterPack(),
14014 getCommonDeclChecked(AX->getTypeConstraintConcept(),
14015 AY->getTypeConstraintConcept()),
14016 As);
14017 }
14018 case Type::IncompleteArray: {
14019 const auto *AX = cast<IncompleteArrayType>(X),
14021 return Ctx.getIncompleteArrayType(
14022 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14024 }
14025 case Type::DependentSizedArray: {
14026 const auto *AX = cast<DependentSizedArrayType>(X),
14028 return Ctx.getDependentSizedArrayType(
14029 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14030 getCommonSizeExpr(Ctx, AX, AY), getCommonSizeModifier(AX, AY),
14032 }
14033 case Type::ConstantArray: {
14034 const auto *AX = cast<ConstantArrayType>(X),
14035 *AY = cast<ConstantArrayType>(Y);
14036 assert(AX->getSize() == AY->getSize());
14037 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14038 ? AX->getSizeExpr()
14039 : nullptr;
14040 return Ctx.getConstantArrayType(
14041 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14043 }
14044 case Type::ArrayParameter: {
14045 const auto *AX = cast<ArrayParameterType>(X),
14046 *AY = cast<ArrayParameterType>(Y);
14047 assert(AX->getSize() == AY->getSize());
14048 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14049 ? AX->getSizeExpr()
14050 : nullptr;
14051 auto ArrayTy = Ctx.getConstantArrayType(
14052 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14054 return Ctx.getArrayParameterType(ArrayTy);
14055 }
14056 case Type::Atomic: {
14057 const auto *AX = cast<AtomicType>(X), *AY = cast<AtomicType>(Y);
14058 return Ctx.getAtomicType(
14059 Ctx.getCommonSugaredType(AX->getValueType(), AY->getValueType()));
14060 }
14061 case Type::Complex: {
14062 const auto *CX = cast<ComplexType>(X), *CY = cast<ComplexType>(Y);
14063 return Ctx.getComplexType(getCommonArrayElementType(Ctx, CX, QX, CY, QY));
14064 }
14065 case Type::Pointer: {
14066 const auto *PX = cast<PointerType>(X), *PY = cast<PointerType>(Y);
14067 return Ctx.getPointerType(getCommonPointeeType(Ctx, PX, PY));
14068 }
14069 case Type::BlockPointer: {
14070 const auto *PX = cast<BlockPointerType>(X), *PY = cast<BlockPointerType>(Y);
14071 return Ctx.getBlockPointerType(getCommonPointeeType(Ctx, PX, PY));
14072 }
14073 case Type::ObjCObjectPointer: {
14074 const auto *PX = cast<ObjCObjectPointerType>(X),
14076 return Ctx.getObjCObjectPointerType(getCommonPointeeType(Ctx, PX, PY));
14077 }
14078 case Type::MemberPointer: {
14079 const auto *PX = cast<MemberPointerType>(X),
14080 *PY = cast<MemberPointerType>(Y);
14081 assert(declaresSameEntity(PX->getMostRecentCXXRecordDecl(),
14082 PY->getMostRecentCXXRecordDecl()));
14083 return Ctx.getMemberPointerType(
14084 getCommonPointeeType(Ctx, PX, PY),
14085 getCommonQualifier(Ctx, PX, PY, /*IsSame=*/true),
14086 PX->getMostRecentCXXRecordDecl());
14087 }
14088 case Type::LValueReference: {
14089 const auto *PX = cast<LValueReferenceType>(X),
14091 // FIXME: Preserve PointeeTypeAsWritten.
14092 return Ctx.getLValueReferenceType(getCommonPointeeType(Ctx, PX, PY),
14093 PX->isSpelledAsLValue() ||
14094 PY->isSpelledAsLValue());
14095 }
14096 case Type::RValueReference: {
14097 const auto *PX = cast<RValueReferenceType>(X),
14099 // FIXME: Preserve PointeeTypeAsWritten.
14100 return Ctx.getRValueReferenceType(getCommonPointeeType(Ctx, PX, PY));
14101 }
14102 case Type::DependentAddressSpace: {
14103 const auto *PX = cast<DependentAddressSpaceType>(X),
14105 assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
14106 return Ctx.getDependentAddressSpaceType(getCommonPointeeType(Ctx, PX, PY),
14107 PX->getAddrSpaceExpr(),
14108 getCommonAttrLoc(PX, PY));
14109 }
14110 case Type::FunctionNoProto: {
14111 const auto *FX = cast<FunctionNoProtoType>(X),
14113 assert(FX->getExtInfo() == FY->getExtInfo());
14114 return Ctx.getFunctionNoProtoType(
14115 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType()),
14116 FX->getExtInfo());
14117 }
14118 case Type::FunctionProto: {
14119 const auto *FX = cast<FunctionProtoType>(X),
14120 *FY = cast<FunctionProtoType>(Y);
14121 FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
14122 EPIY = FY->getExtProtoInfo();
14123 assert(EPIX.ExtInfo == EPIY.ExtInfo);
14124 assert(!EPIX.ExtParameterInfos == !EPIY.ExtParameterInfos);
14125 assert(!EPIX.ExtParameterInfos ||
14126 llvm::equal(
14127 llvm::ArrayRef(EPIX.ExtParameterInfos, FX->getNumParams()),
14128 llvm::ArrayRef(EPIY.ExtParameterInfos, FY->getNumParams())));
14129 assert(EPIX.RefQualifier == EPIY.RefQualifier);
14130 assert(EPIX.TypeQuals == EPIY.TypeQuals);
14131 assert(EPIX.Variadic == EPIY.Variadic);
14132
14133 // FIXME: Can we handle an empty EllipsisLoc?
14134 // Use emtpy EllipsisLoc if X and Y differ.
14135
14136 EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
14137
14138 QualType R =
14139 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType());
14140 auto P = getCommonTypes(Ctx, FX->param_types(), FY->param_types(),
14141 /*Unqualified=*/true);
14142
14143 SmallVector<QualType, 8> Exceptions;
14145 EPIX.ExceptionSpec, EPIY.ExceptionSpec, Exceptions, true);
14146 return Ctx.getFunctionType(R, P, EPIX);
14147 }
14148 case Type::ObjCObject: {
14149 const auto *OX = cast<ObjCObjectType>(X), *OY = cast<ObjCObjectType>(Y);
14150 assert(
14151 std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
14152 OY->getProtocols().begin(), OY->getProtocols().end(),
14153 [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
14154 return P0->getCanonicalDecl() == P1->getCanonicalDecl();
14155 }) &&
14156 "protocol lists must be the same");
14157 auto TAs = getCommonTypes(Ctx, OX->getTypeArgsAsWritten(),
14158 OY->getTypeArgsAsWritten());
14159 return Ctx.getObjCObjectType(
14160 Ctx.getCommonSugaredType(OX->getBaseType(), OY->getBaseType()), TAs,
14161 OX->getProtocols(),
14162 OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
14163 }
14164 case Type::ConstantMatrix: {
14165 const auto *MX = cast<ConstantMatrixType>(X),
14166 *MY = cast<ConstantMatrixType>(Y);
14167 assert(MX->getNumRows() == MY->getNumRows());
14168 assert(MX->getNumColumns() == MY->getNumColumns());
14169 return Ctx.getConstantMatrixType(getCommonElementType(Ctx, MX, MY),
14170 MX->getNumRows(), MX->getNumColumns());
14171 }
14172 case Type::DependentSizedMatrix: {
14173 const auto *MX = cast<DependentSizedMatrixType>(X),
14175 assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
14176 assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
14177 return Ctx.getDependentSizedMatrixType(
14178 getCommonElementType(Ctx, MX, MY), MX->getRowExpr(),
14179 MX->getColumnExpr(), getCommonAttrLoc(MX, MY));
14180 }
14181 case Type::Vector: {
14182 const auto *VX = cast<VectorType>(X), *VY = cast<VectorType>(Y);
14183 assert(VX->getNumElements() == VY->getNumElements());
14184 assert(VX->getVectorKind() == VY->getVectorKind());
14185 return Ctx.getVectorType(getCommonElementType(Ctx, VX, VY),
14186 VX->getNumElements(), VX->getVectorKind());
14187 }
14188 case Type::ExtVector: {
14189 const auto *VX = cast<ExtVectorType>(X), *VY = cast<ExtVectorType>(Y);
14190 assert(VX->getNumElements() == VY->getNumElements());
14191 return Ctx.getExtVectorType(getCommonElementType(Ctx, VX, VY),
14192 VX->getNumElements());
14193 }
14194 case Type::DependentSizedExtVector: {
14195 const auto *VX = cast<DependentSizedExtVectorType>(X),
14198 getCommonSizeExpr(Ctx, VX, VY),
14199 getCommonAttrLoc(VX, VY));
14200 }
14201 case Type::DependentVector: {
14202 const auto *VX = cast<DependentVectorType>(X),
14204 assert(VX->getVectorKind() == VY->getVectorKind());
14205 return Ctx.getDependentVectorType(
14206 getCommonElementType(Ctx, VX, VY), getCommonSizeExpr(Ctx, VX, VY),
14207 getCommonAttrLoc(VX, VY), VX->getVectorKind());
14208 }
14209 case Type::Enum:
14210 case Type::Record:
14211 case Type::InjectedClassName: {
14212 const auto *TX = cast<TagType>(X), *TY = cast<TagType>(Y);
14213 return Ctx.getTagType(
14214 ::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14215 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false),
14216 ::getCommonDeclChecked(TX->getOriginalDecl(), TY->getOriginalDecl()),
14217 /*OwnedTag=*/false);
14218 }
14219 case Type::TemplateSpecialization: {
14220 const auto *TX = cast<TemplateSpecializationType>(X),
14222 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
14223 TY->template_arguments());
14225 getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14226 ::getCommonTemplateNameChecked(Ctx, TX->getTemplateName(),
14227 TY->getTemplateName(),
14228 /*IgnoreDeduced=*/true),
14229 As, /*CanonicalArgs=*/{}, X->getCanonicalTypeInternal());
14230 }
14231 case Type::Decltype: {
14232 const auto *DX = cast<DecltypeType>(X);
14233 [[maybe_unused]] const auto *DY = cast<DecltypeType>(Y);
14234 assert(DX->isDependentType());
14235 assert(DY->isDependentType());
14236 assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
14237 // As Decltype is not uniqued, building a common type would be wasteful.
14238 return QualType(DX, 0);
14239 }
14240 case Type::PackIndexing: {
14241 const auto *DX = cast<PackIndexingType>(X);
14242 [[maybe_unused]] const auto *DY = cast<PackIndexingType>(Y);
14243 assert(DX->isDependentType());
14244 assert(DY->isDependentType());
14245 assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr()));
14246 return QualType(DX, 0);
14247 }
14248 case Type::DependentName: {
14249 const auto *NX = cast<DependentNameType>(X),
14250 *NY = cast<DependentNameType>(Y);
14251 assert(NX->getIdentifier() == NY->getIdentifier());
14252 return Ctx.getDependentNameType(
14253 getCommonTypeKeyword(NX, NY, /*IsSame=*/true),
14254 getCommonQualifier(Ctx, NX, NY, /*IsSame=*/true), NX->getIdentifier());
14255 }
14256 case Type::UnaryTransform: {
14257 const auto *TX = cast<UnaryTransformType>(X),
14258 *TY = cast<UnaryTransformType>(Y);
14259 assert(TX->getUTTKind() == TY->getUTTKind());
14260 return Ctx.getUnaryTransformType(
14261 Ctx.getCommonSugaredType(TX->getBaseType(), TY->getBaseType()),
14262 Ctx.getCommonSugaredType(TX->getUnderlyingType(),
14263 TY->getUnderlyingType()),
14264 TX->getUTTKind());
14265 }
14266 case Type::PackExpansion: {
14267 const auto *PX = cast<PackExpansionType>(X),
14268 *PY = cast<PackExpansionType>(Y);
14269 assert(PX->getNumExpansions() == PY->getNumExpansions());
14270 return Ctx.getPackExpansionType(
14271 Ctx.getCommonSugaredType(PX->getPattern(), PY->getPattern()),
14272 PX->getNumExpansions(), false);
14273 }
14274 case Type::Pipe: {
14275 const auto *PX = cast<PipeType>(X), *PY = cast<PipeType>(Y);
14276 assert(PX->isReadOnly() == PY->isReadOnly());
14277 auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
14279 return (Ctx.*MP)(getCommonElementType(Ctx, PX, PY));
14280 }
14281 case Type::TemplateTypeParm: {
14282 const auto *TX = cast<TemplateTypeParmType>(X),
14284 assert(TX->getDepth() == TY->getDepth());
14285 assert(TX->getIndex() == TY->getIndex());
14286 assert(TX->isParameterPack() == TY->isParameterPack());
14287 return Ctx.getTemplateTypeParmType(
14288 TX->getDepth(), TX->getIndex(), TX->isParameterPack(),
14289 getCommonDecl(TX->getDecl(), TY->getDecl()));
14290 }
14291 }
14292 llvm_unreachable("Unknown Type Class");
14293}
14294
14296 const Type *Y,
14297 SplitQualType Underlying) {
14298 Type::TypeClass TC = X->getTypeClass();
14299 if (TC != Y->getTypeClass())
14300 return QualType();
14301 switch (TC) {
14302#define UNEXPECTED_TYPE(Class, Kind) \
14303 case Type::Class: \
14304 llvm_unreachable("Unexpected " Kind ": " #Class);
14305#define TYPE(Class, Base)
14306#define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
14307#include "clang/AST/TypeNodes.inc"
14308
14309#define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
14312 CANONICAL_TYPE(BlockPointer)
14315 CANONICAL_TYPE(ConstantArray)
14316 CANONICAL_TYPE(ArrayParameter)
14317 CANONICAL_TYPE(ConstantMatrix)
14319 CANONICAL_TYPE(ExtVector)
14320 CANONICAL_TYPE(FunctionNoProto)
14321 CANONICAL_TYPE(FunctionProto)
14322 CANONICAL_TYPE(IncompleteArray)
14323 CANONICAL_TYPE(HLSLAttributedResource)
14324 CANONICAL_TYPE(HLSLInlineSpirv)
14325 CANONICAL_TYPE(LValueReference)
14326 CANONICAL_TYPE(ObjCInterface)
14327 CANONICAL_TYPE(ObjCObject)
14328 CANONICAL_TYPE(ObjCObjectPointer)
14332 CANONICAL_TYPE(RValueReference)
14333 CANONICAL_TYPE(VariableArray)
14335#undef CANONICAL_TYPE
14336
14337#undef UNEXPECTED_TYPE
14338
14339 case Type::Adjusted: {
14340 const auto *AX = cast<AdjustedType>(X), *AY = cast<AdjustedType>(Y);
14341 QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
14342 if (!Ctx.hasSameType(OX, OY))
14343 return QualType();
14344 // FIXME: It's inefficient to have to unify the original types.
14345 return Ctx.getAdjustedType(Ctx.getCommonSugaredType(OX, OY),
14346 Ctx.getQualifiedType(Underlying));
14347 }
14348 case Type::Decayed: {
14349 const auto *DX = cast<DecayedType>(X), *DY = cast<DecayedType>(Y);
14350 QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
14351 if (!Ctx.hasSameType(OX, OY))
14352 return QualType();
14353 // FIXME: It's inefficient to have to unify the original types.
14354 return Ctx.getDecayedType(Ctx.getCommonSugaredType(OX, OY),
14355 Ctx.getQualifiedType(Underlying));
14356 }
14357 case Type::Attributed: {
14358 const auto *AX = cast<AttributedType>(X), *AY = cast<AttributedType>(Y);
14359 AttributedType::Kind Kind = AX->getAttrKind();
14360 if (Kind != AY->getAttrKind())
14361 return QualType();
14362 QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
14363 if (!Ctx.hasSameType(MX, MY))
14364 return QualType();
14365 // FIXME: It's inefficient to have to unify the modified types.
14366 return Ctx.getAttributedType(Kind, Ctx.getCommonSugaredType(MX, MY),
14367 Ctx.getQualifiedType(Underlying),
14368 AX->getAttr());
14369 }
14370 case Type::BTFTagAttributed: {
14371 const auto *BX = cast<BTFTagAttributedType>(X);
14372 const BTFTypeTagAttr *AX = BX->getAttr();
14373 // The attribute is not uniqued, so just compare the tag.
14374 if (AX->getBTFTypeTag() !=
14375 cast<BTFTagAttributedType>(Y)->getAttr()->getBTFTypeTag())
14376 return QualType();
14377 return Ctx.getBTFTagAttributedType(AX, Ctx.getQualifiedType(Underlying));
14378 }
14379 case Type::Auto: {
14380 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14381
14382 AutoTypeKeyword KW = AX->getKeyword();
14383 if (KW != AY->getKeyword())
14384 return QualType();
14385
14386 TemplateDecl *CD = ::getCommonDecl(AX->getTypeConstraintConcept(),
14387 AY->getTypeConstraintConcept());
14389 if (CD &&
14390 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
14391 AY->getTypeConstraintArguments())) {
14392 CD = nullptr; // The arguments differ, so make it unconstrained.
14393 As.clear();
14394 }
14395
14396 // Both auto types can't be dependent, otherwise they wouldn't have been
14397 // sugar. This implies they can't contain unexpanded packs either.
14398 return Ctx.getAutoType(Ctx.getQualifiedType(Underlying), AX->getKeyword(),
14399 /*IsDependent=*/false, /*IsPack=*/false, CD, As);
14400 }
14401 case Type::PackIndexing:
14402 case Type::Decltype:
14403 return QualType();
14404 case Type::DeducedTemplateSpecialization:
14405 // FIXME: Try to merge these.
14406 return QualType();
14407 case Type::MacroQualified: {
14408 const auto *MX = cast<MacroQualifiedType>(X),
14409 *MY = cast<MacroQualifiedType>(Y);
14410 const IdentifierInfo *IX = MX->getMacroIdentifier();
14411 if (IX != MY->getMacroIdentifier())
14412 return QualType();
14413 return Ctx.getMacroQualifiedType(Ctx.getQualifiedType(Underlying), IX);
14414 }
14415 case Type::SubstTemplateTypeParm: {
14416 const auto *SX = cast<SubstTemplateTypeParmType>(X),
14418 Decl *CD =
14419 ::getCommonDecl(SX->getAssociatedDecl(), SY->getAssociatedDecl());
14420 if (!CD)
14421 return QualType();
14422 unsigned Index = SX->getIndex();
14423 if (Index != SY->getIndex())
14424 return QualType();
14425 auto PackIndex = SX->getPackIndex();
14426 if (PackIndex != SY->getPackIndex())
14427 return QualType();
14428 return Ctx.getSubstTemplateTypeParmType(Ctx.getQualifiedType(Underlying),
14429 CD, Index, PackIndex,
14430 SX->getFinal() && SY->getFinal());
14431 }
14432 case Type::ObjCTypeParam:
14433 // FIXME: Try to merge these.
14434 return QualType();
14435 case Type::Paren:
14436 return Ctx.getParenType(Ctx.getQualifiedType(Underlying));
14437
14438 case Type::TemplateSpecialization: {
14439 const auto *TX = cast<TemplateSpecializationType>(X),
14441 TemplateName CTN =
14442 ::getCommonTemplateName(Ctx, TX->getTemplateName(),
14443 TY->getTemplateName(), /*IgnoreDeduced=*/true);
14444 if (!CTN.getAsVoidPointer())
14445 return QualType();
14447 if (getCommonTemplateArguments(Ctx, As, TX->template_arguments(),
14448 TY->template_arguments()))
14449 return QualType();
14451 getCommonTypeKeyword(TX, TY, /*IsSame=*/false), CTN, As,
14452 /*CanonicalArgs=*/{}, Ctx.getQualifiedType(Underlying));
14453 }
14454 case Type::Typedef: {
14455 const auto *TX = cast<TypedefType>(X), *TY = cast<TypedefType>(Y);
14456 const TypedefNameDecl *CD = ::getCommonDecl(TX->getDecl(), TY->getDecl());
14457 if (!CD)
14458 return QualType();
14459 return Ctx.getTypedefType(
14460 ::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14461 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false), CD,
14462 Ctx.getQualifiedType(Underlying));
14463 }
14464 case Type::TypeOf: {
14465 // The common sugar between two typeof expressions, where one is
14466 // potentially a typeof_unqual and the other is not, we unify to the
14467 // qualified type as that retains the most information along with the type.
14468 // We only return a typeof_unqual type when both types are unqual types.
14473 return Ctx.getTypeOfType(Ctx.getQualifiedType(Underlying), Kind);
14474 }
14475 case Type::TypeOfExpr:
14476 return QualType();
14477
14478 case Type::UnaryTransform: {
14479 const auto *UX = cast<UnaryTransformType>(X),
14480 *UY = cast<UnaryTransformType>(Y);
14481 UnaryTransformType::UTTKind KX = UX->getUTTKind();
14482 if (KX != UY->getUTTKind())
14483 return QualType();
14484 QualType BX = UX->getBaseType(), BY = UY->getBaseType();
14485 if (!Ctx.hasSameType(BX, BY))
14486 return QualType();
14487 // FIXME: It's inefficient to have to unify the base types.
14488 return Ctx.getUnaryTransformType(Ctx.getCommonSugaredType(BX, BY),
14489 Ctx.getQualifiedType(Underlying), KX);
14490 }
14491 case Type::Using: {
14492 const auto *UX = cast<UsingType>(X), *UY = cast<UsingType>(Y);
14493 const UsingShadowDecl *CD = ::getCommonDecl(UX->getDecl(), UY->getDecl());
14494 if (!CD)
14495 return QualType();
14496 return Ctx.getUsingType(::getCommonTypeKeyword(UX, UY, /*IsSame=*/false),
14497 ::getCommonQualifier(Ctx, UX, UY, /*IsSame=*/false),
14498 CD, Ctx.getQualifiedType(Underlying));
14499 }
14500 case Type::MemberPointer: {
14501 const auto *PX = cast<MemberPointerType>(X),
14502 *PY = cast<MemberPointerType>(Y);
14503 CXXRecordDecl *Cls = PX->getMostRecentCXXRecordDecl();
14504 assert(Cls == PY->getMostRecentCXXRecordDecl());
14505 return Ctx.getMemberPointerType(
14506 ::getCommonPointeeType(Ctx, PX, PY),
14507 ::getCommonQualifier(Ctx, PX, PY, /*IsSame=*/false), Cls);
14508 }
14509 case Type::CountAttributed: {
14510 const auto *DX = cast<CountAttributedType>(X),
14512 if (DX->isCountInBytes() != DY->isCountInBytes())
14513 return QualType();
14514 if (DX->isOrNull() != DY->isOrNull())
14515 return QualType();
14516 Expr *CEX = DX->getCountExpr();
14517 Expr *CEY = DY->getCountExpr();
14518 ArrayRef<clang::TypeCoupledDeclRefInfo> CDX = DX->getCoupledDecls();
14519 if (Ctx.hasSameExpr(CEX, CEY))
14520 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14521 DX->isCountInBytes(), DX->isOrNull(),
14522 CDX);
14523 if (!CEX->isIntegerConstantExpr(Ctx) || !CEY->isIntegerConstantExpr(Ctx))
14524 return QualType();
14525 // Two declarations with the same integer constant may still differ in their
14526 // expression pointers, so we need to evaluate them.
14527 llvm::APSInt VX = *CEX->getIntegerConstantExpr(Ctx);
14528 llvm::APSInt VY = *CEY->getIntegerConstantExpr(Ctx);
14529 if (VX != VY)
14530 return QualType();
14531 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14532 DX->isCountInBytes(), DX->isOrNull(),
14533 CDX);
14534 }
14535 case Type::PredefinedSugar:
14536 assert(cast<PredefinedSugarType>(X)->getKind() !=
14538 return QualType();
14539 }
14540 llvm_unreachable("Unhandled Type Class");
14541}
14542
14543static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
14545 while (true) {
14546 QTotal.addConsistentQualifiers(T.Quals);
14547 QualType NT = T.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
14548 if (NT == QualType(T.Ty, 0))
14549 break;
14550 R.push_back(T);
14551 T = NT.split();
14552 }
14553 return R;
14554}
14555
14557 bool Unqualified) const {
14558 assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
14559 if (X == Y)
14560 return X;
14561 if (!Unqualified) {
14562 if (X.isCanonical())
14563 return X;
14564 if (Y.isCanonical())
14565 return Y;
14566 }
14567
14568 SplitQualType SX = X.split(), SY = Y.split();
14569 Qualifiers QX, QY;
14570 // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
14571 // until we reach their underlying "canonical nodes". Note these are not
14572 // necessarily canonical types, as they may still have sugared properties.
14573 // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
14574 auto Xs = ::unwrapSugar(SX, QX), Ys = ::unwrapSugar(SY, QY);
14575
14576 // If this is an ArrayType, the element qualifiers are interchangeable with
14577 // the top level qualifiers.
14578 // * In case the canonical nodes are the same, the elements types are already
14579 // the same.
14580 // * Otherwise, the element types will be made the same, and any different
14581 // element qualifiers will be moved up to the top level qualifiers, per
14582 // 'getCommonArrayElementType'.
14583 // In both cases, this means there may be top level qualifiers which differ
14584 // between X and Y. If so, these differing qualifiers are redundant with the
14585 // element qualifiers, and can be removed without changing the canonical type.
14586 // The desired behaviour is the same as for the 'Unqualified' case here:
14587 // treat the redundant qualifiers as sugar, remove the ones which are not
14588 // common to both sides.
14589 bool KeepCommonQualifiers = Unqualified || isa<ArrayType>(SX.Ty);
14590
14591 if (SX.Ty != SY.Ty) {
14592 // The canonical nodes differ. Build a common canonical node out of the two,
14593 // unifying their sugar. This may recurse back here.
14594 SX.Ty =
14595 ::getCommonNonSugarTypeNode(*this, SX.Ty, QX, SY.Ty, QY).getTypePtr();
14596 } else {
14597 // The canonical nodes were identical: We may have desugared too much.
14598 // Add any common sugar back in.
14599 while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
14600 QX -= SX.Quals;
14601 QY -= SY.Quals;
14602 SX = Xs.pop_back_val();
14603 SY = Ys.pop_back_val();
14604 }
14605 }
14606 if (KeepCommonQualifiers)
14608 else
14609 assert(QX == QY);
14610
14611 // Even though the remaining sugar nodes in Xs and Ys differ, some may be
14612 // related. Walk up these nodes, unifying them and adding the result.
14613 while (!Xs.empty() && !Ys.empty()) {
14614 auto Underlying = SplitQualType(
14615 SX.Ty, Qualifiers::removeCommonQualifiers(SX.Quals, SY.Quals));
14616 SX = Xs.pop_back_val();
14617 SY = Ys.pop_back_val();
14618 SX.Ty = ::getCommonSugarTypeNode(*this, SX.Ty, SY.Ty, Underlying)
14620 // Stop at the first pair which is unrelated.
14621 if (!SX.Ty) {
14622 SX.Ty = Underlying.Ty;
14623 break;
14624 }
14625 QX -= Underlying.Quals;
14626 };
14627
14628 // Add back the missing accumulated qualifiers, which were stripped off
14629 // with the sugar nodes we could not unify.
14630 QualType R = getQualifiedType(SX.Ty, QX);
14631 assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
14632 return R;
14633}
14634
14636 assert(Ty->isFixedPointType());
14637
14639 return Ty;
14640
14641 switch (Ty->castAs<BuiltinType>()->getKind()) {
14642 default:
14643 llvm_unreachable("Not a saturated fixed point type!");
14644 case BuiltinType::SatShortAccum:
14645 return ShortAccumTy;
14646 case BuiltinType::SatAccum:
14647 return AccumTy;
14648 case BuiltinType::SatLongAccum:
14649 return LongAccumTy;
14650 case BuiltinType::SatUShortAccum:
14651 return UnsignedShortAccumTy;
14652 case BuiltinType::SatUAccum:
14653 return UnsignedAccumTy;
14654 case BuiltinType::SatULongAccum:
14655 return UnsignedLongAccumTy;
14656 case BuiltinType::SatShortFract:
14657 return ShortFractTy;
14658 case BuiltinType::SatFract:
14659 return FractTy;
14660 case BuiltinType::SatLongFract:
14661 return LongFractTy;
14662 case BuiltinType::SatUShortFract:
14663 return UnsignedShortFractTy;
14664 case BuiltinType::SatUFract:
14665 return UnsignedFractTy;
14666 case BuiltinType::SatULongFract:
14667 return UnsignedLongFractTy;
14668 }
14669}
14670
14672 assert(Ty->isFixedPointType());
14673
14674 if (Ty->isSaturatedFixedPointType()) return Ty;
14675
14676 switch (Ty->castAs<BuiltinType>()->getKind()) {
14677 default:
14678 llvm_unreachable("Not a fixed point type!");
14679 case BuiltinType::ShortAccum:
14680 return SatShortAccumTy;
14681 case BuiltinType::Accum:
14682 return SatAccumTy;
14683 case BuiltinType::LongAccum:
14684 return SatLongAccumTy;
14685 case BuiltinType::UShortAccum:
14687 case BuiltinType::UAccum:
14688 return SatUnsignedAccumTy;
14689 case BuiltinType::ULongAccum:
14691 case BuiltinType::ShortFract:
14692 return SatShortFractTy;
14693 case BuiltinType::Fract:
14694 return SatFractTy;
14695 case BuiltinType::LongFract:
14696 return SatLongFractTy;
14697 case BuiltinType::UShortFract:
14699 case BuiltinType::UFract:
14700 return SatUnsignedFractTy;
14701 case BuiltinType::ULongFract:
14703 }
14704}
14705
14707 if (LangOpts.OpenCL)
14709
14710 if (LangOpts.CUDA)
14712
14713 return getLangASFromTargetAS(AS);
14714}
14715
14716// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
14717// doesn't include ASTContext.h
14718template
14720 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
14722 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
14723 const clang::ASTContext &Ctx, Decl *Value);
14724
14726 assert(Ty->isFixedPointType());
14727
14728 const TargetInfo &Target = getTargetInfo();
14729 switch (Ty->castAs<BuiltinType>()->getKind()) {
14730 default:
14731 llvm_unreachable("Not a fixed point type!");
14732 case BuiltinType::ShortAccum:
14733 case BuiltinType::SatShortAccum:
14734 return Target.getShortAccumScale();
14735 case BuiltinType::Accum:
14736 case BuiltinType::SatAccum:
14737 return Target.getAccumScale();
14738 case BuiltinType::LongAccum:
14739 case BuiltinType::SatLongAccum:
14740 return Target.getLongAccumScale();
14741 case BuiltinType::UShortAccum:
14742 case BuiltinType::SatUShortAccum:
14743 return Target.getUnsignedShortAccumScale();
14744 case BuiltinType::UAccum:
14745 case BuiltinType::SatUAccum:
14746 return Target.getUnsignedAccumScale();
14747 case BuiltinType::ULongAccum:
14748 case BuiltinType::SatULongAccum:
14749 return Target.getUnsignedLongAccumScale();
14750 case BuiltinType::ShortFract:
14751 case BuiltinType::SatShortFract:
14752 return Target.getShortFractScale();
14753 case BuiltinType::Fract:
14754 case BuiltinType::SatFract:
14755 return Target.getFractScale();
14756 case BuiltinType::LongFract:
14757 case BuiltinType::SatLongFract:
14758 return Target.getLongFractScale();
14759 case BuiltinType::UShortFract:
14760 case BuiltinType::SatUShortFract:
14761 return Target.getUnsignedShortFractScale();
14762 case BuiltinType::UFract:
14763 case BuiltinType::SatUFract:
14764 return Target.getUnsignedFractScale();
14765 case BuiltinType::ULongFract:
14766 case BuiltinType::SatULongFract:
14767 return Target.getUnsignedLongFractScale();
14768 }
14769}
14770
14772 assert(Ty->isFixedPointType());
14773
14774 const TargetInfo &Target = getTargetInfo();
14775 switch (Ty->castAs<BuiltinType>()->getKind()) {
14776 default:
14777 llvm_unreachable("Not a fixed point type!");
14778 case BuiltinType::ShortAccum:
14779 case BuiltinType::SatShortAccum:
14780 return Target.getShortAccumIBits();
14781 case BuiltinType::Accum:
14782 case BuiltinType::SatAccum:
14783 return Target.getAccumIBits();
14784 case BuiltinType::LongAccum:
14785 case BuiltinType::SatLongAccum:
14786 return Target.getLongAccumIBits();
14787 case BuiltinType::UShortAccum:
14788 case BuiltinType::SatUShortAccum:
14789 return Target.getUnsignedShortAccumIBits();
14790 case BuiltinType::UAccum:
14791 case BuiltinType::SatUAccum:
14792 return Target.getUnsignedAccumIBits();
14793 case BuiltinType::ULongAccum:
14794 case BuiltinType::SatULongAccum:
14795 return Target.getUnsignedLongAccumIBits();
14796 case BuiltinType::ShortFract:
14797 case BuiltinType::SatShortFract:
14798 case BuiltinType::Fract:
14799 case BuiltinType::SatFract:
14800 case BuiltinType::LongFract:
14801 case BuiltinType::SatLongFract:
14802 case BuiltinType::UShortFract:
14803 case BuiltinType::SatUShortFract:
14804 case BuiltinType::UFract:
14805 case BuiltinType::SatUFract:
14806 case BuiltinType::ULongFract:
14807 case BuiltinType::SatULongFract:
14808 return 0;
14809 }
14810}
14811
14812llvm::FixedPointSemantics
14814 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
14815 "Can only get the fixed point semantics for a "
14816 "fixed point or integer type.");
14817 if (Ty->isIntegerType())
14818 return llvm::FixedPointSemantics::GetIntegerSemantics(
14819 getIntWidth(Ty), Ty->isSignedIntegerType());
14820
14821 bool isSigned = Ty->isSignedFixedPointType();
14822 return llvm::FixedPointSemantics(
14823 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
14825 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
14826}
14827
14828llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
14829 assert(Ty->isFixedPointType());
14830 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
14831}
14832
14833llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
14834 assert(Ty->isFixedPointType());
14835 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
14836}
14837
14839 assert(Ty->isUnsignedFixedPointType() &&
14840 "Expected unsigned fixed point type");
14841
14842 switch (Ty->castAs<BuiltinType>()->getKind()) {
14843 case BuiltinType::UShortAccum:
14844 return ShortAccumTy;
14845 case BuiltinType::UAccum:
14846 return AccumTy;
14847 case BuiltinType::ULongAccum:
14848 return LongAccumTy;
14849 case BuiltinType::SatUShortAccum:
14850 return SatShortAccumTy;
14851 case BuiltinType::SatUAccum:
14852 return SatAccumTy;
14853 case BuiltinType::SatULongAccum:
14854 return SatLongAccumTy;
14855 case BuiltinType::UShortFract:
14856 return ShortFractTy;
14857 case BuiltinType::UFract:
14858 return FractTy;
14859 case BuiltinType::ULongFract:
14860 return LongFractTy;
14861 case BuiltinType::SatUShortFract:
14862 return SatShortFractTy;
14863 case BuiltinType::SatUFract:
14864 return SatFractTy;
14865 case BuiltinType::SatULongFract:
14866 return SatLongFractTy;
14867 default:
14868 llvm_unreachable("Unexpected unsigned fixed point type");
14869 }
14870}
14871
14872// Given a list of FMV features, return a concatenated list of the
14873// corresponding backend features (which may contain duplicates).
14874static std::vector<std::string> getFMVBackendFeaturesFor(
14875 const llvm::SmallVectorImpl<StringRef> &FMVFeatStrings) {
14876 std::vector<std::string> BackendFeats;
14877 llvm::AArch64::ExtensionSet FeatureBits;
14878 for (StringRef F : FMVFeatStrings)
14879 if (auto FMVExt = llvm::AArch64::parseFMVExtension(F))
14880 if (FMVExt->ID)
14881 FeatureBits.enable(*FMVExt->ID);
14882 FeatureBits.toLLVMFeatureList(BackendFeats);
14883 return BackendFeats;
14884}
14885
14886ParsedTargetAttr
14887ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
14888 assert(TD != nullptr);
14889 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TD->getFeaturesStr());
14890
14891 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) {
14892 return !Target->isValidFeatureName(StringRef{Feat}.substr(1));
14893 });
14894 return ParsedAttr;
14895}
14896
14897void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
14898 const FunctionDecl *FD) const {
14899 if (FD)
14900 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
14901 else
14902 Target->initFeatureMap(FeatureMap, getDiagnostics(),
14903 Target->getTargetOpts().CPU,
14904 Target->getTargetOpts().Features);
14905}
14906
14907// Fills in the supplied string map with the set of target features for the
14908// passed in function.
14909void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
14910 GlobalDecl GD) const {
14911 StringRef TargetCPU = Target->getTargetOpts().CPU;
14912 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
14913 if (const auto *TD = FD->getAttr<TargetAttr>()) {
14915
14916 // Make a copy of the features as passed on the command line into the
14917 // beginning of the additional features from the function to override.
14918 // AArch64 handles command line option features in parseTargetAttr().
14919 if (!Target->getTriple().isAArch64())
14920 ParsedAttr.Features.insert(
14921 ParsedAttr.Features.begin(),
14922 Target->getTargetOpts().FeaturesAsWritten.begin(),
14923 Target->getTargetOpts().FeaturesAsWritten.end());
14924
14925 if (ParsedAttr.CPU != "" && Target->isValidCPUName(ParsedAttr.CPU))
14926 TargetCPU = ParsedAttr.CPU;
14927
14928 // Now populate the feature map, first with the TargetCPU which is either
14929 // the default or a new one from the target attribute string. Then we'll use
14930 // the passed in features (FeaturesAsWritten) along with the new ones from
14931 // the attribute.
14932 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
14933 ParsedAttr.Features);
14934 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
14936 Target->getCPUSpecificCPUDispatchFeatures(
14937 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
14938 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
14939 Features.insert(Features.begin(),
14940 Target->getTargetOpts().FeaturesAsWritten.begin(),
14941 Target->getTargetOpts().FeaturesAsWritten.end());
14942 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14943 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
14944 if (Target->getTriple().isAArch64()) {
14946 TC->getFeatures(Feats, GD.getMultiVersionIndex());
14947 std::vector<std::string> Features = getFMVBackendFeaturesFor(Feats);
14948 Features.insert(Features.begin(),
14949 Target->getTargetOpts().FeaturesAsWritten.begin(),
14950 Target->getTargetOpts().FeaturesAsWritten.end());
14951 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14952 } else if (Target->getTriple().isRISCV()) {
14953 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
14954 std::vector<std::string> Features;
14955 if (VersionStr != "default") {
14956 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(VersionStr);
14957 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
14958 ParsedAttr.Features.end());
14959 }
14960 Features.insert(Features.begin(),
14961 Target->getTargetOpts().FeaturesAsWritten.begin(),
14962 Target->getTargetOpts().FeaturesAsWritten.end());
14963 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14964 } else {
14965 std::vector<std::string> Features;
14966 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
14967 if (VersionStr.starts_with("arch="))
14968 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
14969 else if (VersionStr != "default")
14970 Features.push_back((StringRef{"+"} + VersionStr).str());
14971 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14972 }
14973 } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
14974 std::vector<std::string> Features;
14975 if (Target->getTriple().isRISCV()) {
14976 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TV->getName());
14977 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
14978 ParsedAttr.Features.end());
14979 } else {
14980 assert(Target->getTriple().isAArch64());
14982 TV->getFeatures(Feats);
14983 Features = getFMVBackendFeaturesFor(Feats);
14984 }
14985 Features.insert(Features.begin(),
14986 Target->getTargetOpts().FeaturesAsWritten.begin(),
14987 Target->getTargetOpts().FeaturesAsWritten.end());
14988 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14989 } else {
14990 FeatureMap = Target->getTargetOpts().FeatureMap;
14991 }
14992}
14993
14995 CanQualType KernelNameType,
14996 const FunctionDecl *FD) {
14997 // Host and device compilation may use different ABIs and different ABIs
14998 // may allocate name mangling discriminators differently. A discriminator
14999 // override is used to ensure consistent discriminator allocation across
15000 // host and device compilation.
15001 auto DeviceDiscriminatorOverrider =
15002 [](ASTContext &Ctx, const NamedDecl *ND) -> UnsignedOrNone {
15003 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
15004 if (RD->isLambda())
15005 return RD->getDeviceLambdaManglingNumber();
15006 return std::nullopt;
15007 };
15008 std::unique_ptr<MangleContext> MC{ItaniumMangleContext::create(
15009 Context, Context.getDiagnostics(), DeviceDiscriminatorOverrider)};
15010
15011 // Construct a mangled name for the SYCL kernel caller offload entry point.
15012 // FIXME: The Itanium typeinfo mangling (_ZTS<type>) is currently used to
15013 // name the SYCL kernel caller offload entry point function. This mangling
15014 // does not suffice to clearly identify symbols that correspond to SYCL
15015 // kernel caller functions, nor is this mangling natural for targets that
15016 // use a non-Itanium ABI.
15017 std::string Buffer;
15018 Buffer.reserve(128);
15019 llvm::raw_string_ostream Out(Buffer);
15020 MC->mangleCanonicalTypeName(KernelNameType, Out);
15021 std::string KernelName = Out.str();
15022
15023 return {KernelNameType, FD, KernelName};
15024}
15025
15027 // If the function declaration to register is invalid or dependent, the
15028 // registration attempt is ignored.
15029 if (FD->isInvalidDecl() || FD->isTemplated())
15030 return;
15031
15032 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
15033 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
15034
15035 // Be tolerant of multiple registration attempts so long as each attempt
15036 // is for the same entity. Callers are obligated to detect and diagnose
15037 // conflicting kernel names prior to calling this function.
15038 CanQualType KernelNameType = getCanonicalType(SKEPAttr->getKernelName());
15039 auto IT = SYCLKernels.find(KernelNameType);
15040 assert((IT == SYCLKernels.end() ||
15041 declaresSameEntity(FD, IT->second.getKernelEntryPointDecl())) &&
15042 "SYCL kernel name conflict");
15043 (void)IT;
15044 SYCLKernels.insert(std::make_pair(
15045 KernelNameType, BuildSYCLKernelInfo(*this, KernelNameType, FD)));
15046}
15047
15049 CanQualType KernelNameType = getCanonicalType(T);
15050 return SYCLKernels.at(KernelNameType);
15051}
15052
15054 CanQualType KernelNameType = getCanonicalType(T);
15055 auto IT = SYCLKernels.find(KernelNameType);
15056 if (IT != SYCLKernels.end())
15057 return &IT->second;
15058 return nullptr;
15059}
15060
15062 OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
15063 return *OMPTraitInfoVector.back();
15064}
15065
15068 const ASTContext::SectionInfo &Section) {
15069 if (Section.Decl)
15070 return DB << Section.Decl;
15071 return DB << "a prior #pragma section";
15072}
15073
15074bool ASTContext::mayExternalize(const Decl *D) const {
15075 bool IsInternalVar =
15076 isa<VarDecl>(D) &&
15078 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
15079 !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
15080 (D->hasAttr<CUDAConstantAttr>() &&
15081 !D->getAttr<CUDAConstantAttr>()->isImplicit());
15082 // CUDA/HIP: managed variables need to be externalized since it is
15083 // a declaration in IR, therefore cannot have internal linkage. Kernels in
15084 // anonymous name space needs to be externalized to avoid duplicate symbols.
15085 return (IsInternalVar &&
15086 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
15087 (D->hasAttr<CUDAGlobalAttr>() &&
15089 GVA_Internal);
15090}
15091
15093 return mayExternalize(D) &&
15094 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
15096}
15097
15098StringRef ASTContext::getCUIDHash() const {
15099 if (!CUIDHash.empty())
15100 return CUIDHash;
15101 if (LangOpts.CUID.empty())
15102 return StringRef();
15103 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
15104 return CUIDHash;
15105}
15106
15107const CXXRecordDecl *
15109 assert(ThisClass);
15110 assert(ThisClass->isPolymorphic());
15111 const CXXRecordDecl *PrimaryBase = ThisClass;
15112 while (1) {
15113 assert(PrimaryBase);
15114 assert(PrimaryBase->isPolymorphic());
15115 auto &Layout = getASTRecordLayout(PrimaryBase);
15116 auto Base = Layout.getPrimaryBase();
15117 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
15118 break;
15119 PrimaryBase = Base;
15120 }
15121 return PrimaryBase;
15122}
15123
15125 StringRef MangledName) {
15126 auto *Method = cast<CXXMethodDecl>(VirtualMethodDecl.getDecl());
15127 assert(Method->isVirtual());
15128 bool DefaultIncludesPointerAuth =
15129 LangOpts.PointerAuthCalls || LangOpts.PointerAuthIntrinsics;
15130
15131 if (!DefaultIncludesPointerAuth)
15132 return true;
15133
15134 auto Existing = ThunksToBeAbbreviated.find(VirtualMethodDecl);
15135 if (Existing != ThunksToBeAbbreviated.end())
15136 return Existing->second.contains(MangledName.str());
15137
15138 std::unique_ptr<MangleContext> Mangler(createMangleContext());
15139 llvm::StringMap<llvm::SmallVector<std::string, 2>> Thunks;
15140 auto VtableContext = getVTableContext();
15141 if (const auto *ThunkInfos = VtableContext->getThunkInfo(VirtualMethodDecl)) {
15142 auto *Destructor = dyn_cast<CXXDestructorDecl>(Method);
15143 for (const auto &Thunk : *ThunkInfos) {
15144 SmallString<256> ElidedName;
15145 llvm::raw_svector_ostream ElidedNameStream(ElidedName);
15146 if (Destructor)
15147 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15148 Thunk, /* elideOverrideInfo */ true,
15149 ElidedNameStream);
15150 else
15151 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ true,
15152 ElidedNameStream);
15153 SmallString<256> MangledName;
15154 llvm::raw_svector_ostream mangledNameStream(MangledName);
15155 if (Destructor)
15156 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15157 Thunk, /* elideOverrideInfo */ false,
15158 mangledNameStream);
15159 else
15160 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ false,
15161 mangledNameStream);
15162
15163 Thunks[ElidedName].push_back(std::string(MangledName));
15164 }
15165 }
15166 llvm::StringSet<> SimplifiedThunkNames;
15167 for (auto &ThunkList : Thunks) {
15168 llvm::sort(ThunkList.second);
15169 SimplifiedThunkNames.insert(ThunkList.second[0]);
15170 }
15171 bool Result = SimplifiedThunkNames.contains(MangledName);
15172 ThunksToBeAbbreviated[VirtualMethodDecl] = std::move(SimplifiedThunkNames);
15173 return Result;
15174}
This file provides AST data structures related to concepts.
static void SortAndUniqueProtocols(SmallVectorImpl< ObjCProtocolDecl * > &Protocols)
static bool isCanonicalExceptionSpecification(const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType)
static SourceLocation getCommonAttrLoc(const T *X, const T *Y)
static auto getCanonicalTemplateArguments(const ASTContext &C, ArrayRef< TemplateArgument > Args, bool &AnyNonCanonArgs)
static char getObjCEncodingForPrimitiveType(const ASTContext *C, const BuiltinType *BT)
static bool isSameQualifier(const NestedNameSpecifier X, const NestedNameSpecifier Y)
static bool unionHasUniqueObjectRepresentations(const ASTContext &Context, const RecordDecl *RD, bool CheckIfTriviallyCopyable)
static TypedefDecl * CreateHexagonBuiltinVaListDecl(const ASTContext *Context)
#define CANONICAL_TYPE(Class)
static ElaboratedTypeKeyword getCommonTypeKeyword(const T *X, const T *Y, bool IsSame)
static Decl * getCommonDecl(Decl *X, Decl *Y)
static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context, const Decl *D, GVALinkage L)
static bool isTypeTypedefedAsBOOL(QualType T)
static void EncodeBitField(const ASTContext *Ctx, std::string &S, QualType T, const FieldDecl *FD)
static GVALinkage basicGVALinkageForVariable(const ASTContext &Context, const VarDecl *VD)
static const TemplateArgument * getDefaultTemplateArgumentOrNone(const NamedDecl *P)
static QualType getCommonArrayElementType(const ASTContext &Ctx, const T *X, Qualifiers &QX, const T *Y, Qualifiers &QY)
#define SUGAR_FREE_TYPE(Class)
static SYCLKernelInfo BuildSYCLKernelInfo(ASTContext &Context, CanQualType KernelNameType, const FunctionDecl *FD)
static bool hasTemplateSpecializationInEncodedString(const Type *T, bool VisitBasesAndFields)
static void getIntersectionOfProtocols(ASTContext &Context, const ObjCInterfaceDecl *CommonBase, const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT, SmallVectorImpl< ObjCProtocolDecl * > &IntersectionSet)
getIntersectionOfProtocols - This routine finds the intersection of set of protocols inherited from t...
static bool areCompatMatrixTypes(const ConstantMatrixType *LHS, const ConstantMatrixType *RHS)
areCompatMatrixTypes - Return true if the two specified matrix types are compatible.
static TypedefDecl * CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context)
static bool sameObjCTypeArgs(ASTContext &ctx, const ObjCInterfaceDecl *iface, ArrayRef< QualType > lhsArgs, ArrayRef< QualType > rhsArgs, bool stripKindOf)
static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs, QualType rhs)
Determine whether the first type is a subtype of the second.
static const Type * getIntegerTypeForEnum(const EnumType *ET)
static bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B)
static const Decl & adjustDeclToTemplate(const Decl &D)
If we have a 'templated' declaration for a template, adjust 'D' to refer to the actual template.
static TemplateName getCommonTemplateName(const ASTContext &Ctx, TemplateName X, TemplateName Y, bool IgnoreDeduced=false)
static int CmpProtocolNames(ObjCProtocolDecl *const *LHS, ObjCProtocolDecl *const *RHS)
CmpProtocolNames - Comparison predicate for sorting protocols alphabetically.
static auto * getCommonSizeExpr(const ASTContext &Ctx, T *X, T *Y)
static TypedefDecl * CreatePowerABIBuiltinVaListDecl(const ASTContext *Context)
static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y)
static TemplateArgument getCommonTemplateArgument(const ASTContext &Ctx, const TemplateArgument &X, const TemplateArgument &Y)
static std::optional< int64_t > structHasUniqueObjectRepresentations(const ASTContext &Context, const RecordDecl *RD, bool CheckIfTriviallyCopyable)
static bool hasSameOverloadableAttrs(const FunctionDecl *A, const FunctionDecl *B)
Determine whether the attributes we can overload on are identical for A and B.
static T * getCommonDeclChecked(T *X, T *Y)
static NestedNameSpecifier getCommonNNS(const ASTContext &Ctx, NestedNameSpecifier NNS1, NestedNameSpecifier NNS2, bool IsSame)
Returns a NestedNameSpecifier which has only the common sugar present in both NNS1 and NNS2.
static TypedefDecl * CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context)
static int64_t getSubobjectOffset(const FieldDecl *Field, const ASTContext &Context, const clang::ASTRecordLayout &)
static QualType getCommonSugarTypeNode(const ASTContext &Ctx, const Type *X, const Type *Y, SplitQualType Underlying)
static TypedefDecl * CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context)
static QualType getCommonNonSugarTypeNode(const ASTContext &Ctx, const Type *X, Qualifiers &QX, const Type *Y, Qualifiers &QY)
static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET, QualType other, bool isBlockReturnType)
Given that we have an enum type and a non-enum type, try to merge them.
static GVALinkage adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D, GVALinkage L)
Adjust the GVALinkage for a declaration based on what an external AST source knows about whether ther...
static TypedefDecl * CreateSystemZBuiltinVaListDecl(const ASTContext *Context)
static std::optional< int64_t > getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context, bool CheckIfTriviallyCopyable)
static GVALinkage basicGVALinkageForFunction(const ASTContext &Context, const FunctionDecl *FD)
#define NON_UNIQUE_TYPE(Class)
static TypedefDecl * CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context)
static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI, const LangOptions &LangOpts)
static ElaboratedTypeKeyword getCanonicalElaboratedTypeKeyword(ElaboratedTypeKeyword Keyword)
static QualType getCommonPointeeType(const ASTContext &Ctx, const T *X, const T *Y)
static auto getCommonIndexTypeCVRQualifiers(const ArrayType *X, const ArrayType *Y)
static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, ASTContext::GetBuiltinTypeError &Error, bool &RequiresICE, bool AllowTypeModifiers)
DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the pointer over the consume...
FloatingRank
@ FloatRank
@ LongDoubleRank
@ Float16Rank
@ Ibm128Rank
@ Float128Rank
@ BFloat16Rank
@ HalfRank
@ DoubleRank
static TypedefDecl * CreateCharPtrBuiltinVaListDecl(const ASTContext *Context)
static bool areSortedAndUniqued(ArrayRef< ObjCProtocolDecl * > Protocols)
static TypeInfoChars getConstantArrayInfoInChars(const ASTContext &Context, const ConstantArrayType *CAT)
getConstantArrayInfoInChars - Performing the computation in CharUnits instead of in bits prevents ove...
static FloatingRank getFloatingRank(QualType T)
getFloatingRank - Return a relative rank for floating point types.
static bool getCommonTemplateArguments(const ASTContext &Ctx, SmallVectorImpl< TemplateArgument > &R, ArrayRef< TemplateArgument > Xs, ArrayRef< TemplateArgument > Ys)
static TypedefDecl * CreateXtensaABIBuiltinVaListDecl(const ASTContext *Context)
static QualType getCommonElementType(const ASTContext &Ctx, const T *X, const T *Y)
static void mergeTypeLists(const ASTContext &Ctx, SmallVectorImpl< QualType > &Out, ArrayRef< QualType > X, ArrayRef< QualType > Y)
static void encodeTypeForFunctionPointerAuth(const ASTContext &Ctx, raw_ostream &OS, QualType QT)
Encode a function type for use in the discriminator of a function pointer type.
static std::optional< int64_t > structSubobjectsHaveUniqueObjectRepresentations(const RangeT &Subobjects, int64_t CurOffsetInBits, const ASTContext &Context, const clang::ASTRecordLayout &Layout, bool CheckIfTriviallyCopyable)
static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty)
getRVVTypeSize - Return RVV vector register size.
static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal)
static TemplateName getCommonTemplateNameChecked(const ASTContext &Ctx, TemplateName X, TemplateName Y, bool IgnoreDeduced)
static int compareObjCProtocolsByName(ObjCProtocolDecl *const *lhs, ObjCProtocolDecl *const *rhs)
Comparison routine for Objective-C protocols to be used with llvm::array_pod_sort.
static std::string charUnitsToString(const CharUnits &CU)
static const TagDecl * getNonInjectedClassName(const TagDecl *TD)
static bool hasAnyPackExpansions(ArrayRef< TemplateArgument > Args)
static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED)
static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod, SmallVectorImpl< const NamedDecl * > &Redeclared)
static SmallVector< SourceLocation, 2 > getDeclLocsForCommentSearch(const Decl *D, SourceManager &SourceMgr)
static auto getCommonTypes(const ASTContext &Ctx, ArrayRef< QualType > Xs, ArrayRef< QualType > Ys, bool Unqualified=false)
static bool isCanonicalResultType(QualType T)
Determine whether T is canonical as the result type of a function.
static TypedefDecl * CreateMSVaListDecl(const ASTContext *Context)
static bool areCompatVectorTypes(const VectorType *LHS, const VectorType *RHS)
areCompatVectorTypes - Return true if the two specified vector types are compatible.
static TypedefDecl * CreateCharPtrNamedVaListDecl(const ASTContext *Context, StringRef Name)
static NestedNameSpecifier getCommonQualifier(const ASTContext &Ctx, const T *X, const T *Y, bool IsSame)
#define UNEXPECTED_TYPE(Class, Kind)
static TypedefDecl * CreateVaListDecl(const ASTContext *Context, TargetInfo::BuiltinVaListKind Kind)
static bool primaryBaseHaseAddressDiscriminatedVTableAuthentication(const ASTContext &Context, const CXXRecordDecl *Class)
static std::vector< std::string > getFMVBackendFeaturesFor(const llvm::SmallVectorImpl< StringRef > &FMVFeatStrings)
Defines the clang::ASTContext interface.
#define V(N, I)
#define BuiltinTemplate(BTName)
Definition ASTContext.h:451
Provides definitions for the various language-specific address spaces.
static bool isUnsigned(SValBuilder &SVB, NonLoc Value)
Defines enum values for all the target-independent builtin functions.
static bool CanThrow(Expr *E, ASTContext &Ctx)
Definition CFG.cpp:2777
Defines the clang::CommentOptions interface.
static Decl::Kind getKind(const Decl *D)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
This file defines OpenMP nodes for declarative directives.
Defines the C++ template declaration subclasses.
Defines the ExceptionSpecificationType enumeration and various utility functions.
Defines the clang::Expr interface and subclasses for C++ expressions.
FormatToken * Next
The next token in the unwrapped line.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
static const Decl * getCanonicalDecl(const Decl *D)
#define X(type, name)
Definition Value.h:97
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
llvm::MachO::Record Record
Definition MachO.h:31
static bool hasFeature(StringRef Feature, const LangOptions &LangOpts, const TargetInfo &Target)
Determine whether a translation unit built using the current language options has the given feature.
Definition Module.cpp:95
Defines the clang::Module class, which describes a module in the source code.
Defines types useful for describing an Objective-C runtime.
#define SM(sm)
static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y)
static QualType getUnderlyingType(const SubRegion *R)
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
static QualType getPointeeType(const MemRegion *R)
Defines the TargetCXXABI class, which abstracts details of the C++ ABI that we're targeting.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
__device__ __2f16 float c
QualType getReadPipeType(QualType T) const
Return a read_only pipe type for the specified type.
QualType getWritePipeType(QualType T) const
Return a write_only pipe type for the specified type.
@ GE_Missing_stdio
Missing a type from <stdio.h>
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
RawComment * getRawCommentForDeclNoCacheImpl(const Decl *D, const SourceLocation RepresentativeLocForDecl, const std::map< unsigned, RawComment * > &CommentsInFile) const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
bool isMemberPointerToDerivedMember() const
Definition APValue.cpp:1073
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1066
ArrayRef< const CXXRecordDecl * > getMemberPointerPath() const
Definition APValue.cpp:1080
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
bool getByrefLifetime(QualType Ty, Qualifiers::ObjCLifetime &Lifetime, bool &HasByrefExtendedLayout) const
Returns true, if given type has a known lifetime.
MSGuidDecl * getMSGuidDecl(MSGuidDeclParts Parts) const
Return a declaration for the global GUID object representing the given GUID value.
CanQualType AccumTy
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, const ObjCMethodDecl *MethodImp)
CanQualType ObjCBuiltinSelTy
TranslationUnitDecl * getTranslationUnitDecl() const
const ConstantArrayType * getAsConstantArrayType(QualType T) const
CanQualType getCanonicalFunctionResultType(QualType ResultType) const
Adjust the given function result type.
QualType getAtomicType(QualType T) const
Return the uniqued reference to the atomic type for the specified type.
LangAS getOpenCLTypeAddrSpace(const Type *T) const
Get address space for OpenCL type.
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
void InitBuiltinTypes(const TargetInfo &Target, const TargetInfo *AuxTarget=nullptr)
Initialize built-in types.
ParentMapContext & getParentMapContext()
Returns the dynamic AST node parent map context.
QualType getParenType(QualType NamedType) const
size_t getSideTableAllocatedMemory() const
Return the total memory used for various side tables.
MemberSpecializationInfo * getInstantiatedFromStaticDataMember(const VarDecl *Var)
If this variable is an instantiated static data member of a class template specialization,...
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
CanQualType ARCUnbridgedCastTy
QualType getDependentSizedMatrixType(QualType ElementType, Expr *RowExpr, Expr *ColumnExpr, SourceLocation AttrLoc) const
Return the unique reference to the matrix type of the specified element type and size.
QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr, QualType Wrapped) const
llvm::DenseMap< const Decl *, comments::FullComment * > ParsedComments
Mapping from declarations to parsed comments attached to any redeclaration.
Definition ASTContext.h:988
unsigned getManglingNumber(const NamedDecl *ND, bool ForAuxTarget=false) const
CanQualType LongTy
unsigned getIntWidth(QualType T) const
CanQualType getCanonicalParamType(QualType T) const
Return the canonical parameter type corresponding to the specific potentially non-canonical one.
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
TemplateOrSpecializationInfo getTemplateOrSpecializationInfo(const VarDecl *Var)
CanQualType WIntTy
@ Weak
Weak definition of inline variable.
@ WeakUnknown
Weak for now, might become strong later in this TU.
void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl)
TypedefDecl * getObjCClassDecl() const
Retrieve the typedef declaration corresponding to the predefined Objective-C 'Class' type.
TypedefNameDecl * getTypedefNameForUnnamedTagDecl(const TagDecl *TD)
TypedefDecl * getCFConstantStringDecl() const
CanQualType Int128Ty
CanQualType SatUnsignedFractTy
void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern)
Remember that the using decl Inst is an instantiation of the using decl Pattern of a class template.
bool areCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an RISC-V vector builtin type and a VectorType that is a fixed-len...
ExternCContextDecl * getExternCContextDecl() const
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
ParsedTargetAttr filterFunctionTargetAttrs(const TargetAttr *TD) const
Parses the target attributes passed in, and returns only the ones that are valid feature names.
QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
TypedefDecl * getObjCSelDecl() const
Retrieve the typedef corresponding to the predefined 'SEL' type in Objective-C.
CanQualType UnsignedShortAccumTy
TypedefDecl * getObjCInstanceTypeDecl()
Retrieve the typedef declaration corresponding to the Objective-C "instancetype" type.
QualType adjustFunctionResultType(QualType FunctionType, QualType NewResultType)
Change the result type of a function type, preserving sugar such as attributed types.
void setTemplateOrSpecializationInfo(VarDecl *Inst, TemplateOrSpecializationInfo TSI)
bool isTypeAwareOperatorNewOrDelete(const FunctionDecl *FD) const
bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, ObjCProtocolDecl *rProto) const
ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the inheritance hierarchy of 'rProto...
TypedefDecl * buildImplicitTypedef(QualType T, StringRef Name) const
Create a new implicit TU-level typedef declaration.
QualType getCanonicalTemplateSpecializationType(ElaboratedTypeKeyword Keyword, TemplateName T, ArrayRef< TemplateArgument > CanonicalArgs) const
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
getObjCInterfaceType - Return the unique reference to the type for the specified ObjC interface decl.
void adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig, ObjCTypeParamDecl *New) const
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
QualType getAutoRRefDeductType() const
C++11 deduction pattern for 'auto &&' type.
TypedefDecl * getBuiltinMSVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_ms_va_list type.
bool ObjCQualifiedIdTypesAreCompatible(const ObjCObjectPointerType *LHS, const ObjCObjectPointerType *RHS, bool ForCompare)
ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an ObjCQualifiedIDType.
QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool AllowCXX=false, bool IsConditionalOperator=false)
NamedDecl * getInstantiatedFromUsingDecl(NamedDecl *Inst)
If the given using decl Inst is an instantiation of another (possibly unresolved) using decl,...
DeclarationNameTable DeclarationNames
Definition ASTContext.h:776
comments::FullComment * cloneFullComment(comments::FullComment *FC, const Decl *D) const
CharUnits getObjCEncodingTypeSize(QualType T) const
Return the size of type T for Objective-C encoding purpose, in characters.
int getIntegerTypeOrder(QualType LHS, QualType RHS) const
Return the highest ranked integer type, see C99 6.3.1.8p1.
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType, const Attr *attr=nullptr) const
TypedefDecl * getObjCIdDecl() const
Retrieve the typedef corresponding to the predefined id type in Objective-C.
void setCurrentNamedModule(Module *M)
Set the (C++20) module we are building.
QualType getProcessIDType() const
Return the unique type for "pid_t" defined in <sys/types.h>.
CharUnits getMemberPointerPathAdjustment(const APValue &MP) const
Find the 'this' offset for the member path in a pointer-to-member APValue.
bool mayExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel may be externalized.
std::unique_ptr< MangleNumberingContext > createMangleNumberingContext() const
CanQualType SatAccumTy
QualType getUnsignedPointerDiffType() const
Return the unique unsigned counterpart of "ptrdiff_t" integer type.
QualType getScalableVectorType(QualType EltTy, unsigned NumElts, unsigned NumFields=1) const
Return the unique reference to a scalable vector type of the specified element type and scalable numb...
bool hasSameExpr(const Expr *X, const Expr *Y) const
Determine whether the given expressions X and Y are equivalent.
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
MangleContext * createMangleContext(const TargetInfo *T=nullptr)
If T is null pointer, assume the target in ASTContext.
QualType getRealTypeForBitwidth(unsigned DestWidth, FloatModeKind ExplicitType) const
getRealTypeForBitwidth - sets floating point QualTy according to specified bitwidth.
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
CanQualType ShortAccumTy
ASTMutationListener * getASTMutationListener() const
Retrieve a pointer to the AST mutation listener associated with this AST context, if any.
unsigned NumImplicitCopyAssignmentOperatorsDeclared
The number of implicitly-declared copy assignment operators for which declarations were built.
uint64_t getTargetNullPointerValue(QualType QT) const
Get target-dependent integer value for null pointer which is used for constant folding.
unsigned getTypeUnadjustedAlign(QualType T) const
Return the ABI-specified natural alignment of a (complete) type T, before alignment adjustments,...
unsigned char getFixedPointIBits(QualType Ty) const
QualType getSubstBuiltinTemplatePack(const TemplateArgument &ArgPack)
QualType getCorrespondingSignedFixedPointType(QualType Ty) const
IntrusiveRefCntPtr< ExternalASTSource > ExternalSource
Definition ASTContext.h:777
CanQualType FloatTy
QualType getArrayParameterType(QualType Ty) const
Return the uniqued reference to a specified array parameter type from the original array type.
QualType getCountAttributedType(QualType T, Expr *CountExpr, bool CountInBytes, bool OrNull, ArrayRef< TypeCoupledDeclRefInfo > DependentDecls) const
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
unsigned NumImplicitDestructorsDeclared
The number of implicitly-declared destructors for which declarations were built.
bool mergeExtParameterInfo(const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType, bool &CanUseFirst, bool &CanUseSecond, SmallVectorImpl< FunctionProtoType::ExtParameterInfo > &NewParamInfos)
This function merges the ExtParameterInfo lists of two functions.
bool ObjCQualifiedClassTypesAreCompatible(const ObjCObjectPointerType *LHS, const ObjCObjectPointerType *RHS)
ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and Class<pr1, ...>.
bool shouldExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel should be externalized.
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
bool propertyTypesAreCompatible(QualType, QualType)
void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, UsingShadowDecl *Pattern)
CanQualType DoubleTy
QualType getDependentVectorType(QualType VectorType, Expr *SizeExpr, SourceLocation AttrLoc, VectorKind VecKind) const
Return the unique reference to the type for a dependently sized vector of the specified element type.
CanQualType SatLongAccumTy
CanQualType getIntMaxType() const
Return the unique type for "intmax_t" (C99 7.18.1.5), defined in <stdint.h>.
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
OpenCLTypeKind getOpenCLTypeKind(const Type *T) const
Map an AST Type to an OpenCLTypeKind enum value.
TemplateName getDependentTemplateName(const DependentTemplateStorage &Name) const
Retrieve the template name that represents a dependent template name such as MetaFun::template operat...
ArrayRef< Decl * > getModuleInitializers(Module *M)
Get the initializations to perform when importing a module, if any.
void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, std::string &S) const
Put the string version of the type qualifiers QT into S.
unsigned getPreferredTypeAlign(QualType T) const
Return the "preferred" alignment of the specified type T for the current target, in bits.
std::string getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, bool Extended=false) const
Emit the encoded type for the method declaration Decl into S.
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
CanQualType LongDoubleTy
CanQualType OMPArrayShapingTy
ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents, SelectorTable &sels, Builtin::Context &builtins, TranslationUnitKind TUKind)
QualType getReadPipeType(QualType T) const
Return a read_only pipe type for the specified type.
std::string getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, const Decl *Container) const
getObjCEncodingForPropertyDecl - Return the encoded type for this method declaration.
CanQualType Char16Ty
TemplateName getCanonicalTemplateName(TemplateName Name, bool IgnoreDeduced=false) const
Retrieves the "canonical" template name that refers to a given template.
unsigned getStaticLocalNumber(const VarDecl *VD) const
void addComment(const RawComment &RC)
void getLegacyIntegralTypeEncoding(QualType &t) const
getLegacyIntegralTypeEncoding - Another legacy compatibility encoding: 32-bit longs are encoded as 'l...
bool isSameTypeConstraint(const TypeConstraint *XTC, const TypeConstraint *YTC) const
Determine whether two type contraint are similar enough that they could used in declarations of the s...
void setRelocationInfoForCXXRecord(const CXXRecordDecl *, CXXRecordDeclRelocationInfo)
QualType getSubstTemplateTypeParmType(QualType Replacement, Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex, bool Final) const
Retrieve a substitution-result type.
RecordDecl * buildImplicitRecord(StringRef Name, RecordDecl::TagKind TK=RecordDecl::TagKind::Struct) const
Create a new implicit TU-level CXXRecordDecl or RecordDecl declaration.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const CXXMethodDecl * getCurrentKeyFunction(const CXXRecordDecl *RD)
Get our current best idea for the key function of the given record decl, or nullptr if there isn't on...
CanQualType UnsignedLongFractTy
QualType mergeTagDefinitions(QualType, QualType)
overridden_method_range overridden_methods(const CXXMethodDecl *Method) const
void setIsTypeAwareOperatorNewOrDelete(const FunctionDecl *FD, bool IsTypeAware)
QualType getDependentBitIntType(bool Unsigned, Expr *BitsExpr) const
Return a dependent bit-precise integer type with the specified signedness and bit count.
void setObjCImplementation(ObjCInterfaceDecl *IFaceD, ObjCImplementationDecl *ImplD)
Set the implementation of ObjCInterfaceDecl.
StringRef getCUIDHash() const
bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const
Returns true if this is an inline-initialized static data member which is treated as a definition for...
bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
canAssignObjCInterfaces - Return true if the two interface types are compatible for assignment from R...
CanQualType VoidPtrTy
QualType getReferenceQualifiedType(const Expr *e) const
getReferenceQualifiedType - Given an expr, will return the type for that expression,...
bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U) const
Determine whether two function types are the same, ignoring exception specifications in cases where t...
QualType getBlockDescriptorExtendedType() const
Gets the struct used to keep track of the extended descriptor for pointer to blocks.
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT, ObjCInterfaceDecl *IDecl)
QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in QT's qualified-id protocol list adopt...
FunctionProtoType::ExceptionSpecInfo mergeExceptionSpecs(FunctionProtoType::ExceptionSpecInfo ESI1, FunctionProtoType::ExceptionSpecInfo ESI2, SmallVectorImpl< QualType > &ExceptionTypeStorage, bool AcceptDependent) const
void addLazyModuleInitializers(Module *M, ArrayRef< GlobalDeclID > IDs)
bool isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const
Determine whether two 'requires' expressions are similar enough that they may be used in re-declarati...
bool BlockRequiresCopying(QualType Ty, const VarDecl *D)
Returns true iff we need copy/dispose helpers for the given type.
CanQualType NullPtrTy
QualType getUsingType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UsingShadowDecl *D, QualType UnderlyingType=QualType()) const
CanQualType WideCharTy
CanQualType OMPIteratorTy
IdentifierTable & Idents
Definition ASTContext.h:772
Builtin::Context & BuiltinInfo
Definition ASTContext.h:774
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:926
QualType getFunctionTypeWithoutPtrSizes(QualType T)
Get a function type and produce the equivalent function type where pointer size address spaces in the...
uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID, const ObjCIvarDecl *Ivar) const
Get the offset of an ObjCIvarDecl in bits.
SelectorTable & Selectors
Definition ASTContext.h:773
bool isTypeIgnoredBySanitizer(const SanitizerMask &Mask, const QualType &Ty) const
Check if a type can have its sanitizer instrumentation elided based on its presence within an ignorel...
unsigned getMinGlobalAlignOfVar(uint64_t Size, const VarDecl *VD) const
Return the minimum alignment as specified by the target.
RawCommentList Comments
All comments in this translation unit.
Definition ASTContext.h:959
bool isSameDefaultTemplateArgument(const NamedDecl *X, const NamedDecl *Y) const
Determine whether two default template arguments are similar enough that they may be used in declarat...
QualType applyObjCProtocolQualifiers(QualType type, ArrayRef< ObjCProtocolDecl * > protocols, bool &hasError, bool allowOnPointerType=false) const
Apply Objective-C protocol qualifiers to the given type.
QualType getMacroQualifiedType(QualType UnderlyingTy, const IdentifierInfo *MacroII) const
QualType removePtrSizeAddrSpace(QualType T) const
Remove the existing address space on the type if it is a pointer size address space and return the ty...
bool areLaxCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible RISC-V vector types as defined by -flax-vect...
CanQualType SatShortFractTy
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod) const
Retrieves the default calling convention for the current context.
bool canBindObjCObjectType(QualType To, QualType From)
TemplateTemplateParmDecl * insertCanonicalTemplateTemplateParmDeclInternal(TemplateTemplateParmDecl *CanonTTP) const
int getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const
Compare the rank of two floating point types as above, but compare equal if both types have the same ...
QualType getUIntPtrType() const
Return a type compatible with "uintptr_t" (C99 7.18.1.4), as defined by the target.
void setParameterIndex(const ParmVarDecl *D, unsigned index)
Used by ParmVarDecl to store on the side the index of the parameter when it exceeds the size of the n...
QualType getFunctionTypeWithExceptionSpec(QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const
Get a function type and produce the equivalent function type with the specified exception specificati...
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier NNS, const IdentifierInfo *Name) const
Qualifiers::GC getObjCGCAttrKind(QualType Ty) const
Return one of the GCNone, Weak or Strong Objective-C garbage collection attributes.
CanQualType Ibm128Ty
bool hasUniqueObjectRepresentations(QualType Ty, bool CheckIfTriviallyCopyable=true) const
Return true if the specified type has unique object representations according to (C++17 [meta....
CanQualType getCanonicalSizeType() const
bool typesAreBlockPointerCompatible(QualType, QualType)
CanQualType SatUnsignedAccumTy
bool useAbbreviatedThunkName(GlobalDecl VirtualMethodDecl, StringRef MangledName)
const ASTRecordLayout & getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const
Get or compute information about the layout of the specified Objective-C interface.
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
void setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst, UsingEnumDecl *Pattern)
Remember that the using enum decl Inst is an instantiation of the using enum decl Pattern of a class ...
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
QualType getSignatureParameterType(QualType T) const
Retrieve the parameter type as adjusted for use in the signature of a function, decaying array and fu...
CanQualType ArraySectionTy
CanQualType ObjCBuiltinIdTy
overridden_cxx_method_iterator overridden_methods_end(const CXXMethodDecl *Method) const
VTableContextBase * getVTableContext()
ComparisonCategories CompCategories
Types and expressions required to build C++2a three-way comparisons using operator<=>,...
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const
ObjCPropertyImplDecl * getObjCPropertyImplDeclForPropertyDecl(const ObjCPropertyDecl *PD, const Decl *Container) const
bool isNearlyEmpty(const CXXRecordDecl *RD) const
PointerAuthQualifier getObjCMemberSelTypePtrAuth()
QualType AutoDeductTy
CanQualType BoolTy
void cacheRawCommentForDecl(const Decl &OriginalD, const RawComment &Comment) const
Attaches Comment to OriginalD and to its redeclaration chain and removes the redeclaration chain from...
void attachCommentsToJustParsedDecls(ArrayRef< Decl * > Decls, const Preprocessor *PP)
Searches existing comments for doc comments that should be attached to Decls.
QualType getIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
getIntTypeForBitwidth - sets integer QualTy according to specified details: bitwidth,...
void setStaticLocalNumber(const VarDecl *VD, unsigned Number)
QualType getCFConstantStringType() const
Return the C structure type used to represent constant CFStrings.
void eraseDeclAttrs(const Decl *D)
Erase the attributes corresponding to the given declaration.
UsingEnumDecl * getInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst)
If the given using-enum decl Inst is an instantiation of another using-enum decl, return it.
RecordDecl * getCFConstantStringTagDecl() const
std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const
Emit the encoded type for the function Decl into S.
TypeSourceInfo * getTemplateSpecializationTypeInfo(ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc, TemplateName T, SourceLocation TLoc, const TemplateArgumentListInfo &SpecifiedArgs, ArrayRef< TemplateArgument > CanonicalArgs, QualType Canon=QualType()) const
QualType getTemplateTypeParmType(unsigned Depth, unsigned Index, bool ParameterPack, TemplateTypeParmDecl *ParmDecl=nullptr) const
Retrieve the template type parameter type for a template parameter or parameter pack with the given d...
CanQualType UnsignedFractTy
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
QualType mergeFunctionParameterTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false)
mergeFunctionParameterTypes - merge two types which appear as function parameter types
void addOverriddenMethod(const CXXMethodDecl *Method, const CXXMethodDecl *Overridden)
Note that the given C++ Method overrides the given Overridden method.
TemplateTemplateParmDecl * findCanonicalTemplateTemplateParmDeclInternal(TemplateTemplateParmDecl *TTP) const
CanQualType Float128Ty
CanQualType ObjCBuiltinClassTy
unsigned NumImplicitDefaultConstructorsDeclared
The number of implicitly-declared default constructors for which declarations were built.
CanQualType UnresolvedTemplateTy
OMPTraitInfo & getNewOMPTraitInfo()
Return a new OMPTraitInfo object owned by this context.
friend class CXXRecordDecl
Definition ASTContext.h:555
CanQualType UnsignedLongTy
void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass, SmallVectorImpl< const ObjCIvarDecl * > &Ivars) const
DeepCollectObjCIvars - This routine first collects all declared, but not synthesized,...
bool computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits, unsigned NumPositiveBits, QualType &BestType, QualType &BestPromotionType)
Compute BestType and BestPromotionType for an enum based on the highest number of negative and positi...
llvm::APFixedPoint getFixedPointMin(QualType Ty) const
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
QualType adjustType(QualType OldType, llvm::function_ref< QualType(QualType)> Adjust) const
Rebuild a type, preserving any existing type sugar.
void addedLocalImportDecl(ImportDecl *Import)
Notify the AST context that a new import declaration has been parsed or implicitly created within thi...
const TranslationUnitKind TUKind
Definition ASTContext.h:775
CanQualType UnsignedLongAccumTy
QualType AutoRRefDeductTy
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
CanQualType ShortFractTy
QualType getStringLiteralArrayType(QualType EltTy, unsigned Length) const
Return a type for a constant array for a string literal of the specified element type and length.
QualType getCorrespondingSaturatedType(QualType Ty) const
bool isSameEntity(const NamedDecl *X, const NamedDecl *Y) const
Determine whether the two declarations refer to the same entity.
QualType getSubstTemplateTypeParmPackType(Decl *AssociatedDecl, unsigned Index, bool Final, const TemplateArgument &ArgPack)
CanQualType BoundMemberTy
CanQualType SatUnsignedShortFractTy
CanQualType CharTy
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
bool hasSameFunctionTypeIgnoringParamABI(QualType T, QualType U) const
Determine if two function types are the same, ignoring parameter ABI annotations.
TypedefDecl * getInt128Decl() const
Retrieve the declaration for the 128-bit signed integer type.
unsigned getOpenMPDefaultSimdAlign(QualType T) const
Get default simd alignment of the specified complete type in bits.
QualType getObjCSuperType() const
Returns the C struct type for objc_super.
QualType getBlockDescriptorType() const
Gets the struct used to keep track of the descriptor for pointer to blocks.
bool CommentsLoaded
True if comments are already loaded from ExternalASTSource.
Definition ASTContext.h:962
BlockVarCopyInit getBlockVarCopyInit(const VarDecl *VD) const
Get the copy initialization expression of the VarDecl VD, or nullptr if none exists.
QualType getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size, uint32_t Alignment, ArrayRef< SpirvOperand > Operands)
unsigned NumImplicitMoveConstructorsDeclared
The number of implicitly-declared move constructors for which declarations were built.
bool isInSameModule(const Module *M1, const Module *M2) const
If the two module M1 and M2 are in the same module.
unsigned NumImplicitCopyConstructorsDeclared
The number of implicitly-declared copy constructors for which declarations were built.
CanQualType IntTy
llvm::DenseSet< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
CanQualType PseudoObjectTy
QualType getWebAssemblyExternrefType() const
Return a WebAssembly externref type.
void setTraversalScope(const std::vector< Decl * > &)
CharUnits getTypeUnadjustedAlignInChars(QualType T) const
getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a type, in characters,...
QualType getAdjustedType(QualType Orig, QualType New) const
Return the uniqued reference to a type adjusted from the original type to a new type.
friend class NestedNameSpecifier
Definition ASTContext.h:221
void PrintStats() const
unsigned getAlignOfGlobalVar(QualType T, const VarDecl *VD) const
Return the alignment in bits that should be given to a global variable with type T.
TypeInfoChars getTypeInfoDataSizeInChars(QualType T) const
MangleNumberingContext & getManglingNumberContext(const DeclContext *DC)
Retrieve the context for computing mangling numbers in the given DeclContext.
comments::FullComment * getLocalCommentForDeclUncached(const Decl *D) const
Return parsed documentation comment attached to a given declaration.
unsigned NumImplicitDestructors
The number of implicitly-declared destructors.
CanQualType Float16Ty
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
bool isAlignmentRequired(const Type *T) const
Determine if the alignment the type has was required using an alignment attribute.
TagDecl * MSGuidTagDecl
bool areComparableObjCPointerTypes(QualType LHS, QualType RHS)
MangleContext * createDeviceMangleContext(const TargetInfo &T)
Creates a device mangle context to correctly mangle lambdas in a mixed architecture compile by settin...
CharUnits getExnObjectAlignment() const
Return the alignment (in bytes) of the thrown exception object.
CanQualType SignedCharTy
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
ASTMutationListener * Listener
Definition ASTContext.h:778
CanQualType ObjCBuiltinBoolTy
TypeInfoChars getTypeInfoInChars(const Type *T) const
QualType getPredefinedSugarType(PredefinedSugarType::Kind KD) const
QualType getObjCObjectType(QualType Base, ObjCProtocolDecl *const *Protocols, unsigned NumProtocols) const
Legacy interface: cannot provide type arguments or __kindof.
TemplateParamObjectDecl * getTemplateParamObjectDecl(QualType T, const APValue &V) const
Return the template parameter object of the given type with the given value.
CanQualType OverloadTy
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
TemplateTemplateParmDecl * getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const
Canonicalize the given TemplateTemplateParmDecl.
CanQualType OCLClkEventTy
void adjustExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, bool AsWritten=false)
Change the exception specification on a function once it is delay-parsed, instantiated,...
TypedefDecl * getUInt128Decl() const
Retrieve the declaration for the 128-bit unsigned integer type.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:825
void ResetObjCLayout(const ObjCInterfaceDecl *D)
ArrayRef< Module * > getModulesWithMergedDefinition(const NamedDecl *Def)
Get the additional modules in which the definition Def has been merged.
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
CanQualType SatUnsignedShortAccumTy
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false, bool IsConditionalOperator=false)
const RawComment * getRawCommentForAnyRedecl(const Decl *D, const Decl **OriginalDecl=nullptr) const
Return the documentation comment attached to a given declaration.
CharUnits getAlignOfGlobalVarInChars(QualType T, const VarDecl *VD) const
Return the alignment in characters that should be given to a global variable with type T.
const ObjCMethodDecl * getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const
Get the duplicate declaration of a ObjCMethod in the same interface, or null if none exists.
QualType getPackIndexingType(QualType Pattern, Expr *IndexExpr, bool FullySubstituted=false, ArrayRef< QualType > Expansions={}, UnsignedOrNone Index=std::nullopt) const
static bool isObjCNSObjectType(QualType Ty)
Return true if this is an NSObject object with its NSObject attribute set.
GVALinkage GetGVALinkageForVariable(const VarDecl *VD) const
llvm::PointerUnion< VarTemplateDecl *, MemberSpecializationInfo * > TemplateOrSpecializationInfo
A type synonym for the TemplateOrInstantiation mapping.
Definition ASTContext.h:547
UsingShadowDecl * getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst)
QualType getVariableArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a non-unique reference to the type for a variable array of the specified element type.
QualType getObjCIdType() const
Represents the Objective-CC id type.
Decl * getVaListTagDecl() const
Retrieve the C type declaration corresponding to the predefined __va_list_tag type used to help defin...
QualType getUnsignedWCharType() const
Return the type of "unsigned wchar_t".
QualType getFunctionTypeWithoutParamABIs(QualType T) const
Get or construct a function type that is equivalent to the input type except that the parameter ABI a...
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
QualType getCorrespondingUnsaturatedType(QualType Ty) const
comments::FullComment * getCommentForDecl(const Decl *D, const Preprocessor *PP) const
Return parsed documentation comment attached to a given declaration.
TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl) const
unsigned getTargetDefaultAlignForAttributeAligned() const
Return the default alignment for attribute((aligned)) on this target, to be used if no alignment valu...
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
llvm::DenseMap< CanQualType, SYCLKernelInfo > SYCLKernels
Map of SYCL kernels indexed by the unique type used to name the kernel.
bool isSameTemplateParameterList(const TemplateParameterList *X, const TemplateParameterList *Y) const
Determine whether two template parameter lists are similar enough that they may be used in declaratio...
QualType getWritePipeType(QualType T) const
Return a write_only pipe type for the specified type.
QualType getTypeDeclType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypeDecl *Decl) const
bool isDestroyingOperatorDelete(const FunctionDecl *FD) const
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CanQualType UnsignedInt128Ty
CanQualType BuiltinFnTy
ObjCInterfaceDecl * getObjCProtocolDecl() const
Retrieve the Objective-C class declaration corresponding to the predefined Protocol class.
unsigned NumImplicitDefaultConstructors
The number of implicitly-declared default constructors.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
llvm::iterator_range< overridden_cxx_method_iterator > overridden_method_range
unsigned NumImplicitMoveAssignmentOperatorsDeclared
The number of implicitly-declared move assignment operators for which declarations were built.
void setManglingNumber(const NamedDecl *ND, unsigned Number)
llvm::DenseMap< const Decl *, const RawComment * > DeclRawComments
Mapping from declaration to directly attached comment.
Definition ASTContext.h:968
CanQualType OCLSamplerTy
QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent, bool IsPack=false, TemplateDecl *TypeConstraintConcept=nullptr, ArrayRef< TemplateArgument > TypeConstraintArgs={}) const
C++11 deduced auto type.
TypedefDecl * getBuiltinVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_va_list type.
CanQualType getCanonicalTypeDeclType(const TypeDecl *TD) const
CanQualType VoidTy
QualType getPackExpansionType(QualType Pattern, UnsignedOrNone NumExpansions, bool ExpectPackInType=true) const
Form a pack expansion type with the given pattern.
CanQualType UnsignedCharTy
CanQualType UnsignedShortFractTy
BuiltinTemplateDecl * buildBuiltinTemplateDecl(BuiltinTemplateKind BTK, const IdentifierInfo *II) const
void * Allocate(size_t Size, unsigned Align=8) const
Definition ASTContext.h:846
bool canBuiltinBeRedeclared(const FunctionDecl *) const
Return whether a declaration to a builtin is allowed to be overloaded/redeclared.
CanQualType UnsignedIntTy
unsigned NumImplicitMoveConstructors
The number of implicitly-declared move constructors.
QualType getTypedefType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType UnderlyingType=QualType(), std::optional< bool > TypeMatchesDeclOrNone=std::nullopt) const
Return the unique reference to the type for the specified typedef-name decl.
QualType getObjCTypeParamType(const ObjCTypeParamDecl *Decl, ArrayRef< ObjCProtocolDecl * > protocols) const
void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, QualType T, std::string &S, bool Extended) const
getObjCEncodingForMethodParameter - Return the encoded type for a single method parameter or return t...
void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD)
unsigned overridden_methods_size(const CXXMethodDecl *Method) const
std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const
Return the encoded type for this block declaration.
QualType getTemplateSpecializationType(ElaboratedTypeKeyword Keyword, TemplateName T, ArrayRef< TemplateArgument > SpecifiedArgs, ArrayRef< TemplateArgument > CanonicalArgs, QualType Underlying=QualType()) const
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
TemplateName getQualifiedTemplateName(NestedNameSpecifier Qualifier, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
bool isSameAssociatedConstraint(const AssociatedConstraint &ACX, const AssociatedConstraint &ACY) const
Determine whether two 'requires' expressions are similar enough that they may be used in re-declarati...
QualType getExceptionObjectType(QualType T) const
CanQualType UnknownAnyTy
void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
Note that the static data member Inst is an instantiation of the static data member template Tmpl of ...
FieldDecl * getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) const
DeclaratorDecl * getDeclaratorForUnnamedTagDecl(const TagDecl *TD)
bool ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *Decl)
ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's protocol list adopt all protocols in Q...
CanQualType UnsignedLongLongTy
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
CanQualType OCLReserveIDTy
bool isSameTemplateParameter(const NamedDecl *X, const NamedDecl *Y) const
Determine whether two template parameters are similar enough that they may be used in declarations of...
void registerSYCLEntryPointFunction(FunctionDecl *FD)
Generates and stores SYCL kernel metadata for the provided SYCL kernel entry point function.
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
overridden_cxx_method_iterator overridden_methods_begin(const CXXMethodDecl *Method) const
CanQualType UnsignedShortTy
unsigned getTypeAlignIfKnown(QualType T, bool NeedsPreferredAlignment=false) const
Return the alignment of a type, in bits, or 0 if the type is incomplete and we cannot determine the a...
void UnwrapSimilarArrayTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true) const
Attempt to unwrap two types that may both be array types with the same bound (or both be array types ...
bool isRepresentableIntegerValue(llvm::APSInt &Value, QualType T)
Determine whether the given integral value is representable within the given type T.
bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
const SYCLKernelInfo & getSYCLKernelInfo(QualType T) const
Given a type used as a SYCL kernel name, returns a reference to the metadata generated from the corre...
bool canAssignObjCInterfacesInBlockPointer(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT, bool BlockReturnType)
canAssignObjCInterfacesInBlockPointer - This routine is specifically written for providing type-safet...
CanQualType SatUnsignedLongFractTy
QualType getMemberPointerType(QualType T, NestedNameSpecifier Qualifier, const CXXRecordDecl *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
const CXXConstructorDecl * getCopyConstructorForExceptionObject(CXXRecordDecl *RD)
QualType getDependentAddressSpaceType(QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttrLoc) const
RawComment * getRawCommentForDeclNoCache(const Decl *D) const
Return the documentation comment attached to a given declaration, without looking into cache.
QualType getTagType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TagDecl *TD, bool OwnsTag) const
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
CanQualType getMSGuidType() const
Retrieve the implicitly-predeclared 'struct _GUID' type.
const VariableArrayType * getAsVariableArrayType(QualType T) const
QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType, UnaryTransformType::UTTKind UKind) const
Unary type transforms.
void setExternalSource(IntrusiveRefCntPtr< ExternalASTSource > Source)
Attach an external AST source to the AST context.
const ObjCInterfaceDecl * getObjContainingInterface(const NamedDecl *ND) const
Returns the Objective-C interface that ND belongs to if it is an Objective-C method/property/ivar etc...
CanQualType ShortTy
StringLiteral * getPredefinedStringLiteralFromCache(StringRef Key) const
Return a string representing the human readable name for the specified function declaration or file n...
CanQualType getCanonicalUnresolvedUsingType(const UnresolvedUsingTypenameDecl *D) const
bool hasSimilarType(QualType T1, QualType T2) const
Determine if two types are similar, according to the C++ rules.
llvm::APFixedPoint getFixedPointMax(QualType Ty) const
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type.
bool hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
CanQualType FractTy
Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const
Recurses in pointer/array types until it finds an Objective-C retainable type and returns its ownersh...
void addCopyConstructorForExceptionObject(CXXRecordDecl *RD, CXXConstructorDecl *CD)
void deduplicateMergedDefinitionsFor(NamedDecl *ND)
Clean up the merged definition list.
DiagnosticsEngine & getDiagnostics() const
QualType getAdjustedParameterType(QualType T) const
Perform adjustment on the parameter type of a function.
CanQualType LongAccumTy
interp::Context & getInterpContext()
Returns the clang bytecode interpreter context.
CanQualType Char32Ty
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
UnnamedGlobalConstantDecl * getUnnamedGlobalConstantDecl(QualType Ty, const APValue &Value) const
Return a declaration for a uniquified anonymous global constant corresponding to a given APValue.
CanQualType SatFractTy
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
QualType getUnresolvedUsingType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UnresolvedUsingTypenameDecl *D) const
bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec)
Return true if the given vector types are of the same unqualified type or if they are equivalent to t...
void getOverriddenMethods(const NamedDecl *Method, SmallVectorImpl< const NamedDecl * > &Overridden) const
Return C++ or ObjC overridden methods for the given Method.
DeclarationNameInfo getNameForTemplate(TemplateName Name, SourceLocation NameLoc) const
bool hasSameTemplateName(const TemplateName &X, const TemplateName &Y, bool IgnoreDeduced=false) const
Determine whether the given template names refer to the same template.
CanQualType SatLongFractTy
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:891
void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl)
CanQualType OCLQueueTy
CanQualType LongFractTy
CanQualType SatShortAccumTy
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
CanQualType BFloat16Ty
unsigned NumImplicitCopyConstructors
The number of implicitly-declared copy constructors.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType IncompleteMatrixIdxTy
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
CanQualType getNSIntegerType() const
QualType getCorrespondingUnsignedType(QualType T) const
void setBlockVarCopyInit(const VarDecl *VD, Expr *CopyExpr, bool CanThrow)
Set the copy initialization expression of a block var decl.
TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, UnresolvedSetIterator End) const
Retrieve the template name that corresponds to a non-empty lookup.
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
TemplateName getSubstTemplateTemplateParmPack(const TemplateArgument &ArgPack, Decl *AssociatedDecl, unsigned Index, bool Final) const
QualType getDeducedTemplateSpecializationType(ElaboratedTypeKeyword Keyword, TemplateName Template, QualType DeducedType, bool IsDependent) const
C++17 deduced class template specialization type.
TargetCXXABI::Kind getCXXABIKind() const
Return the C++ ABI kind that should be used.
QualType getHLSLAttributedResourceType(QualType Wrapped, QualType Contained, const HLSLAttributedResourceType::Attributes &Attrs)
bool UnwrapSimilarTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true) const
Attempt to unwrap two types that may be similar (C++ [conv.qual]).
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
QualType getSignedSizeType() const
Return the unique signed counterpart of the integer type corresponding to size_t.
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const
Return number of constant array elements.
CanQualType SatUnsignedLongAccumTy
QualType getUnconstrainedType(QualType T) const
Remove any type constraints from a template parameter type, for equivalence comparison of template pa...
CanQualType LongLongTy
CanQualType getCanonicalTagType(const TagDecl *TD) const
bool isSameTemplateArgument(const TemplateArgument &Arg1, const TemplateArgument &Arg2) const
Determine whether the given template arguments Arg1 and Arg2 are equivalent.
QualType getTypeOfType(QualType QT, TypeOfKind Kind) const
getTypeOfType - Unlike many "get<Type>" functions, we don't unique TypeOfType nodes.
QualType getCorrespondingSignedType(QualType T) const
QualType mergeObjCGCQualifiers(QualType, QualType)
mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 'RHS' attributes and ret...
llvm::DenseMap< const Decl *, const Decl * > CommentlessRedeclChains
Keeps track of redeclaration chains that don't have any comment attached.
Definition ASTContext.h:984
uint64_t getArrayInitLoopExprElementCount(const ArrayInitLoopExpr *AILE) const
Return number of elements initialized in an ArrayInitLoopExpr.
unsigned getTargetAddressSpace(LangAS AS) const
QualType getIntPtrType() const
Return a type compatible with "intptr_t" (C99 7.18.1.4), as defined by the target.
void mergeDefinitionIntoModule(NamedDecl *ND, Module *M, bool NotifyListeners=true)
Note that the definition ND has been merged into module M, and should be visible whenever M is visibl...
QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a non-unique reference to the type for a dependently-sized array of the specified element type...
void addTranslationUnitDecl()
CanQualType WCharTy
void getObjCEncodingForPropertyType(QualType T, std::string &S) const
Emit the Objective-C property type encoding for the given type T into S.
unsigned NumImplicitCopyAssignmentOperators
The number of implicitly-declared copy assignment operators.
void CollectInheritedProtocols(const Decl *CDecl, llvm::SmallPtrSet< ObjCProtocolDecl *, 8 > &Protocols)
CollectInheritedProtocols - Collect all protocols in current class and those inherited by it.
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
llvm::DenseMap< const Decl *, const Decl * > RedeclChainComments
Mapping from canonical declaration to the first redeclaration in chain that has a comment attached.
Definition ASTContext.h:975
void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType)
Change the result type of a function type once it is deduced.
QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const
Return the uniqued reference to the type for an Objective-C gc-qualified type.
QualType getDecltypeType(Expr *e, QualType UnderlyingType) const
C++11 decltype.
std::optional< CXXRecordDeclRelocationInfo > getRelocationInfoForCXXRecord(const CXXRecordDecl *) const
InlineVariableDefinitionKind getInlineVariableDefinitionKind(const VarDecl *VD) const
Determine whether a definition of this inline variable should be treated as a weak or strong definiti...
TemplateName getSubstTemplateTemplateParm(TemplateName replacement, Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex, bool Final) const
CanQualType getUIntMaxType() const
Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in <stdint.h>.
friend class DeclContext
uint16_t getPointerAuthVTablePointerDiscriminator(const CXXRecordDecl *RD)
Return the "other" discriminator used for the pointer auth schema used for vtable pointers in instanc...
CharUnits getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const
Loading virtual member pointers using the virtual inheritance model always results in an adjustment u...
LangAS getLangASForBuiltinAddressSpace(unsigned AS) const
bool hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U)
Determine whether two function types are the same, ignoring pointer sizes in the return type and para...
unsigned char getFixedPointScale(QualType Ty) const
QualType getIncompleteArrayType(QualType EltTy, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a unique reference to the type for an incomplete array of the specified element type.
QualType getDependentSizedExtVectorType(QualType VectorType, Expr *SizeExpr, SourceLocation AttrLoc) const
QualType DecodeTypeStr(const char *&Str, const ASTContext &Context, ASTContext::GetBuiltinTypeError &Error, bool &RequireICE, bool AllowTypeModifiers) const
TemplateName getAssumedTemplateName(DeclarationName Name) const
Retrieve a template name representing an unqualified-id that has been assumed to name a template for ...
@ GE_None
No error.
@ GE_Missing_type
Missing a type.
QualType adjustStringLiteralBaseType(QualType StrLTy) const
uint16_t getPointerAuthTypeDiscriminator(QualType T)
Return the "other" type-specific discriminator for the given type.
bool canonicalizeTemplateArguments(MutableArrayRef< TemplateArgument > Args) const
Canonicalize the given template argument list.
QualType getTypeOfExprType(Expr *E, TypeOfKind Kind) const
C23 feature and GCC extension.
CanQualType Char8Ty
QualType getSignedWCharType() const
Return the type of "signed wchar_t".
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
bool hasCvrSimilarType(QualType T1, QualType T2)
Determine if two types are similar, ignoring only CVR qualifiers.
TemplateName getDeducedTemplateName(TemplateName Underlying, DefaultArguments DefaultArgs) const
Represents a TemplateName which had some of its default arguments deduced.
ObjCImplementationDecl * getObjCImplementation(ObjCInterfaceDecl *D)
Get the implementation of the ObjCInterfaceDecl D, or nullptr if none exists.
CanQualType HalfTy
CanQualType UnsignedAccumTy
void setObjCMethodRedeclaration(const ObjCMethodDecl *MD, const ObjCMethodDecl *Redecl)
void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND)
QualType getConstantMatrixType(QualType ElementType, unsigned NumRows, unsigned NumColumns) const
Return the unique reference to the matrix type of the specified element type and size.
const CXXRecordDecl * baseForVTableAuthentication(const CXXRecordDecl *ThisClass) const
Resolve the root record to be used to derive the vtable pointer authentication policy for the specifi...
QualType getVariableArrayDecayedType(QualType Ty) const
Returns a vla type where known sizes are replaced with [*].
void setCFConstantStringType(QualType T)
const SYCLKernelInfo * findSYCLKernelInfo(QualType T) const
Returns a pointer to the metadata generated from the corresponding SYCLkernel entry point if the prov...
unsigned getParameterIndex(const ParmVarDecl *D) const
Used by ParmVarDecl to retrieve on the side the index of the parameter when it exceeds the size of th...
QualType getCommonSugaredType(QualType X, QualType Y, bool Unqualified=false) const
CanQualType OCLEventTy
void AddDeallocation(void(*Callback)(void *), void *Data) const
Add a deallocation callback that will be invoked when the ASTContext is destroyed.
AttrVec & getDeclAttrs(const Decl *D)
Retrieve the attributes for the given declaration.
CXXMethodVector::const_iterator overridden_cxx_method_iterator
RawComment * getRawCommentForDeclNoCacheImpl(const Decl *D, const SourceLocation RepresentativeLocForDecl, const std::map< unsigned, RawComment * > &CommentsInFile) const
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
QualType mergeTransparentUnionType(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false)
mergeTransparentUnionType - if T is a transparent union type and a member of T is compatible with Sub...
QualType isPromotableBitField(Expr *E) const
Whether this is a promotable bitfield reference according to C99 6.3.1.1p2, bullet 2 (and GCC extensi...
bool isSentinelNullExpr(const Expr *E)
CanQualType getNSUIntegerType() const
void setIsDestroyingOperatorDelete(const FunctionDecl *FD, bool IsDestroying)
uint64_t getCharWidth() const
Return the size of the character type, in bits.
QualType getBitIntType(bool Unsigned, unsigned NumBits) const
Return a bit-precise integer type with the specified signedness and bit count.
unsigned NumImplicitMoveAssignmentOperators
The number of implicitly-declared move assignment operators.
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
virtual void DeducedReturnType(const FunctionDecl *FD, QualType ReturnType)
A function's return type has been deduced.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
CharUnits getAlignment() const
getAlignment - Get the record alignment in characters.
const CXXRecordDecl * getBaseSharingVBPtr() const
CharUnits getSize() const
getSize - Get the record size in characters.
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
CharUnits getDataSize() const
getDataSize() - Get the record data size, which is the record size without tail padding,...
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
CharUnits getNonVirtualSize() const
getNonVirtualSize - Get the non-virtual size (in chars) of an object, which is the size of the object...
CharUnits getUnadjustedAlignment() const
getUnadjustedAlignment - Get the record alignment in characters, before alignment adjustment.
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons.
Definition TypeBase.h:3489
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3508
Represents a loop initializing the elements of an array.
Definition Expr.h:5902
llvm::APInt getArraySize() const
Definition Expr.h:5924
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:5922
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition TypeBase.h:3890
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3720
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3734
Qualifiers getIndexTypeQualifiers() const
Definition TypeBase.h:3738
QualType getElementType() const
Definition TypeBase.h:3732
unsigned getIndexTypeCVRQualifiers() const
Definition TypeBase.h:3742
A structure for storing the information associated with a name that has been assumed to be a template...
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition Expr.h:6814
Expr * getPtr() const
Definition Expr.h:6845
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:8089
Attr - This represents one attribute.
Definition Attr.h:44
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8137
void Profile(llvm::FoldingSetNodeID &ID) const
Definition TypeBase.h:8154
unsigned getNumBits() const
Definition TypeBase.h:8149
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4651
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6558
Pointer to a block type.
Definition TypeBase.h:3540
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3557
Represents the builtin template declaration which is used to implement __make_integer_seq and other b...
static BuiltinTemplateDecl * Create(const ASTContext &C, DeclContext *DC, DeclarationName Name, BuiltinTemplateKind BTK)
This class is used for builtin types like 'int'.
Definition TypeBase.h:3164
Kind getKind() const
Definition TypeBase.h:3212
StringRef getName(const PrintingPolicy &Policy) const
Definition Type.cpp:3363
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition Builtins.h:228
Implements C++ ABI-specific semantic analysis functions.
Definition CXXABI.h:29
virtual ~CXXABI()
Represents a C++ constructor within a class.
Definition DeclCXX.h:2604
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2225
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr)
Definition DeclCXX.cpp:132
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:548
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition DeclCXX.h:1214
bool isDynamicClass() const
Definition DeclCXX.h:574
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1186
SplitQualType split() const
static CanQual< Type > CreateUnsafe(QualType Other)
QualType withConst() const
Retrieves a version of this type with const applied.
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
Qualifiers getQualifiers() const
Retrieve all qualifiers.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
bool isPositive() const
isPositive - Test whether the quantity is greater than zero.
Definition CharUnits.h:128
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition CharUnits.h:122
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition CharUnits.h:53
Declaration of a class template.
llvm::PointerUnion< ClassTemplateDecl *, ClassTemplatePartialSpecializationDecl * > getSpecializedTemplateOrPartial() const
Retrieve the class template or class template partial specialization which was specialized by this.
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3275
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3290
bool hasExplicitTemplateArgs() const
Whether or not template arguments were explicitly specified in the concept reference (they might not ...
Definition ASTConcept.h:205
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Definition ASTConcept.h:199
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3758
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition TypeBase.h:3854
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3814
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition TypeBase.h:3873
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3834
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4371
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4392
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4409
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4389
static constexpr bool isDimensionValid(size_t NumElements)
Returns true if NumElements is a valid matrix dimension.
Definition TypeBase.h:4400
Represents a sugar type with __counted_by or __sized_by annotations, including their _or_null variant...
Definition TypeBase.h:3436
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3472
Represents a pointer type decayed from an array or function type.
Definition TypeBase.h:3523
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
bool isFileContext() const
Definition DeclBase.h:2180
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition DeclBase.h:2125
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
void addDecl(Decl *D)
Add the declaration D into this context.
Decl::Kind getDeclKind() const
Definition DeclBase.h:2102
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1270
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
const DeclContext * getParentFunctionOrMethod(bool LexicalParent=false) const
If this decl is defined inside a function/method/block it returns the corresponding DeclContext,...
Definition DeclBase.cpp:319
bool isModuleLocal() const
Whether this declaration was a local declaration to a C++20 named module.
T * getAttr() const
Definition DeclBase.h:573
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:524
void addAttr(Attr *A)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:593
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition DeclBase.cpp:538
bool isUnconditionallyVisible() const
Determine whether this declaration is definitely visible to name lookup, independent of whether the o...
Definition DeclBase.h:859
static Decl * castFromDeclContext(const DeclContext *)
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition DeclBase.cpp:286
bool isCanonicalDecl() const
Whether this particular Decl is a canonical one.
Definition DeclBase.h:984
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:842
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:251
ObjCDeclQualifier
ObjCDeclQualifier - 'Qualifiers' written next to the return and parameter types in method declaration...
Definition DeclBase.h:198
bool isInvalidDecl() const
Definition DeclBase.h:588
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:559
SourceLocation getLocation() const
Definition DeclBase.h:439
void setImplicit(bool I=true)
Definition DeclBase.h:594
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition DeclBase.h:1049
DeclContext * getDeclContext()
Definition DeclBase.h:448
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:431
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition DeclBase.cpp:360
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:918
bool hasAttr() const
Definition DeclBase.h:577
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:978
Kind getKind() const
Definition DeclBase.h:442
DeclarationNameLoc - Additional source/type location info for a declaration name.
static DeclarationNameLoc makeCXXOperatorNameLoc(SourceLocation BeginLoc, SourceLocation EndLoc)
Construct location information for a non-literal C++ operator.
The name of a declaration.
static int compare(DeclarationName LHS, DeclarationName RHS)
Represents a ValueDecl that came out of a declarator.
Definition Decl.h:779
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:808
TemplateName getUnderlying() const
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) const
DefaultArguments getDefaultArguments() const
Represents an extended address space qualifier where the input address space value is dependent.
Definition TypeBase.h:4059
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4081
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:8182
Represents an array type in C++ whose size is a value-dependent expression.
Definition TypeBase.h:4009
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4038
Represents an extended vector type where either the type or size is dependent.
Definition TypeBase.h:4099
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4124
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition TypeBase.h:4430
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4450
Represents a dependent template name that cannot be resolved prior to template instantiation.
void Profile(llvm::FoldingSetNodeID &ID) const
IdentifierOrOverloadedOperator getName() const
NestedNameSpecifier getQualifier() const
Return the nested name specifier that qualifies this name.
bool hasTemplateKeyword() const
Was this template name was preceeded by the template keyword?
Internal representation of canonical, dependent typeof(expr) types.
Definition TypeBase.h:6209
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:6214
Represents a vector type where either the type or size is dependent.
Definition TypeBase.h:4225
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4250
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:231
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition Diagnostic.h:904
Represents an enum.
Definition Decl.h:4004
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4213
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4227
EnumDecl * getDefinitionOrSelf() const
Definition Decl.h:4111
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4168
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition Decl.cpp:5033
This represents one expression.
Definition Expr.h:112
bool isIntegerConstantExpr(const ASTContext &Ctx) const
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3090
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:4205
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:831
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:3065
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:4042
QualType getType() const
Definition Expr.h:144
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition Expr.h:434
We can encode up to four bits in the low bits of a type pointer, but there are many more type qualifi...
Definition TypeBase.h:1717
void Profile(llvm::FoldingSetNodeID &ID) const
Definition TypeBase.h:1764
ExtVectorType - Extended vector type.
Definition TypeBase.h:4265
Declaration context for names declared as extern "C" in C++.
Definition Decl.h:246
static ExternCContextDecl * Create(const ASTContext &C, TranslationUnitDecl *TU)
Definition Decl.cpp:5420
Abstract interface for external sources of AST nodes.
virtual void CompleteRedeclChain(const Decl *D)
Gives the external AST source an opportunity to complete the redeclaration chain for a declaration.
Represents a member of a struct/union/class.
Definition Decl.h:3157
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3260
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4693
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3242
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3393
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
Definition Decl.cpp:4641
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Represents a function declaration or definition.
Definition Decl.h:1999
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2686
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3703
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2918
bool isMSExternInline() const
The combination of the extern and inline keywords under MSVC forces the function to be required.
Definition Decl.cpp:3832
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3688
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4358
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition Decl.h:2409
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4106
bool isInlineDefinitionExternallyVisible() const
For an inline function definition in C, or for a gnu_inline function in C++, determine whether the de...
Definition Decl.cpp:4019
FunctionDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5232
static FunctionEffectSet getIntersection(FunctionEffectsRef LHS, FunctionEffectsRef RHS)
Definition Type.cpp:5641
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition Type.cpp:5679
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5064
ArrayRef< EffectConditionExpr > conditions() const
Definition TypeBase.h:5098
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition TypeBase.h:4842
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4858
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5264
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5768
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5571
unsigned getNumParams() const
Definition TypeBase.h:5542
QualType getParamType(unsigned i) const
Definition TypeBase.h:5544
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition Type.cpp:3956
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5577
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5668
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5553
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5549
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
Definition TypeBase.h:5737
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition TypeBase.h:5733
Declaration of a template function.
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4571
CallingConv getCC() const
Definition TypeBase.h:4630
unsigned getRegParm() const
Definition TypeBase.h:4623
bool getNoCallerSavedRegs() const
Definition TypeBase.h:4619
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4642
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition TypeBase.h:4486
ExtParameterInfo withIsNoEscape(bool NoEscape) const
Definition TypeBase.h:4526
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4460
ExtInfo getExtInfo() const
Definition TypeBase.h:4816
QualType getReturnType() const
Definition TypeBase.h:4800
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:57
unsigned getMultiVersionIndex() const
Definition GlobalDecl.h:125
CXXDtorType getDtorType() const
Definition GlobalDecl.h:113
const Decl * getDecl() const
Definition GlobalDecl.h:106
One of these records is kept for each identifier that is lexed.
unsigned getLength() const
Efficiently return the length of this identifier info.
StringRef getName() const
Return the actual identifier string.
Implements an efficient mapping from strings to IdentifierInfo nodes.
Describes a module import declaration, which makes the contents of the named module visible in the cu...
Definition Decl.h:5032
Represents a C array with an unspecified size.
Definition TypeBase.h:3907
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3924
static ItaniumMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
@ Relative
Components in the vtable are relative offsets between the vtable and the other structs/functions.
@ Pointer
Components in the vtable are pointers to other structs/functions.
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3615
@ Swift
Interoperability with the latest known version of the Swift runtime.
@ Swift4_2
Interoperability with the Swift 4.2 runtime.
@ Swift4_1
Interoperability with the Swift 4.1 runtime.
@ Integer
Permit vector bitcasts between integer vectors with different numbers of elements but the same total ...
@ All
Permit vector bitcasts between all vectors with the same total bit-width.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
std::optional< TargetCXXABI::Kind > CXXABI
C++ ABI to compile with, if specified by the frontend through -fc++-abi=.
clang::ObjCRuntime ObjCRuntime
CoreFoundationABI CFRuntime
A global _GUID constant.
Definition DeclCXX.h:4398
static void Profile(llvm::FoldingSetNodeID &ID, Parts P)
Definition DeclCXX.h:4435
MSGuidDeclParts Parts
Definition DeclCXX.h:4400
Sugar type that represents a type that was qualified by a qualifier written as a macro invocation.
Definition TypeBase.h:6143
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
Definition Mangle.h:52
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4349
static bool isValidElementType(QualType T)
Valid elements types are the following:
Definition TypeBase.h:4356
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3651
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3694
Provides information a specialization of a member of a class template, which may be a member function...
static MicrosoftMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
Describes a module or submodule.
Definition Module.h:144
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition Module.h:224
This represents a decl that may have a name.
Definition Decl.h:273
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:486
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:294
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition Decl.cpp:1095
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:339
std::string getNameAsString() const
Get a human-readable name for the declaration, even if it is one of the special kinds of names (C++ c...
Definition Decl.h:316
bool isExternallyVisible() const
Definition Decl.h:432
Represent a C++ namespace.
Definition Decl.h:591
static NamespaceDecl * Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl, bool Nested)
Definition DeclCXX.cpp:3261
A C++ nested-name-specifier augmented with source location information.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NestedNameSpecifier getCanonical() const
Retrieves the "canonical" nested name specifier for a given nested name specifier.
CXXRecordDecl * getAsMicrosoftSuper() const
NamespaceAndPrefix getAsNamespaceAndPrefix() const
bool isCanonical() const
Whether this nested name specifier is canonical.
Kind
The kind of specifier that completes this nested name specifier.
@ MicrosoftSuper
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace-like entity, stored as a NamespaceBaseDecl*.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, unsigned D, unsigned P, const IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
Helper data structure representing the traits in a match clause of an declare variant or metadirectiv...
ObjCCategoryDecl - Represents a category declaration.
Definition DeclObjC.h:2329
ObjCCategoryImplDecl - An object of this class encapsulates a category @implementation declaration.
Definition DeclObjC.h:2545
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition DeclObjC.h:2597
Represents an ObjC class declaration.
Definition DeclObjC.h:1154
ObjCTypeParamList * getTypeParamList() const
Retrieve the type parameters of this class.
Definition DeclObjC.cpp:319
static ObjCInterfaceDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation atLoc, const IdentifierInfo *Id, ObjCTypeParamList *typeParamList, ObjCInterfaceDecl *PrevDecl, SourceLocation ClassLoc=SourceLocation(), bool isInternal=false)
bool hasDefinition() const
Determine whether this class has been defined.
Definition DeclObjC.h:1528
ivar_range ivars() const
Definition DeclObjC.h:1451
bool ClassImplementsProtocol(ObjCProtocolDecl *lProto, bool lookupCategory, bool RHSIsQualifiedID=false)
ClassImplementsProtocol - Checks that 'lProto' protocol has been implemented in IDecl class,...
StringRef getObjCRuntimeNameAsString() const
Produce a name to be used for class's metadata.
ObjCImplementationDecl * getImplementation() const
ObjCInterfaceDecl * getSuperClass() const
Definition DeclObjC.cpp:349
bool isSuperClassOf(const ObjCInterfaceDecl *I) const
isSuperClassOf - Return true if this class is the specified class or is a super class of the specifie...
Definition DeclObjC.h:1810
known_extensions_range known_extensions() const
Definition DeclObjC.h:1762
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:7847
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
Definition Type.cpp:951
ObjCIvarDecl - Represents an ObjC instance variable.
Definition DeclObjC.h:1952
ObjCIvarDecl * getNextIvar()
Definition DeclObjC.h:1987
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
ObjCDeclQualifier getObjCDeclQualifier() const
Definition DeclObjC.h:246
unsigned param_size() const
Definition DeclObjC.h:347
param_const_iterator param_end() const
Definition DeclObjC.h:358
param_const_iterator param_begin() const
Definition DeclObjC.h:354
bool isVariadic() const
Definition DeclObjC.h:431
const ParmVarDecl *const * param_const_iterator
Definition DeclObjC.h:349
Selector getSelector() const
Definition DeclObjC.h:327
bool isInstanceMethod() const
Definition DeclObjC.h:426
QualType getReturnType() const
Definition DeclObjC.h:329
Represents a pointer to an Objective C object.
Definition TypeBase.h:7903
bool isObjCQualifiedClassType() const
True if this is equivalent to 'Class.
Definition TypeBase.h:7984
const ObjCObjectPointerType * stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const
Strip off the Objective-C "kindof" type and (with it) any protocol qualifiers.
Definition Type.cpp:958
bool isObjCQualifiedIdType() const
True if this is equivalent to 'id.
Definition TypeBase.h:7978
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:8060
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:7940
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition TypeBase.h:7961
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:7915
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:7955
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:1840
qual_range quals() const
Definition TypeBase.h:8022
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition TypeBase.h:7967
Represents one property declaration in an Objective-C interface.
Definition DeclObjC.h:731
bool isReadOnly() const
isReadOnly - Return true iff the property has a setter.
Definition DeclObjC.h:838
static ObjCPropertyDecl * findPropertyDecl(const DeclContext *DC, const IdentifierInfo *propertyID, ObjCPropertyQueryKind queryKind)
Lookup a property by name in the specified DeclContext.
Definition DeclObjC.cpp:176
bool isOptional() const
Definition DeclObjC.h:916
SetterKind getSetterKind() const
getSetterKind - Return the method used for doing assignment in the property setter.
Definition DeclObjC.h:873
Selector getSetterName() const
Definition DeclObjC.h:893
QualType getType() const
Definition DeclObjC.h:804
Selector getGetterName() const
Definition DeclObjC.h:885
ObjCPropertyAttribute::Kind getPropertyAttributes() const
Definition DeclObjC.h:815
ObjCPropertyImplDecl - Represents implementation declaration of a property in a class or category imp...
Definition DeclObjC.h:2805
ObjCIvarDecl * getPropertyIvarDecl() const
Definition DeclObjC.h:2879
Represents an Objective-C protocol declaration.
Definition DeclObjC.h:2084
protocol_range protocols() const
Definition DeclObjC.h:2161
bool isGNUFamily() const
Is this runtime basically of the GNU family of runtimes?
Represents the declaration of an Objective-C type parameter.
Definition DeclObjC.h:578
ObjCTypeParamVariance getVariance() const
Determine the variance of this type parameter.
Definition DeclObjC.h:623
Stores a list of Objective-C type parameters for a parameterized class or a category/extension thereo...
Definition DeclObjC.h:662
A structure for storing the information associated with an overloaded template name.
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition ExprCXX.h:4357
Sugar for parentheses used when specifying types.
Definition TypeBase.h:3302
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3316
void clear()
Clear parent maps.
Represents a parameter to a function.
Definition Decl.h:1789
ObjCDeclQualifier getObjCDeclQualifier() const
Definition Decl.h:1853
QualType getOriginalType() const
Definition Decl.cpp:2955
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:8120
Pointer-authentication qualifiers.
Definition TypeBase.h:152
static PointerAuthQualifier Create(unsigned Key, bool IsAddressDiscriminated, unsigned ExtraDiscriminator, PointerAuthenticationMode AuthenticationMode, bool IsIsaPointer, bool AuthenticatesNullValues)
Definition TypeBase.h:239
bool isEquivalent(PointerAuthQualifier Other) const
Definition TypeBase.h:301
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3328
QualType getPointeeType() const
Definition TypeBase.h:3338
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3343
PredefinedSugarKind Kind
Definition TypeBase.h:8196
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
A (possibly-)qualified type.
Definition TypeBase.h:937
bool hasAddressDiscriminatedPointerAuth() const
Definition TypeBase.h:1457
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8369
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:2867
Qualifiers::GC getObjCGCAttr() const
Returns gc attribute of this type.
Definition TypeBase.h:8416
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8374
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition TypeBase.h:1296
QualType withConst() const
Definition TypeBase.h:1159
bool hasLocalQualifiers() const
Determine whether this particular QualType instance has any qualifiers, without looking through any t...
Definition TypeBase.h:1064
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8285
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8411
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8325
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1438
QualType getCanonicalType() const
Definition TypeBase.h:8337
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8379
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition TypeBase.h:8306
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8358
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1545
bool isCanonical() const
Definition TypeBase.h:8342
const Type * getTypePtrOrNull() const
Definition TypeBase.h:8289
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1332
PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const
Check if this is a non-trivial type that would cause a C struct transitively containing this type to ...
Definition Type.cpp:2990
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8317
Represents a template name as written in source code.
void Profile(llvm::FoldingSetNodeID &ID)
A qualifier set is used to build a set of qualifiers.
Definition TypeBase.h:8225
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8232
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
unsigned getCVRQualifiers() const
Definition TypeBase.h:488
void removeCVRQualifiers(unsigned mask)
Definition TypeBase.h:495
GC getObjCGCAttr() const
Definition TypeBase.h:519
void addAddressSpace(LangAS space)
Definition TypeBase.h:597
static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R)
Returns the common set of qualifiers while removing them from the given sets.
Definition TypeBase.h:384
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:361
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:354
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:350
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:364
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:367
void removeObjCLifetime()
Definition TypeBase.h:551
bool hasNonFastQualifiers() const
Return true if the set contains any qualifiers which require an ExtQuals node to be allocated.
Definition TypeBase.h:638
void addConsistentQualifiers(Qualifiers qs)
Add the qualifiers from the given set to this set, given that they don't conflict.
Definition TypeBase.h:689
void removeFastQualifiers(unsigned mask)
Definition TypeBase.h:624
bool hasUnaligned() const
Definition TypeBase.h:511
bool hasAddressSpace() const
Definition TypeBase.h:570
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B, const ASTContext &Ctx)
Returns true if address space A is equal to or a superset of B.
Definition TypeBase.h:708
unsigned getFastQualifiers() const
Definition TypeBase.h:619
void removeAddressSpace()
Definition TypeBase.h:596
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:603
bool hasObjCGCAttr() const
Definition TypeBase.h:518
uint64_t getAsOpaqueValue() const
Definition TypeBase.h:455
bool hasObjCLifetime() const
Definition TypeBase.h:544
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:545
bool empty() const
Definition TypeBase.h:647
void addObjCGCAttr(GC type)
Definition TypeBase.h:524
LangAS getAddressSpace() const
Definition TypeBase.h:571
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3633
bool isTrailingComment() const LLVM_READONLY
Returns true if it is a comment that should be put after a member:
SourceRange getSourceRange() const LLVM_READONLY
bool isDocumentation() const LLVM_READONLY
Returns true if this comment any kind of a documentation comment.
comments::FullComment * parse(const ASTContext &Context, const Preprocessor *PP, const Decl *D) const
Parse the comment, assuming it is attached to decl D.
Represents a struct/union/class.
Definition Decl.h:4309
bool isLambda() const
Determine whether this record is a class describing a lambda function object.
Definition Decl.cpp:5125
bool hasFlexibleArrayMember() const
Definition Decl.h:4342
field_range fields() const
Definition Decl.h:4512
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition Decl.cpp:5111
RecordDecl * getMostRecentDecl()
Definition Decl.h:4335
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition Decl.cpp:5170
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4493
bool field_empty() const
Definition Decl.h:4520
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3571
QualType getPointeeType() const
Definition TypeBase.h:3589
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3597
This table allows us to fully hide how we implement multi-keyword caching.
std::string getAsString() const
Derive the full selector name (e.g.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical, bool ProfileLambdaExpr=false) const
Produce a unique representation of the given statement.
The streaming interface shared between DiagnosticBuilder and PartialDiagnostic.
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1799
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, ArrayRef< SourceLocation > Locs)
This is the "fully general" constructor that allows representation of strings formed from one or more...
Definition Expr.cpp:1184
A structure for storing an already-substituted template template parameter pack.
Decl * getAssociatedDecl() const
A template-like entity which owns the whole pattern being substituted.
void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context)
TemplateTemplateParmDecl * getParameterPack() const
Retrieve the template template parameter pack being substituted.
TemplateArgument getArgumentPack() const
Retrieve the template template argument pack with which this parameter was substituted.
unsigned getIndex() const
Returns the index of the replaced parameter in the associated declaration.
A structure for storing the information associated with a substituted template template parameter.
void Profile(llvm::FoldingSetNodeID &ID)
TemplateTemplateParmDecl * getParameter() const
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3714
TagTypeKind TagKind
Definition Decl.h:3719
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition Decl.h:3945
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:4847
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:4840
bool isUnion() const
Definition Decl.h:3919
TagKind getTagKind() const
Definition Decl.h:3908
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Kind
The basic C++ ABI kind.
static Kind getKind(StringRef Name)
Exposes information about the current target.
Definition TargetInfo.h:226
TargetOptions & getTargetOpts() const
Retrieve the target options.
Definition TargetInfo.h:323
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
unsigned getMaxAtomicInlineWidth() const
Return the maximum width lock-free atomic operation which can be inlined given the supported features...
Definition TargetInfo.h:853
virtual LangAS getCUDABuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space.
virtual LangAS getOpenCLBuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space.
unsigned getDefaultAlignForAttributeAligned() const
Return the default alignment for attribute((aligned)) on this target, to be used if no alignment valu...
Definition TargetInfo.h:746
BuiltinVaListKind
The different kinds of __builtin_va_list types defined by the target implementation.
Definition TargetInfo.h:330
@ AArch64ABIBuiltinVaList
__builtin_va_list as defined by the AArch64 ABI http://infocenter.arm.com/help/topic/com....
Definition TargetInfo.h:339
@ PowerABIBuiltinVaList
__builtin_va_list as defined by the Power ABI: https://www.power.org /resources/downloads/Power-Arch-...
Definition TargetInfo.h:344
@ AAPCSABIBuiltinVaList
__builtin_va_list as defined by ARM AAPCS ABI http://infocenter.arm.com
Definition TargetInfo.h:353
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition TargetInfo.h:332
@ VoidPtrBuiltinVaList
typedef void* __builtin_va_list;
Definition TargetInfo.h:335
@ X86_64ABIBuiltinVaList
__builtin_va_list as defined by the x86-64 ABI: http://refspecs.linuxbase.org/elf/x86_64-abi-0....
Definition TargetInfo.h:348
virtual uint64_t getNullPointerValue(LangAS AddrSpace) const
Get integer value for null pointer.
Definition TargetInfo.h:502
static bool isTypeSigned(IntType T)
Returns true if the type is signed; false otherwise.
IntType getPtrDiffType(LangAS AddrSpace) const
Definition TargetInfo.h:404
IntType getSizeType() const
Definition TargetInfo.h:385
FloatModeKind getRealTypeByWidth(unsigned BitWidth, FloatModeKind ExplicitType) const
Return floating point type with specified width.
virtual IntType getIntTypeByWidth(unsigned BitWidth, bool IsSigned) const
Return integer type with specified width.
unsigned getMaxAlignedAttribute() const
Get the maximum alignment in bits for a static variable with aligned attribute.
Definition TargetInfo.h:970
virtual unsigned getMinGlobalAlign(uint64_t Size, bool HasNonWeakDef) const
getMinGlobalAlign - Return the minimum alignment of a global variable, unless its alignment is explic...
Definition TargetInfo.h:754
unsigned getTargetAddressSpace(LangAS AS) const
IntType getSignedSizeType() const
Definition TargetInfo.h:386
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
bool useAddressSpaceMapMangling() const
Specify if mangling based on address space map should be used or not for language specific address sp...
llvm::StringMap< bool > FeatureMap
The map of which features have been enabled disabled based on the command line.
A convenient class for passing around template argument information.
ArrayRef< TemplateArgumentLoc > arguments() const
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Location wrapper for a TemplateArgument.
Represents a template argument.
ArrayRef< TemplateArgument > getPackAsArray() const
Return the array of arguments in this template argument pack.
QualType getStructuralValueType() const
Get the type of a StructuralValue.
QualType getParamTypeForDecl() const
Expr * getAsExpr() const
Retrieve the template argument as an expression.
UnsignedOrNone getNumTemplateExpansions() const
Retrieve the number of expansions that a template template argument expansion will produce,...
QualType getAsType() const
Retrieve the type for a type template argument.
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
static TemplateArgument CreatePackCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument pack by copying the given set of template arguments.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
bool structurallyEquals(const TemplateArgument &Other) const
Determines whether two template arguments are superficially the same.
QualType getIntegralType() const
Retrieve the type of the integral value.
bool getIsDefaulted() const
If returns 'true', this TemplateArgument corresponds to a default template parameter.
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
ArrayRef< TemplateArgument > pack_elements() const
Iterator range referencing all of the elements of a template argument pack.
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
@ Template
The template argument is a template name that was provided for a template template parameter.
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
@ Pack
The template argument is actually a parameter pack.
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
@ Type
The template argument is a type.
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
ArgKind getKind() const
Return the kind of stored template argument.
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion,...
const APValue & getAsStructuralValue() const
Get the value of a StructuralValue.
The base class of all kinds of template declarations (e.g., class, function, etc.).
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
DeducedTemplateStorage * getAsDeducedTemplateName() const
Retrieve the deduced template info, if any.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
std::optional< TemplateName > desugar(bool IgnoreDeduced) const
OverloadedTemplateStorage * getAsOverloadedTemplate() const
Retrieve the underlying, overloaded function template declarations that this template name refers to,...
AssumedTemplateStorage * getAsAssumedTemplateName() const
Retrieve information on a name that has been assumed to be a template-name in order to permit a call ...
NameKind getKind() const
void * getAsVoidPointer() const
Retrieve the template name as a void pointer.
@ UsingTemplate
A template name that refers to a template declaration found through a specific using shadow declarati...
@ OverloadedTemplate
A set of overloaded template declarations.
@ Template
A single template declaration.
@ DependentTemplate
A dependent template name that has not been resolved to a template (or set of templates).
@ SubstTemplateTemplateParm
A template template parameter that has been substituted for some other template name.
@ SubstTemplateTemplateParmPack
A template template parameter pack that has been substituted for a template template argument pack,...
@ DeducedTemplate
A template name that refers to another TemplateName with deduced default arguments.
@ QualifiedTemplate
A qualified template name, where the qualification is kept to describe the source code as written.
@ AssumedTemplate
An unqualified-id that has been assumed to name a function template that will be found by ADL.
UsingShadowDecl * getAsUsingShadowDecl() const
Retrieve the using shadow declaration through which the underlying template declaration is introduced...
SubstTemplateTemplateParmPackStorage * getAsSubstTemplateTemplateParmPack() const
Retrieve the substituted template template parameter pack, if known.
SubstTemplateTemplateParmStorage * getAsSubstTemplateTemplateParm() const
Retrieve the substituted template template parameter, if known.
A template parameter object.
static void Profile(llvm::FoldingSetNodeID &ID, QualType T, const APValue &V)
Stores a list of template parameters for a TemplateDecl and its derived classes.
NamedDecl * getParam(unsigned Idx)
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
NamedDecl *const * const_iterator
Iterates through the template parameters in this list.
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
ArrayRef< NamedDecl * > asArray()
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
TemplateNameKind templateParameterKind() const
unsigned getPosition() const
Get the position of the template parameter within its parameter list.
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, bool ParameterPack, IdentifierInfo *Id, TemplateNameKind ParameterKind, bool Typename, TemplateParameterList *Params)
bool isParameterPack() const
Whether this template template parameter is a template parameter pack.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
Declaration of a template type parameter.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, UnsignedOrNone NumExpanded=std::nullopt)
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition ASTConcept.h:223
Expr * getImmediatelyDeclaredConstraint() const
Get the immediately-declared constraint expression introduced by this type-constraint,...
Definition ASTConcept.h:240
TemplateDecl * getNamedConcept() const
Definition ASTConcept.h:250
ConceptReference * getConceptReference() const
Definition ASTConcept.h:244
Represents a declaration of a type.
Definition Decl.h:3510
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition TypeLoc.h:78
static unsigned getFullDataSizeForType(QualType Ty)
Returns the size of type source info data block for the given type.
Definition TypeLoc.cpp:95
void initialize(ASTContext &Context, SourceLocation Loc) const
Initializes this to state that every location in this type is the given location.
Definition TypeLoc.h:216
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition TypeBase.h:6175
A container of type source information.
Definition TypeBase.h:8256
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:272
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isBlockPointerType() const
Definition TypeBase.h:8542
bool isVoidType() const
Definition TypeBase.h:8878
bool isObjCBuiltinType() const
Definition TypeBase.h:8742
QualType getRVVEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an RVV builtin type.
Definition Type.cpp:2678
bool isIncompleteArrayType() const
Definition TypeBase.h:8629
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2205
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isConstantArrayType() const
Definition TypeBase.h:8625
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2426
bool isArrayType() const
Definition TypeBase.h:8621
bool isCharType() const
Definition Type.cpp:2132
bool isPointerType() const
Definition TypeBase.h:8522
bool isArrayParameterType() const
Definition TypeBase.h:8637
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8922
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9165
bool isSignedFixedPointType() const
Return true if this is a fixed point type that is signed according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8962
bool isEnumeralType() const
Definition TypeBase.h:8653
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8712
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:752
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:8996
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2899
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2790
bool isBitIntType() const
Definition TypeBase.h:8787
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8645
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2782
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8934
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8950
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2405
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3119
@ PtrdiffT
The "ptrdiff_t" type.
Definition TypeBase.h:2281
@ SizeT
The "size_t" type.
Definition TypeBase.h:2275
@ SignedSizeT
The signed integer type corresponding to "size_t".
Definition TypeBase.h:2278
bool isObjCIdType() const
Definition TypeBase.h:8724
bool isUnsaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8958
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9151
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2436
bool isFunctionType() const
Definition TypeBase.h:8518
bool isObjCObjectPointerType() const
Definition TypeBase.h:8691
bool isUnsignedFixedPointType() const
Return true if this is a fixed point type that is unsigned according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8976
bool isVectorType() const
Definition TypeBase.h:8661
bool isObjCClassType() const
Definition TypeBase.h:8730
bool isRVVVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'riscv_rvv_vector_bits' type attribute,...
Definition Type.cpp:2660
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2595
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2921
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition Type.cpp:2253
bool isAnyPointerType() const
Definition TypeBase.h:8530
TypeClass getTypeClass() const
Definition TypeBase.h:2385
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2411
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9098
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:653
bool isNullPtrType() const
Definition TypeBase.h:8915
bool isRecordType() const
Definition TypeBase.h:8649
bool isObjCRetainableType() const
Definition Type.cpp:5291
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5022
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3664
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5633
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3559
QualType getUnderlyingType() const
Definition Decl.h:3614
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType Underlying)
Definition TypeBase.h:6119
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition DeclCXX.h:4455
static void Profile(llvm::FoldingSetNodeID &ID, QualType Ty, const APValue &APVal)
Definition DeclCXX.h:4483
The iterator over UnresolvedSets.
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition TypeBase.h:5980
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UnresolvedUsingTypenameDecl *D)
Definition TypeBase.h:6017
Represents a dependent using declaration which was marked with typename.
Definition DeclCXX.h:4037
UnresolvedUsingTypenameDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this declaration.
Definition DeclCXX.h:4102
Represents a C++ using-enum-declaration.
Definition DeclCXX.h:3792
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3399
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3463
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition DeclCXX.cpp:3374
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UsingShadowDecl *D, QualType UnderlyingType)
Definition TypeBase.h:6057
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:711
void setType(QualType newType)
Definition Decl.h:723
QualType getType() const
Definition Decl.h:722
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5453
void clear()
Definition Value.cpp:216
Represents a variable declaration or definition.
Definition Decl.h:925
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2810
bool hasInit() const
Definition Decl.cpp:2398
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a static data member.
Definition Decl.cpp:2461
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1282
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1207
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition Decl.cpp:2772
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1550
@ DeclarationOnly
This declaration is only a declaration.
Definition Decl.h:1294
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition Decl.cpp:2375
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition Decl.cpp:2779
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:3964
Expr * getSizeExpr() const
Definition TypeBase.h:3978
Represents a GCC generic vector type.
Definition TypeBase.h:4173
unsigned getNumElements() const
Definition TypeBase.h:4188
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4197
VectorKind getVectorKind() const
Definition TypeBase.h:4193
QualType getElementType() const
Definition TypeBase.h:4187
A full comment attached to a declaration, contains block content.
Definition Comment.h:1104
ArrayRef< BlockContentComment * > getBlocks() const
Definition Comment.h:1142
const DeclInfo * getDeclInfo() const LLVM_READONLY
Definition Comment.h:1136
const Decl * getDecl() const LLVM_READONLY
Definition Comment.h:1132
Holds all information required to evaluate constexpr code in a module.
Definition Context.h:41
Defines the Linkage enumeration and various utility functions.
Defines the clang::TargetInfo interface.
Definition SPIR.cpp:47
mlir::Type getBaseType(mlir::Value varPtr)
const AstTypeMatcher< TagType > tagType
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< ArrayType > arrayType
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus17
GVALinkage
A more specific kind of linkage than enum Linkage.
Definition Linkage.h:72
@ GVA_StrongODR
Definition Linkage.h:77
@ GVA_StrongExternal
Definition Linkage.h:76
@ GVA_AvailableExternally
Definition Linkage.h:74
@ GVA_DiscardableODR
Definition Linkage.h:75
@ GVA_Internal
Definition Linkage.h:73
AutoTypeKeyword
Which keyword(s) were used to create an AutoType.
Definition TypeBase.h:1792
OpenCLTypeKind
OpenCL type kinds.
Definition TargetInfo.h:212
@ OCLTK_ReserveID
Definition TargetInfo.h:219
@ OCLTK_Sampler
Definition TargetInfo.h:220
@ OCLTK_Pipe
Definition TargetInfo.h:217
@ OCLTK_ClkEvent
Definition TargetInfo.h:214
@ OCLTK_Event
Definition TargetInfo.h:215
@ OCLTK_Default
Definition TargetInfo.h:213
@ OCLTK_Queue
Definition TargetInfo.h:218
FunctionType::ExtInfo getFunctionExtInfo(const Type &t)
Definition TypeBase.h:8420
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
NullabilityKind
Describes the nullability of a particular type.
Definition Specifiers.h:348
@ Nullable
Values of this type can be null.
Definition Specifiers.h:352
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
Definition Specifiers.h:357
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:350
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:272
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
std::pair< FileID, unsigned > FileIDAndOffset
CXXABI * CreateMicrosoftCXXABI(ASTContext &Ctx)
@ Vector
'vector' clause, allowed on 'loop', Combined, and 'routine' directives.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
TypeOfKind
The kind of 'typeof' expression we're after.
Definition TypeBase.h:918
@ AS_public
Definition Specifiers.h:124
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ SC_Register
Definition Specifiers.h:257
@ SC_Static
Definition Specifiers.h:252
CXXABI * CreateItaniumCXXABI(ASTContext &Ctx)
Creates an instance of a C++ ABI class.
const StreamingDiagnostic & operator<<(const StreamingDiagnostic &DB, const ASTContext::SectionInfo &Section)
Insertion operator for diagnostics.
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition Linkage.h:24
@ External
External linkage, which indicates that the entity can be referred to from other translation units.
Definition Linkage.h:58
@ Result
The result type of a method or function.
Definition TypeBase.h:905
@ TypeAlignment
Definition TypeBase.h:76
ArraySizeModifier
Capture whether this is a normal array (e.g.
Definition TypeBase.h:3717
const FunctionProtoType * T
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
@ Template
We are parsing a template declaration.
Definition Parser.h:81
@ Interface
The "__interface" keyword.
Definition TypeBase.h:5893
@ Struct
The "struct" keyword.
Definition TypeBase.h:5890
@ Class
The "class" keyword.
Definition TypeBase.h:5899
constexpr uint16_t SelPointerConstantDiscriminator
Constant discriminator to be used with objective-c sel pointers.
bool isDiscardableGVALinkage(GVALinkage L)
Definition Linkage.h:80
BuiltinTemplateKind
Kinds of BuiltinTemplateDecl.
Definition Builtins.h:462
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:559
LangAS
Defines the address space values used by the address space qualifier of QualType.
TranslationUnitKind
Describes the kind of translation unit being processed.
FloatModeKind
Definition TargetInfo.h:75
bool isPtrSizeAddressSpace(LangAS AS)
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:139
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1288
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:202
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:191
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:278
@ CC_M68kRTD
Definition Specifiers.h:299
@ CC_X86RegCall
Definition Specifiers.h:287
@ CC_X86VectorCall
Definition Specifiers.h:283
@ CC_X86StdCall
Definition Specifiers.h:280
@ CC_X86FastCall
Definition Specifiers.h:281
@ Invariant
The parameter is invariant: must match exactly.
Definition DeclObjC.h:555
@ Contravariant
The parameter is contravariant, e.g., X<T> is a subtype of X when the type parameter is covariant and...
Definition DeclObjC.h:563
@ Covariant
The parameter is covariant, e.g., X<T> is a subtype of X when the type parameter is covariant and T i...
Definition DeclObjC.h:559
@ AltiVecBool
is AltiVec 'vector bool ...'
Definition TypeBase.h:4143
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
Definition TypeBase.h:4152
@ AltiVecPixel
is AltiVec 'vector Pixel'
Definition TypeBase.h:4140
@ Generic
not a target-specific vector type
Definition TypeBase.h:4134
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
Definition TypeBase.h:4158
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
Definition TypeBase.h:4161
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
Definition TypeBase.h:4155
U cast(CodeGen::Address addr)
Definition Address.h:327
LangAS getLangASFromTargetAS(unsigned TargetAS)
AlignRequirementKind
Definition ASTContext.h:176
@ None
The alignment was not explicit in code.
Definition ASTContext.h:178
@ RequiredByEnum
The alignment comes from an alignment attribute on a enum type.
Definition ASTContext.h:187
@ RequiredByTypedef
The alignment comes from an alignment attribute on a typedef.
Definition ASTContext.h:181
@ RequiredByRecord
The alignment comes from an alignment attribute on a record type.
Definition ASTContext.h:184
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition TypeBase.h:5863
@ Interface
The "__interface" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5868
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5884
@ Struct
The "struct" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5865
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5874
@ Union
The "union" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5871
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5877
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:5881
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
@ EST_DependentNoexcept
noexcept(expression), value-dependent
@ EST_Uninstantiated
not instantiated yet
@ EST_Unparsed
not parsed yet
@ EST_NoThrow
Microsoft __declspec(nothrow) extension.
@ EST_None
no exception specification
@ EST_MSAny
Microsoft throw(...) extension.
@ EST_BasicNoexcept
noexcept
@ EST_NoexceptFalse
noexcept(expression), evals to 'false'
@ EST_Unevaluated
not evaluated yet, for special member function
@ EST_NoexceptTrue
noexcept(expression), evals to 'true'
@ EST_Dynamic
throw(T1, T2)
unsigned long uint64_t
unsigned NumTemplateArgs
The number of template arguments in TemplateArgs.
const Expr * ConstraintExpr
Definition Decl.h:87
UnsignedOrNone ArgPackSubstIndex
Definition Decl.h:88
Copy initialization expr of a __block variable and a boolean flag that indicates whether the expressi...
Definition Expr.h:6604
Expr * getCopyExpr() const
Definition Expr.h:6611
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
ArrayRef< TemplateArgument > Args
Holds information about the various types of exception specification.
Definition TypeBase.h:5321
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5323
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition TypeBase.h:5326
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition TypeBase.h:5329
Extra information about a function prototype.
Definition TypeBase.h:5349
bool requiresFunctionProtoTypeArmAttributes() const
Definition TypeBase.h:5395
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5354
bool requiresFunctionProtoTypeExtraAttributeInfo() const
Definition TypeBase.h:5399
bool requiresFunctionProtoTypeExtraBitfields() const
Definition TypeBase.h:5388
const IdentifierInfo * getIdentifier() const
Returns the identifier to which this template name refers.
OverloadedOperatorKind getOperator() const
Return the overloaded operator to which this template name refers.
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition Type.cpp:3259
A lazy value (of type T) that is within an AST node of type Owner, where the value might change in la...
Contains information gathered from parsing the contents of TargetAttr.
Definition TargetInfo.h:60
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition TypeBase.h:870
const Type * Ty
The locally-unqualified type.
Definition TypeBase.h:872
Qualifiers Quals
The local qualifiers.
Definition TypeBase.h:875
llvm::DenseSet< std::tuple< Decl *, Decl *, int > > NonEquivalentDeclSet
Store declaration pairs already found to be non-equivalent.
bool IsEquivalent(Decl *D1, Decl *D2)
Determine whether the two declarations are structurally equivalent.
A this pointer adjustment.
Definition Thunk.h:92
IntType
===-— Target Data Type Query Methods ----------------------------—===//
Definition TargetInfo.h:146
AlignRequirementKind AlignRequirement
Definition ASTContext.h:207
bool isAlignRequired()
Definition ASTContext.h:199
AlignRequirementKind AlignRequirement
Definition ASTContext.h:193
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